subjects studied so far? procedural to object oriented

158
Subjects Studied so far? Procedural to object oriented.. What is a Programming Language? Natural Language , is it capable? Example of College administration process.. Calculation of limits and integration.. On what bases it is decided? The model provided by a programming language to discuss concepts, formulate algorithms or structure, and reason about problem solutions.

Upload: others

Post on 15-Apr-2022

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Subjects Studied so far? Procedural to object oriented

• Subjects Studied so far?• Procedural to object oriented..•What is a Programming Language?•Natural Language , is it capable?•Example of College administration process..•Calculation of limits and integration..•On what bases it is decided?•The model provided by a programming

language to discuss concepts, formulate algorithms or structure, and reason about problem solutions.

Page 2: Subjects Studied so far? Procedural to object oriented

Principles of Programming Languages

Page 3: Subjects Studied so far? Procedural to object oriented

Prerequisite: Data Structures & Algorithms and Object Oriented Programming

Course Objectives:

  1 To Understand fundamental principles of programming language 2 To understand structural, computational and logical implications regarding programming languages 3 To explore main programming paradigms 4 To understand and apply Object Oriented Programming (OOP) principles using C++ and Java Course Outcomes:

On completion of the course, student will be able to– 1 Write a survey on analysis of the strengths and weaknesses of programming languages for effective and efficient program development.2 To inculcate the principles underlying the programming languages enabling to learn new programming languages.3 To recognize and discuss different programming paradigms 4 To apply the programming paradigms effectively in application development followed by demonstration and a case study.

Page 4: Subjects Studied so far? Procedural to object oriented

Introduction• Purpose of Studying this Subject• What should you expect to get out of this course• Study of Programming Language• Programming Language Concepts

What is programming languageWhy Are There So Many Programming LanguagesTypes of programming languages.

• Why Study programming language• A short history of programming language• Influences on programming language• Attributes of good language.

Page 5: Subjects Studied so far? Procedural to object oriented

1. Purpose of Studying PPL

The purpose of the course is for the student to gain knowledge

of important principles in programming languages

and for the student to gain an understanding of techniques for

describing and compiling programming languages.

Page 6: Subjects Studied so far? Procedural to object oriented

2. What should you expect to get out of this course

Ideas, principles and techniques to help you

–Design your own programming language or design

your own extensions to an existing language

–Lots of knowledge about programming languages

–Tools and techniques to implement a compiler or an

interpreter

Page 7: Subjects Studied so far? Procedural to object oriented

3. The Study of Programming Languages

The purpose of language is simply that it must convey

meaning. (Confucius)

That which can be said, clearly. (Wittgenstein,1963)

A program is a specification of a computation. A programming

language is a notation for writing programs.(Sethi,89)

Page 8: Subjects Studied so far? Procedural to object oriented

4. Programming Language Concepts

What is a programming language?Why are there so many programming languages?What are the types of programming languages?Does the world need new languages?

Page 9: Subjects Studied so far? Procedural to object oriented

What is a Programming Languages

A programming language is a set of rules that provides a way of telling a computer what operations to perform.

A programming language is a set of rules for communicating an algorithm

It provides a linguistic framework for describing computations

Page 10: Subjects Studied so far? Procedural to object oriented

What is a Programming Language

English is a natural language. It has words, symbols and grammatical rules.

A programming language also has words, symbols and rules of grammar.

The grammatical rules are called syntax.Each programming language has a different set of syntax

rules.

Page 11: Subjects Studied so far? Procedural to object oriented

Definition of Programming language

A language that is intended for the expression of computer programs and that is capable of expressing any computer program.

Page 12: Subjects Studied so far? Procedural to object oriented

Why There Are So Many Programming Languages

Programming languages have evolved over time as better ways have been developed to design them.

First programming languages were developed in the 1950sSince then thousands of languages have been developed

Different programming languages are designed for different types of programs.

Productivity, Performance and Generality.

Page 13: Subjects Studied so far? Procedural to object oriented

Levels of Programming LanguagesHigh-level program class Triangle {

... float surface() return b*h/2; }

Low-level program LOAD r1,bLOAD r2,hMUL r1,r2DIV r1,#2RET

Executable Machine code 0001001001000101001001001110110010101101001...

Page 14: Subjects Studied so far? Procedural to object oriented

Does the world need new Languages??

Page 15: Subjects Studied so far? Procedural to object oriented

5. Why study programming languages?

Programming languages are important for students in all disciplines of

computer science because they are the primary tools of the central

activity of computer science programming.

There is an idea: the structure of language defines the boundaries of thought.

Increased capacity to express ideas

Improved background for choosing appropriate languages

Increased ability to learn new languages

Better understanding of the significance of implementation

Increased ability to design new languages

Background for compiler writing

Page 16: Subjects Studied so far? Procedural to object oriented

To improve your ability to develop effective algorithms and to

improve your use of your existing programming language.

O-O features, recursion

Call by value, call by reference

To increase your vocabulary of useful programming constructs.

To allow a better choice of programming languages.

Page 17: Subjects Studied so far? Procedural to object oriented

A short history of programming Languages

• 1950 : LISP, FORTRAN• 1970 : Ada, C, Pascal, Prolog, Smalltalk• 1980 : C++

• During 1970 : a lot of PLs were designed.• Early languages:–Numerically based languages. (FORTRAN:55,ALGOL:58)–Business languages. (COBOL:60)–Artificial intelligence languages. (LISP,Prolog)–Systems languages. ( C:70)

Page 18: Subjects Studied so far? Procedural to object oriented

A short history of programming languages (cont.)

• 80s:–Development of functional programming: ML, Miranda–Need for reliability and maintainability: Ada–Object-oriented programming: Smalltalk, C++• 90s:–Fourth-generation languages–Productivity tools (such as spreadsheets)–Visual languages : Delphi–Scripting languages : Perl–Expert systems shells–Network computing : Java

Page 19: Subjects Studied so far? Procedural to object oriented

Unit 1Programming Language Syntax and Semantics

Page 20: Subjects Studied so far? Procedural to object oriented

Contents Software development processLanguages and software development environments

Languages and software design methods Languages and computer architecture.

Programming language qualities Languages and reliability Languages and maintainability Languages and

efficiency A brief historical perspective A bird’s eye view of programming language

Page 21: Subjects Studied so far? Procedural to object oriented

Software Development Process• Splits the software development work into different phases

containing activities for the purpose of better planning and management.

• SDLC method are : Waterfall modelPrototyping model Iterative model Incremental development Rapid application development model Spiral development and many other types of Agile methodology.

• Software Development process designs, develops and tests high quality software. The goal of this process is to fulfil the customer requirements, provide better quality software and on time delivery of product.

• Software organizations use this SDLC process for completion and execution of process. It consists of detailed planning that how to develop software, how to maintain, and what up gradation will be required

Page 22: Subjects Studied so far? Procedural to object oriented

SDLC ModelsWaterfall Model Design

Waterfall approach was first SDLC Model to be used widely in Software Engineering to ensure success of the project.

As the name is “The Waterfall”, in this approach, the whole software development process is divided into different phases.

In Waterfall model, normally, the output of first phase is given as input to the second phase and so on.

This means execution takes place in sequential manner.

Page 23: Subjects Studied so far? Procedural to object oriented
Page 24: Subjects Studied so far? Procedural to object oriented

Waterfall ModelRequirement Gathering and analysis : In this phase, all the

requirements are gathered from the sources and they are documented in requirement specific document.

System Design : In this phase, the requirement specifications from first phase are studied and system design is prepared. This System Design helps to identify hardware required and overall system architecture is also defined.

Implementation : The system first develops small modules or programs using the input from system design, these small modules are called as units. In next phase, the units are integrated. Each developed unit is then tested for its functionality which is referred as Unit Testing.

Page 25: Subjects Studied so far? Procedural to object oriented

Waterfall Model cont..

Integration and Testing : The small units developed and tested in implementation phase are integrated into system. Again the integrated unit is tested for faults and failures.

Deployment of system : Once the functional and non functional testing is done, the product is deployed in the customer environment or released into the market.

Maintenance : After the product is deployed, chances are that some problems may arise at client side environment. In order to fix those issues maintenance phase is required which releases patches. Also to enhance the product some better versions are released. To deliver these changes to client maintenance is done.

Page 26: Subjects Studied so far? Procedural to object oriented

Advantages :

Simple and easyEasily manageable , each phase has specific deliverables.One phase at a time Smaller projects.

Disadvantages:

Difficult to go back and change in previous phase.High risk and uncertainty.Not good idea for large and complex projects.

When to use:

This model is used when requirements are fixed and not ambiguous for short projects.

Page 27: Subjects Studied so far? Procedural to object oriented

• A variation in the representation of waterfall model is called the V – model.

Page 28: Subjects Studied so far? Procedural to object oriented

The high-level design (HLD): system architecture and design. It provide overview of solution, platform, system, product and service/process.

An integration test plan is created in this phase as well in order to test the pieces of the software systems ability to work together.

The low-level design (LLD) phase is where the actual software components are designed. It defines the actual logic for each and every component of the system. Class diagram with all the methods and relation between classes comes under LLD. Component tests are created in this phase as well.

Advantages of V-model:

Simple and easy to use.Testing activities like planning, test designing happens well

before coding. This saves a lot of time. Hence higher chance of success over the waterfall model.

Proactive defect tracking – that is defects are found at early stage.

Avoids the downward flow of the defects.Works well for small projects where requirements are easily

understood.

Page 29: Subjects Studied so far? Procedural to object oriented

Disadvantages of V-model:

Very rigid and least flexible.Software is developed during the implementation phase, so no early

prototypes of the software are produced.If any changes happen in midway, then the test documents along with

requirement documents has to be updated.

When to use the V-model:The V-shaped model should be used for small to medium sized

projects where requirements are clearly defined and fixed.The V-Shaped model should be chosen when ample technical

resources are available with needed technical expertise.

Page 30: Subjects Studied so far? Procedural to object oriented

PLs as Components of a Software Development Environment

• Goal: software productivity

• Need: support for all phases of SD

• Computer-aided tools (“Software Tools”)– Text and program editors, compilers, linkers, libraries, formatters,

pre-processors– E.g., Unix (shell, pipe, redirection)

• Software development environments– E.g., Interlisp, Jbuilder

• Intermediate approach:– Emacs (customizable editor to lightweight SDE)

Page 31: Subjects Studied so far? Procedural to object oriented

Languages and Software Development EnvironmentsEnvironment refers to the group of hardware and software tools used by a

system developer to build software.

Coding is the mainly supported with tools such as compilers, linkers, text editors and libraries.

Though both software development environment and programming environment are considered as a same, in this context, there is difference between these two phrases.

“Programming environment” is the atmosphere that supports coding phase of SDL cycle. It only facilitates the small tasks like editing, compiling etc.

“Software development environment” supports various activities of SDL cycle like configuration management, project management, team management.

Page 32: Subjects Studied so far? Procedural to object oriented

Pl’s and Software Design Methodology

A methodology can be defined as the basic ethics and rules that govern a system.

Software designers are guided by different design methodologyEg: for decomposing a system into modules, procedural design methods are used.Object oriented methods decomposes a system into classes and object.

Different methodologies support works in different phases of the system life cycle, for example, planning, analysis, design and programming, testing and implementation.

Page 33: Subjects Studied so far? Procedural to object oriented

Some design methods are better supported by some programming languages.

Some of the older languages are not well-suited for particular design methods.

For example : a method which requires every task to be accomplished using objects, can use c++ or java.

and top down method can use pascal or c.Most of the time programming languages impose particular

programming style. These styles are called as programming paradigms. These paradigms impacts the relationship between design

method and programming languages. We can classify programming languages as per the computer

programming style with the help of programming paradigm notion.

Page 34: Subjects Studied so far? Procedural to object oriented

Computer Architecture and PLs

The Von Neumann architecture, given in figure 2, is in accordance with the idea of a CPU, an I/O unit and memory to store data, instructions.

Page 35: Subjects Studied so far? Procedural to object oriented

Conventional languages based on the Von Neumann computation model are often called imperative languages. The historical developments of imperative languages have gone through increasingly higher levels of abstractions.

Few languages like, Functional and logical languages have discarded the Von Neumann computation model. Both paradigms follow the mathematical foundations instead of hardware technology: the theory of recursive functions and mathematical logic.

The different underlying computation model of the language is reflected by imperative, functional and logic paradigms. Different organizational principles for program structuring are reflected by next level paradigms which are supported by the language.

Page 36: Subjects Studied so far? Procedural to object oriented
Page 37: Subjects Studied so far? Procedural to object oriented

Other Computer Architectures

• Harvard– separate data and program memories• Functional architectures–Symbolics, Lambda machine, Mago’s reduction machine• Logic architectures–Fifth generation computer project (1982-1992) and the

PIM• Overall, alternate computer architectures have failed

commercially– von Neumann machines get faster too quickly!

Page 38: Subjects Studied so far? Procedural to object oriented

Influences on programming languages

• Computer capabilities–Hardware and OS• Applications–Wide area of applications (open mp,cuda,scala..)• Programming methods–Multiprogramming, interactive systems, data abstraction,

formal semantics,O-O programming,…• Implementation methods • Theoretical studies• Standardization

Page 39: Subjects Studied so far? Procedural to object oriented

Attributes of a good language

• Clarity, simplicity, and unity–Have a minimum number of different concepts, with the rules

for their combination, simple and regular (conceptual integrity).– readability• Orthogonality–Being able to combine various features of a language in all

possible combinations.• Naturalness for the application• Support for abstraction

Page 40: Subjects Studied so far? Procedural to object oriented

Attributes of a good language

• Ease of program verificationProof of correctness, desk checking, testSimplicity of semantic and syntax• Programming environment• Portability of programs• Cost of useProgram executionProgram translationProgram creation, testing, and useProgram maintenance

Page 41: Subjects Studied so far? Procedural to object oriented

Programming language qualities

Software must be reliable.Software must be maintainable.Software must execute efficiently

Page 42: Subjects Studied so far? Procedural to object oriented

Attributes of a good language (another view: to make a software reliable, maintainable,

efficient)• Reliability–Writability–Readability–Simplicity–Safety (no goto, no pointers)–Robustness (undesired events can be trapped, like arithmetic

overflow, invalid inputs)• Maintainability–Factoring (modularity, appropriate names for constants)–Locality• Efficiency (Execution Speed, Space, Reusable, Portable)

Page 43: Subjects Studied so far? Procedural to object oriented

Languages and reliability

WritabilityReadabilitySimplicitySafetyRobustness

Page 44: Subjects Studied so far? Procedural to object oriented

Languages and maintainability

Easily modifiable.Readability and simplicity are obviously important in this

contextTwo main features:

Factoring:This means that the language should allow programmers to

factor related features into one single pointIn doing so, the program becomes more readable and more

easily modifiable.As another example, several programming languages allow

constants to be given symbolic names. Choosing an appropriate name for a constant promotes readability of the program (e.g., we may use pi instead of 3.14).

Page 45: Subjects Studied so far? Procedural to object oriented

Locality:

This means that the effect of a language feature is restricted to a small, local portion of the entire program. Otherwise, if it extends to most of the program, the task of making the change can be exceedingly complex.

Page 46: Subjects Studied so far? Procedural to object oriented

Languages and Efficiency

Efficiency can be achieved by: More execution speedLess memory consumption Efficiency is no longer measured only by the execution speed and space. The effort required to produce a program or system initially and the effort required in maintenance can also be viewed as components of the efficiency measure.ReusabilityPortability

Page 47: Subjects Studied so far? Procedural to object oriented

What makes a successful language?

The following key characteristics:–Simplicity and readability–Clarity about binding–Reliability–Abstraction–Orthogonality–Efficient implementation

Page 48: Subjects Studied so far? Procedural to object oriented

Simplicity and Readability

• Small instruction set–E.g., Java vs Scheme• Simple syntax–E.g., C/C++/Java vs Python• Benefits:–Ease of learning–Ease of programming

Page 49: Subjects Studied so far? Procedural to object oriented

A language element is bound to a property at the time that property is defined for it.So a binding is the association between an object and a property of that object–Examples: • a variable and its type• a variable and its value–Early binding takes place at compile-time–Late binding takes place at run time

Clarity about Binding

Page 50: Subjects Studied so far? Procedural to object oriented

Reliability

A language is reliable if:–Program behavior is the same on different platforms• E.g., early versions of Fortran–Type errors are detected• E.g., C vs Haskell–Semantic errors are properly trapped• E.g., C vs C++–Memory leaks are prevented• E.g., C vs Java

Page 51: Subjects Studied so far? Procedural to object oriented

Abstraction in Programming

•Data–Programmer-defined types/classes–Class libraries• Procedural–Programmer-defined functions–Standard function libraries

Page 52: Subjects Studied so far? Procedural to object oriented

OrthogonalityDefining: orthogonality in a programming language means that a relatively small set of primitive constructs can be combined in a relatively small number of ways to build the control and data structures of the language It is associated with simplicity; the more orthogonal the design, the fewer exceptions.

In programming languages this means that when you execute an instruction, nothing but that instruction happens (very important for debugging).

Page 53: Subjects Studied so far? Procedural to object oriented

Efficient implementation

•Embedded systems–Real-time responsiveness (e.g., navigation)–Failures of early Ada implementations•Web applications–Responsiveness to users (e.g., Google search)•Corporate database applications–Efficient search and updating•AI applications–Modeling human behaviors

Page 54: Subjects Studied so far? Procedural to object oriented

A bird’s eye view of programming language concepts

Using a simple C/C++ program as an example, we look at the kinds of facilities that a programming language must support and the different ways that languages go about providing these facilities.1.Simple Program2.Syntax & Semantics3.Semantic elements4.Program Organization5.Program data and algorithm

• Looking to the program, we want to look at not what it does, but what kinds of linguistic facilities were used to write the program.

Page 55: Subjects Studied so far? Procedural to object oriented

The line extern phone_list pb; indicates that the variable pb of type phone_list is being used in this program

The third part, It contains the program’s data and algorithms

the routines insert and lookup are used in the main program

the output statement: cout << “Enter 1 to insert, 2 to lookup: \

n”;which uses cout, the standard output device defined in the

standard input-output library iostream.h included in the first line of

the program.

Bird eye view of PL concepts

Page 56: Subjects Studied so far? Procedural to object oriented

• The syntax rules of the language state how to form expressions,

statements, and programs that look right

• The semantic rules of the language tell us how to build meaningful

expressions, statements, and programs

• the declaration of a variable such as request causes storage to be

reserved for the variable.

• the presence of the extern in the declaration of the variable pb

indicates that the storage is reserved by some other module and not this

one

Page 57: Subjects Studied so far? Procedural to object oriented

#include <iostream.h>#include “phone.h”

extern phone_list pb;void insert();number lookup ();

main(){int request;cout << “Enter 1 to insert, 2 to lookup: \n”;cin >> request;if (request == 1)insert();else if (request == 2)cout << lookup();else{cout << “invalid request.\n”;exit (1);}}

is used to organize the structure of the program

Environment consists of three “declaration” statements

Computation

the actual code of a function

Page 58: Subjects Studied so far? Procedural to object oriented

Syntax and semantics

Syntax explains the structure of programs and semantics describes the relationship between the syntax and the computational model.

The syntax of programming language is closely related to the computational model, in order to simplify the task of reasoning about programs. The key principle is the principle of clarity.

Page 59: Subjects Studied so far? Procedural to object oriented

Semantic elements

Variables1. A Name 2. A Type3. A Value 4. A Scope1.A Life Time

Page 60: Subjects Studied so far? Procedural to object oriented

• Semantic elements Variables• A variable corresponds to a region of memory which is used to holdvalues that are manipulated by the program.

semantic properties of variables areScope which part of the program has access to the variable?Type what kinds of values may be stored in the variable and what

operations may be performed on the variable?Lifetime when is the variable created and when is it discarded?• static variables live throughout the execution of the programValues and references• An assignment statement of the form:

x = y; The value referred to by the name y is of a different kind from that referred to by the name x.

Page 61: Subjects Studied so far? Procedural to object oriented

right hand side of this assignment statement, we need the contents of that memory

left hand side we need the address of, or a reference to, that regionan l-value is a value that refers to a memory locationan r-value is a value that refers to the contents of a memory location

x = &y; stores the address of y into x.3 = y; //error, left-hand side requires l-value

is an error because literals in C++ do not have l-values.

Instead, y = 3;

Page 62: Subjects Studied so far? Procedural to object oriented

Expressions• Expressions are syntactic constructs that allow the programmer to

combine values and operations to compute new valuesex: request == 1, is an expression of type boolean“invalid request.\n” is an expression of type string

the order in which operations are performed in an expression may influence the value of the expression

• Consider: a = b = c + d;• P = a=b=c=c+d/c

• Program organizationa file called iostream.h, which provides the declarations to use the

standard inputoutput library provided by C/C++.

Page 63: Subjects Studied so far? Procedural to object oriented

The other file included by the program is called phone.h. This file is presumably more specific to this application and contains information, such as type definitions, that are shared by different modules of the program

• Program data and algorithmsthe main program consists of some variable declarations and some

statements that operate on these variables.The execution of statements modifies the values stored in the memory

of the underlying machine; i.e., it modifies the state of the computation

Page 64: Subjects Studied so far? Procedural to object oriented
Page 65: Subjects Studied so far? Procedural to object oriented

Syntax and Semantics

Language Definition

Syntax :Semantics :Pragmatics:It hints at characteristics of language, which are related to language users; e.g. utility or scope of application, its effect on user etc. For programming languages, it includes points such as implementation ease, efficient application and programming methodology.

Page 66: Subjects Studied so far? Procedural to object oriented

Syntax• The syntax does not inform us anything regarding the substance (or

significance) of the sentence– the semantic guidelines let us know that.

• For instance, C , (for example, while, do, if, else,...), identifiers, numbers, operators, ... are words of the language. The C syntax lets us know how to join such words to develop all around shaped statements and programs.

• The language syntax is characterized by two arrangements of rules: lexical and syntactic rules.

• Lexical principles determine the arrangement of characters that constitute the alphabets of language and the way such characters can be joined to shape legitimate words.

Page 67: Subjects Studied so far? Procedural to object oriented

Syntax and Semantics• Syntax – form or structure of expressions or

statements for a given language• For instance, in Java, the form of

a while loop is– while(<bool_expr) <stmt>

• Semantics – meaning of the expressions

• Language – group of words that can be

combined and the rules for combining those words

• Sentence – a legal statement in the language

• Lexeme – lowest level syntactic unit in the

language• Token – a language category for the lexemes

Example (in Java): index = 2 * count + 17;

Lexeme: Token: index identifier = assignment_operator 2 integer_literal * mult_operator count identifier + addition_operator 17 integer_literal ; semicolon

Page 68: Subjects Studied so far? Procedural to object oriented

Languages

• Language Recognizer – given a sentence, is it in the

given language?• Language Generator – given a language, create legal

and meaningful sentences• We can build a language

recognizer if we already have a language generator• Grammar – a description of a language - can

be used for generation or, given the grammar, a language recognizer (known as a parser) can be created

• We classify languages into one of four categories:– Regular– Context-Free– Context-Sensitive– Recursively Enumerable• Here, we are interested in the

context-free grammar– these include those which can be

generated from a language generator

– all natural languages and programming languages fall into this category

Page 69: Subjects Studied so far? Procedural to object oriented

Language DefinitionA language definition should enable a person or a

computer program to determine (1) whether a supposed program is infact valid, and (2) if the program is valid, what its meaning or effect is

Syntaxsyntax of a language is defined by two sets of rules:

lexical rules and syntactic rules.Lexical rules specify the set of characters that

constitute the alphabet of the language and the way such characters can be combined to form valid words.

Ex: Pascal considers lowercase and uppercase characters to be identical

Memory” and “memory” refer to the same variable in PascalC and Ada consider them to be distinct

Page 70: Subjects Studied so far? Procedural to object oriented

<> (or ¦) is a valid operator in PascalAda differs from both, since “not equal” is

represented as /=; delimiter <> (called “box”) stands for an undefined range of an array index.

distinction between syntactic and lexical rules, both contribute to the “external” appearance of the language

EBNF [Extended Backus Naur form ]is a meta-language

A meta-language is a language that is used to describe other languages

The symbols ::=, <, >, *, +, (, ), and | are symbols of the metalanguage: they are metasymbols.

A language is described in EBNF through a set of rules. For example, <program> ::= { <statement>* } is a rule

.

Page 71: Subjects Studied so far? Procedural to object oriented

"::=" stands for “is defined as”

symbol “*” stands for “an arbitrary sequence of the

previous element”

a <program> is defined as an arbitrary sequence of

<statement> within brackets “{” and “}”.

The entities inside the metalanguage brackets “<”, and

“>” are called nonterminals; an entity such as the “}”

above is called a terminal

Terminals are what we have previously called words of

the language being defined

nonterminals are linguistic entities that are defined by

other EBNF rules

Page 72: Subjects Studied so far? Procedural to object oriented

Distinguish between metasymbols and terminalsEBNF, the metasymbol “+” denotes one or more

repetitions of the previous element (i.e., at least one element must be present, as opposed to “*”).

metasymbol “|” denotes a choice (a) Syntax rules

<program>::={ <statement>* } <statement>::=<assignment> | <conditional> |

<loop> <assignment>::=<identifier> = <expr> ;

<conditional>::=if <expr> { <statement> + } | if <expr> { <statement> + } else

{ <statement> + } <loop>::=while <expr> { <statement> + }

<expr> ::=<identifier> | <number> | ( <expr> ) |

<expr> <operator> <expr>

Page 73: Subjects Studied so far? Procedural to object oriented

(a) Syntax rules<program>::={ <statement>* } <statement>::=<assignment> |

<conditional> | <loop> <assignment>::=<identifier> = <expr> ;

<conditional>::=if <expr> { <statement> + } |

if <expr> { <statement> + } else { <statement> + } <loop>::=while <expr> { <statement> + }

<expr> ::=<identifier> | <number> | ( <expr> ) | <expr> <operator> <expr>

Page 74: Subjects Studied so far? Procedural to object oriented

(b) Lexical rules

<operator>::= + | - | * | / | = | ¦ | < | > | ≤ | ≥

<identifier>::= <letter> <ld>*

<ld>::= <letter> | <digit>

<number>::= <digit>+

<letter>::= a | b | c | . . . | z

<digit>::= 0 | 1 |2 | . . . | 9

Page 75: Subjects Studied so far? Procedural to object oriented

Syntax diagrams are similar enough to EBNF to allow you to understand the rules.

Page 76: Subjects Studied so far? Procedural to object oriented
Page 77: Subjects Studied so far? Procedural to object oriented
Page 78: Subjects Studied so far? Procedural to object oriented

Nonterminals are represented by boxes and

terminals by circles

Transition diagram having one entry and one

exit edge i.e. nonterminal symbol

if a terminal (circles) is encountered, that word

must be in the string being recognized

if a nonterminal (box) is encountered, then that

nonterminal must be recognized by traversing

the transition diagram for that nonterminal.

Page 79: Subjects Studied so far? Procedural to object oriented

Syntactic description of a language has two

primary uses

(a) It helps the programmer know how to write

a syntactically correct program. For eg: if

statement

(b) It can be used to determine whether a

program is syntactically correct

compiler writer uses the grammar to write a

syntactic analyzer (also called parser) that is

capable of recognizing all valid programs

LEX and YACC are two wellknown UNIX tools

that generate lexical and syntax analyzers,

respectively

Page 80: Subjects Studied so far? Procedural to object oriented

Abstract syntax, concrete syntax and pragmatics Programming languages have the same conceptual

structure but differ in their appearance C fragment Pascal fragmentwhile (x != y) while x <> y do { . . . }; begin . . . EndWhen two constructs differ only at the lexical level,

we say that they follow the same abstract syntax, but differ at the concrete syntax level

they have the same abstract structure and differ only in lower-level details

Modula-2 adopts a good concrete syntax solution, by using the “end” keyword to terminate both loop and conditional statements

Page 81: Subjects Studied so far? Procedural to object oriented

if x = y then if x = y then while x = y do . . . end . . . . . .

else end. . . end

Concrete Syntax:Set of production rules to represent program, The way program Looks like to the programmer.

Abstract Syntax: Set of trees used to represent program

The way program looks like to the Compiler.

.

2 3

4*

+

Page 82: Subjects Studied so far? Procedural to object oriented

Parse Trees

• A hierarchical structure displaying the derivation of an expression in some grammar• Leaf nodes are terminals, non-leaf nodes are non-

terminals• Parser –Process which takes a sentence and breaks it into its

component parts, deriving a parse tree– If the parser cannot generate a parse tree, then the sentence is

not legal– If the parser can generate two or more parse trees for the same

sentence, then the grammar is ambiguous

Page 83: Subjects Studied so far? Procedural to object oriented

Grammar and Parse Tree

<assign> <id> = <expr><id> A | B | C<expr> <id> + <expr>

| <id> * <expr> | (<expr>)

| <id>

<assign>

<id> = <expr>

A <id> * <expr>

B ( <expr> )

<id> + <expr>

A <id>

C

Parse tree for the derivation<assign> <id> = <expr> A = <expr>

A = <id> * <expr> A = B * <expr> A = B * (<expr>) A = B * (<id> +

<expr>) A = B * (A + <expr>) A = B * (A +

<id> ) A = B * (A + C)

Page 84: Subjects Studied so far? Procedural to object oriented

An Ambiguous Grammar

• <assign> <id> := <expr>• <id> A | B | C• <expr> <expr> + <expr> | <expr> *

<expr> | (<expr>) | <id>• With this grammar, the sentence –<assign> A = B + A * C – has two distinct parse trees• see next slide–The reason this is important is that the second parse tree

represents an interpretation of the expression where + has higher precedence than * which would give us an incorrect answer

Page 85: Subjects Studied so far? Procedural to object oriented

Two Parse Trees for A = B + A * C

<assign>

<id> = <expr>

A <expr> + <expr>

<id> <expr> * <expr>

B <id> <id>

A C

<assign>

<id> = <expr>

A <expr> * <expr>

<expr> + <expr> <id>

<id> <id> C

B A

The lower down the operator in the parse tree, the higher its precedenceso on the left, * has a higher precedence than + (which is as it should be)but the tree on the right is incorrect, essentially being A = (B + A) * C eventhough there are no parentheses specified to alter the precedence

Page 86: Subjects Studied so far? Procedural to object oriented

An Unambiguous Grammar

• <assign> <id> := <expr>• <id> A | B | C• <expr> <expr> + <term> | <term>• <term> <term> * <factor> | <factor>• <factor> (<expr>) | <id>

Here, we force operatorprecedence by making amultiplication occur lowerin the tree by deriving itthrough an additional rule( ) having the highestprecedence requires the most derivation to get to it

Page 87: Subjects Studied so far? Procedural to object oriented

Derivation and Parse Tree of the Unambiguous Grammar

<assign> <id> = <expr> A = <expr> A = <expr> + <term> A = <term> + <term> A = <factor> + <term> A = <id> + <term> A = B + <term> A = B + <term> * <factor> A = B + <factor> * <factor> A = B + <id> * <factor> A = B + C * <factor> A = B + C * <id> A = B + C * A

<assign>

<id> = <expr>

A <expr> + <term>

<term> <term> * <factor>

<factor> <factor> <id>

<id> <id> A

B C

Page 88: Subjects Studied so far? Procedural to object oriented

SemanticsSemantics is all about understanding of programs and prediction of

its outcome. The mapping of Syntactical constructs to computational model is mainly done in semantics.

semantics : syntax --> computational modelThis approach is called syntax-directed semantics.

If the meaning of syntactically correct program is verified before the program execution then it is called static semantic

If the meaning of syntactically correct program is verified after the program execution then it is called dynamic semantic

There are many ways a program can be written with valid syntax but turn nonsensical when evaluated. These nonsensical evaluations are known as runtime errors.

Semantics formally describes how programs should be evaluated. Programs that are well-formed according to its semantics do not get stuck.

Page 89: Subjects Studied so far? Procedural to object oriented

• There are several techniques such as (algebraic, axiomatic, denotational, operational, and translation) are used for description of the semantics of programming languages.

1.Algebraic semantics describes the meaning of a program by defining an algebra. The axioms and equations are described by algebraic relationships and operations.

An algebra consists of a domain of values and a set of operations (functions) defined on the domain.

Page 90: Subjects Studied so far? Procedural to object oriented

Algebraic definition of an Integer Stack ADT

Domains: Nat (the natural numbers  Stack ( of natural numbers)  Bool (boolean values) 

Functions: newStack: () -> Stack  push : (Nat, Stack) -> Stack  pop: Stack -> Stack  top: Stack -> Nat  empty : Stack -> Bool 

Axioms:   or 

pop(push(N,S)) = S  top(push(N,S)) = N  empty(push(N,S)) = false  empty(newStack()) = true Errors: pop(newStack())  top(newStack()) where N in Nat and S in Stack.

                       Defining Equations: newStack() = []  push(N,S) = [N|S]  pop([N|S]) = S  top([N|S]) = N

Page 91: Subjects Studied so far? Procedural to object oriented

Axiomatic Semantics

•A semantics that is appropriate for arguing program correctness

Page 92: Subjects Studied so far? Procedural to object oriented

Axiomatic Semantics• Is an approach based on mathematical logic to prove the

correctness of the program. That means under certain constraints on input data (precondition) program executes and it terminates in a final state satisfying constraint on output data

• Axiomatic semantics views a program as a state machine

• Based on formal logic (predicate calculus)• Original purpose: formal program verification• Axioms or inference rules are defined for each statement type

in the language• The logic expressions are called assertions

Page 93: Subjects Studied so far? Procedural to object oriented

• An assertion before a statement (a precondition) states the relationships and constraints among variables that are true at that point in execution• An assertion following a statement is a postcondition• A weakest precondition is the least restrictive precondition that

will guarantee the postcondition.• Pre-, post form: {P} statement {Q}

• An example– a = b + 1 {a > 1}–One possible precondition: {b > 10}–Weakest precondition: {b > 0}

Page 94: Subjects Studied so far? Procedural to object oriented

• Example 1: {k=5} k:=k+1{k=6}• K=6 post condition• K+1=6 (substituting k=6)• Precondition satisfies.

• Example 2: {j=3, k=4} j:=j+k {j=7,k=4}

Page 95: Subjects Studied so far? Procedural to object oriented

One-Slide Summary

• An axiomatic semantics consists of: – A language for stating assertions about programs, – Rules for establishing the truth of assertions

• Some typical kinds of assertions: – This program terminates – If this program terminates, the variables x and y have the same value throughout the execution of the program – The array accesses are within the array bounds

• Some typical languages of assertions – First-order logic – Other logics (temporal, linear, pointer-assertion) – Special-purpose specification languages (SLIC, Z, Larch)

Page 96: Subjects Studied so far? Procedural to object oriented

Other Applications of Axiomatic Semantics

• The project of defining and proving everything formally has not succeeded (at least not yet)

• Proving has not replaced testing and debugging

• Applications of axiomatic semantics: – Proving the correctness of algorithms (or finding bugs) – Proving the correctness of hardware descriptions (or finding bugs) – “extended static checking” (e.g., checking array bounds) – Proof-carrying code – Documentation of programs and interfaces

Page 97: Subjects Studied so far? Procedural to object oriented

Operational Semantics

• Operational Semantics

–Describe the meaning of a program by executing its

statements on a machine, either simulated or actual.

–The change in the state of the machine (memory, registers,

etc.) defines the meaning of the statement

Page 98: Subjects Studied so far? Procedural to object oriented

• The process:

–Build a translator (translates source code to the machine code

of an idealized computer)

–Build a simulator for the idealized computer

• Evaluation of operational semantics:

–Good if used informally (language manuals, etc.)

–Extremely complex if used formally (e.g., VDL), it was used

for describing semantics of PL/I.

Page 99: Subjects Studied so far? Procedural to object oriented

• The language While of simple while programs has a

grammar consisting of three syntactic categories:

numeric expressions, which represent natural

numbers;

• booleans, which are similar to expressions but

represent truth values rather than numbers;

• and commands, which are imperative statements

which affect the store of the computer

Operational Semantics for While

Page 100: Subjects Studied so far? Procedural to object oriented

• Syntax of While

•B Bool ::= true | false | E = E | E < E | ... | B&B | ∈ Bool ::= true | false | E = E | E < E | ... | B&B |

¬B | ...

• E Exp ::= x | n | E + E | ... ∈ Bool ::= true | false | E = E | E < E | ... | B&B |

•C Com ::= x := E | if B then C else C | C; C | skip ∈ Bool ::= true | false | E = E | E < E | ... | B&B |

| while B do C

We use brackets were necessary to disambiguate.

Page 101: Subjects Studied so far? Procedural to object oriented

The commands C are:

• assignment, which takes a variable and an expression and

gives a command, written x := E;

• the conditional, which takes a boolean and two commands

and yields a command, written if B then C else C;

• sequential composition, which takes two commands and

yields a command, written C1; C2 (note that the semicolon

is an operator joining two commands into one, and not just a

piece of punctuation at the end of a command);

• the constant skip command, which does nothing;

• the loop constructor, which takes a boolean and a

command and yields a command, written while B do C

Page 102: Subjects Studied so far? Procedural to object oriented

• Application of operational semantics: - Language manuals and textbooks - Teaching programming languages

• Two different levels of uses of operational semantics: - Natural operational semantics - Structural operational semantics

Page 103: Subjects Studied so far? Procedural to object oriented

Denotational Semantics• Denotational semantics is based on the recognition that

programs and the objects they manipulate are symbolic realizations of abstract mathematical objects, for example,

-strings of digits realize numbers, -and function subprograms realize (approximate) mathematical

functions.

• The idea of denotational semantics is to associate an appropriate mathematical object, such as a number, a tuple, or a function, with each phrase of the language.

• The phrase is said to denote the mathematical object, and the object is called the denotation of the phrase.

Page 104: Subjects Studied so far? Procedural to object oriented

• A fundamental principle of denotational semantics is that the

definition be compositional.

• That means the denotation of a language construct is defined in

terms of the denotations of its subphrases.

• Denotational definitions use special brackets, the emphatic brackets

[[ ]], to separate the syntactic world from the semantic world.

• If p is a syntactic phrase in a programming language, then a

denotational specification of the language will define a mapping

meaning,

• So that meaning [[p]] is the denotation of p—namely, an abstract

mathematical entity that models the semantics of p.

Page 105: Subjects Studied so far? Procedural to object oriented

For example, • the expressions “2*4”, “(5+3)”, “008”, and “8” are syntactic phrases that

all denote the same abstract object, namely the integer 8.

Therefore with a denotational definition of expressions we should be able to show that meaning :

[[2*4]] = meaning [[(5+3)]] = meaning [[008]] = meaning [[8]] = 8.

Functions play a prominent role in denotational semantics, modeling the bindings in stores and environments as well as control abstractions in programming languages.

Page 106: Subjects Studied so far? Procedural to object oriented

For example:

the “program”

• fact(n) = if n=0 then 1 else n*fact(n–1) denotes the

factorial function,

• a mathematical object that can be viewed as the set of

ordered pairs, {<0,1> ,<1,1> ,<2,2> ,<3,6> ,<4,24> ,

… },

denotational semantics should confirm this relationship.

Page 107: Subjects Studied so far? Procedural to object oriented

• A denotational specification of a programming language consists of

five components, two specifying the syntactic world, one describing

the semantic domains, and two defining the functions that map the

syntactic objects to the semantic objects.

1. The Syntactic World :

-Syntactic categories or syntactic domains

-Abstract production rules

2. The Semantic World :

-Semantic domains

3. The Connection between Syntax and Semantics:

-Semantic functions

-semantic equations

Page 108: Subjects Studied so far? Procedural to object oriented

• complete denotational specification of a simple language of nonnegative integer numerals. Syntactic Domains N : Numeral -- nonnegative numerals D : Digit -- decimal digits Abstract Production Rules Numeral ::= Digit | Numeral Digit Digit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 Semantic Domain Number = { 0, 1, 2, 3, 4, … } -- natural numbers Semantic Functions value : Numeral → Number digit : Digit → Number Semantic Equations value [[N D]] = plus (times(10, value [[N]]), digit [[D]]) value [[D]] = digit [[D]] digit [[0]] = 0 digit [[3]] = 3 digit [[6]] = 6 digit [[8]] = 8 digit [[1]] = 1 digit [[4]] = 4 digit [[7]] = 7 digit [[9]] = 9 digit [[2]] = 2 digit [[5]] = 5

Page 109: Subjects Studied so far? Procedural to object oriented

As an example of evaluating a numeral according to this denotational definition, we find the value of the numeral 65: value [[65]] = plus(times(10, value [[6]]), digit [[5]])

= plus(times(10, digit [[6]]), 5) = plus(times(10, 6), 5)

= plus(60, 5) = 65

Solely using the specification of the semantics of numerals, we can easily prove that value [[008]] = value [[8]]: value [[008]] = plus(times(10, value [[00]]), digit [[8]])

= plus(times(10, plus(times(10, value [[0]]), digit [[0]])), 8) = plus(times(10, plus(times(10, digit [[0]]), 0)), 8)

= plus(times(10, plus(times(10, 0), 0)), 8) = 8 = digit [[8]] = value [[8]]

Problem: Use the denotational semantics for numerals to derive the value of “3087”

Page 110: Subjects Studied so far? Procedural to object oriented

Summary

• BNF and context-free grammars are equivalent meta-languages–Well-suited for describing the syntax of programming

languages• An attribute grammar is a descriptive formalism that can

describe both the syntax and the semantics of a language• Three primary methods of semantics description–Operation, axiomatic, denotational

Page 111: Subjects Studied so far? Procedural to object oriented
Page 112: Subjects Studied so far? Procedural to object oriented

Language ProcessingOn the basis of speed of execution, flexibility and cost of

realization machine languages are designed for developing new software layers. On the other hand, programming languages are often designed with respect to reliability and ease of programming.

A basic problem is how a higher level language ultimately can be executed on a computer whose machine language is very different and at a much lower level.

For an implementation: interpretation and translation are two options.

Page 113: Subjects Studied so far? Procedural to object oriented

Interpretation

In this solution, the actions implied by the constructs of the language are executed directly .

Usually, for each possible action there exists a subprogram–written in machine language–to execute the action.

Thus, interpretation of a program is accomplished by calling subprograms in the appropriate sequence.

Page 114: Subjects Studied so far? Procedural to object oriented

More precisely, an interpreter is a program that repeatedly executes the following sequence.

1. Get the next statement;2. Determine the actions to be executed;3. Perform the actions;This sequence is very similar to the pattern of actions carried out by a

traditional computer, that is:a. Fetch the next instruction (i.e., the instruction whose address is specified by the instruction pointer).b . Advance the instruction pointer (i.e., set the address of the instruction to be fetched next).c. Decode the fetched instruction.a.Execute the instruction.

Page 115: Subjects Studied so far? Procedural to object oriented

TranslationIn this solution, programs written in a high-level language are

translated into an equivalent machine-language version before being executed. This translation is often performed in several steps .

Program modules might first be separately translated into relocatable machine code;

modules of relocatable code are linked together into a single relocatable unit;

finally, the entire program is loaded into the computer’s memory as executable machine code.

The translators used in each of these steps have specialized names: compiler, linker (or linkage editor), and loader, respectively.

Page 116: Subjects Studied so far? Procedural to object oriented

In some cases, the machine on which the translation is performed (the host machine) is different from the machine that is to run the translated code (the target machine). This kind of translation is called cross-translation. Cross translators offer the only viable solution when the target machine is a special purpose processor rather than a general-purpose one that can support a translator.

In practice, many languages are implemented by a combination of the two techniques. A program may be translated into an intermediate code that is then interpreted.

Page 117: Subjects Studied so far? Procedural to object oriented

Compilers and interpreters differ in the way they can report on run-time errors.

Typically, with compilation, any reference to the source code is lost in the generated object code. If an error is generated at run-time, it may be impossible to relate it to the source language construct being executed. This is why run-time error messages are often obscure and almost meaningless to the programmer.

On the opposite, the interpreter processes source statements, and can relate a run-time error to the source statement being executed.

For these reasons, certain programming environments contain both an interpreter and a compiler for a given programming language.

Page 118: Subjects Studied so far? Procedural to object oriented

Interpreter Compiler

Translates program one statement at a time.

Scans the entire program and translates it as a whole into machine code.

It takes less amount of time to analyze the source code but the overall execution time is slower.

It takes large amount of time to analyze the source code but the overall execution time is comparatively faster.

No intermediate object code is generated, hence are memory efficient.

Generates intermediate object code which further requires linking, hence requires more memory.

Continues translating the program until the first error is met, in which case it stops. Hence debugging is easy.

It generates the error message only after scanning the whole program. Hence debugging is comparatively hard.

Programming language like Python, Ruby use interpreters.

Programming language like C, C++ use compilers.

Page 119: Subjects Studied so far? Procedural to object oriented

• Purely interpreted solution: 1. Complicated Decoding process 2. identical each time the statement is encountered 3. If statements appears in loop, speed of execution is affected

• Purely Translated solution: 1. generates machine code for each high level statement. 2. translator decodes each high level statement only once 3. frequently occurring parts are then decoded n no of times in their machine language respectively. 4. Can save processing time over Pure interpreted.

Each high level lang. statement can expand in to 10sor 100s of machine instruction.High level statements are in original form, and instructions necessary to execute them are stored in subprogram for the interpretation

Page 120: Subjects Studied so far? Procedural to object oriented

The concept of bindingBinding is a central concept in the definition of programming language

semantics. Programming languages differ in the number of entities with which they can

deal, in the number of attributes to be bound to entities,

The time at which such bindings occur (binding time), and in the stability of the binding (i.e., whether an established binding is fixed or modifiable).

A binding that cannot be modified is called static. A modifiable binding is

called dynamic.

Some attributes may be bound at language definition time, others at program translation time (or compile time), and others at program execution time (or run time). The following is a (nonexhaustive) list of binding examples:

Page 121: Subjects Studied so far? Procedural to object oriented

Language definition time binding.

In most languages (including FORTRAN, Ada, C, andC++) the

type "integer" is bound at language definition time to its well-

known mathematical counterpart, i.e., to a set of algebraic

operations that produce and manipulate integers;

Page 122: Subjects Studied so far? Procedural to object oriented

Language implementation time binding.

In most languages (including FORTRAN, Ada, C, and C++) a set of

values is bound to the integer type at language implementation

time.

That is, the language definition states that type "integer" must be

supported

and the language implementation binds it to a memory

representation, which–in turn–determines the set of values that are

contained in the type.

Page 123: Subjects Studied so far? Procedural to object oriented

Compile time (or translation time) binding.

Pascal provides a predefined definition of type integer, but

allows the programmer to redefine it. Thus type integer is

bound a representation at language implementation time, but

the binding can be modified at translation time.

Execution time (or run time) binding.

In most programming languages variables are bound to a value

at execution time, and the binding can be modified repeatedly

during execution.

Page 124: Subjects Studied so far? Procedural to object oriented

In the first two examples, the binding is established before run time

and cannot be changed thereafter. This kind of binding regime is

often called static.

The term static denotes both the binding time (which occurs before

the program is executed) and the stability (the binding is fixed).

Conversely, a binding established at run time is usually modifiable

during execution.

The fourth example illustrates this case. This kind of binding regime

is often called dynamic. There are cases, however, where the binding

is established at run time, and cannot be changed after being

established. An example is a language providing (read only) constant

variables that are initialized with an expression to be evaluated at run

time.

The concepts of binding, binding time, and stability help clarify

many semantic aspects of programming languages.

Page 125: Subjects Studied so far? Procedural to object oriented

VariablesConventional computers are based on the notion of a main

memory consisting of elementary cells, each of which is identified by an address.

The contents of a cell is an encoded representation of a value. A value is a mathematical abstraction; its encoded

representation in a memory cell can be read and (usually) modified during execution. Modification implies replacing one encoding with a new encoding

In particular, they introduce the notion of variables as an abstraction of the memory cells.

the variable name as an abstraction of the address. and the notion of assignment statements as an abstraction of

the destructive modification of a cell.

Page 126: Subjects Studied so far? Procedural to object oriented

Formally, a variable is a 5-tuple <name, scope, type, l_value, r_value>,

where name is a string of characters used by program statements to denote the variable; scope is the range of program instructions over which the name is known; type is the variable’s type; l_value is the memory location associated with the variable;r_value is the encoded value stored in the variable’s location.

Page 127: Subjects Studied so far? Procedural to object oriented

Name and scope:• A variable’s name is usually introduced by a special statement,

called declaration and, normally, the variable’s scope extends from that point until some later closing point,

• The scope of a variable is the range of program instructions over which the name is known. Program instructions can manipulate a variable through its name within its scope.

• We also say that a variable is visible under its name within its scope, and invisible outside it.

• Different programming languages adopt different rules for binding variable names to their scope

Page 128: Subjects Studied so far? Procedural to object oriented

• Variables can be bound to a scope either statically or dynamically.

• Static scope binding defines the scope in terms of the lexical structure of a program, that is, each reference to a variable can be statically bound to a particular (implicit or explicit) variable declaration by examining the program text, without executing it. EXAMPLE: C

• Dynamic scope binding defines the scope of a variable's name in terms of program execution. APL, LISP (as originally defined), and SNOBOL4 are examples of languages with dynamic SCOPE RULES

Page 129: Subjects Studied so far? Procedural to object oriented
Page 130: Subjects Studied so far? Procedural to object oriented
Page 131: Subjects Studied so far? Procedural to object oriented

Type:

• type of a variable is a specification of the set of values that can be associated with the variable, together with the operations that can be legally used to create, access, and modify such values. A variable of a given type is said to be an instance of the type.

• When the language is defined, certain type names are bound to certain classes of values and sets of operations. • For example, type integer and its associated operators are

bound to their mathematical counterpart. Values and operations are bound to a certain machine representation when the language is implemented.

Page 132: Subjects Studied so far? Procedural to object oriented

• In some languages, the programmer can define new types by means of type declarations. For example, in C one can write

typedef int vector [10];

• This declaration establishes a binding–at translation time–between the type name vector and its implementation (i.e., an array of 10 integers, each accessible via an index in the subrange 0. .9).

• As a consequence of this binding, type vector inherits all the operations of the representation data structure (the array); thus, it is possible to read and modify each component of an object of type vector by indexing within the array.

Page 133: Subjects Studied so far? Procedural to object oriented

• Traditional languages, such as FORTRAN, COBOL, Pascal, C, C++, Modula-2, and Ada bind variables to their type at compile time, and the binding cannot be changed during execution. This solution is called static typing.

• For example, in C one can write: int x, y; char c;

By declaring variables to belong to a given type, variables are automatically protected from the application of illegal (or nonsensical) operations.

For example, in Ada the compiler can detect the application of the illegal assignment I:= not A, if I is declared to be an integer and A is a boolean. Through this check, the compiler watches for violations to static semantics concerning variables and their types.

The ability to perform checks before the program is executed (static type checking) contributes to early error detection and enhances program reliability

Page 134: Subjects Studied so far? Procedural to object oriented

l_value AND r_value

• The binding between a variable and the value held in its storage area is usually dynamic;• the value can be modified by an assignment operation. An

assignment such as b = a; causes a's r_value to be copied into the storage area referred to by b’s l_value. • That is, b’s r_value changes. This, however, is true only for

conventional imperative languages, like FORTRAN, C, Pascal, Ada, and C++. • Functional and logic programming languages treat variables as

their mathematical counterpart: they can be bound to a value by the evaluation process, but once the binding is established it cannot be changed during the variable's lifetime.

Page 135: Subjects Studied so far? Procedural to object oriented

Routines• Routines is a collection of instruction that can be used to perform specific

task and can be repeatedly executed.

• Functions and procedure are two forms of routines• Functions returns a value but procedure does not return the value• Functions can be converted to routines by making them void(i.e. returning

NULL)• Four attributes name,scope,l-value,r-value• three ways i)declaration ii) call iii) definition

• A routine’s l_value is a reference to the memory area which stores the routine body (i.e., the routine’s executable statements). Activation causes execution of the routine body, which constitutes the r_value that is currently bound to the routine

Page 136: Subjects Studied so far? Procedural to object oriented

An Abstract Semantic Processor

• Language constructs can be executed by sequences of operations of the abstract processor.• an instruction pointer, a memory, and a processor• The memory is where the instructions to be executed and the data to

be manipulated are stored• two separate memory sections: the code memory (C) and the data

memory (D)• Both C's and D's initial address is 0 (zero), and both programs and

data are assumed to be stored from the initial address• The instruction pointer (ip) is always used to point to a location

in C; it is initialized to 0.

Page 137: Subjects Studied so far? Procedural to object oriented

• D[X] and C[X] to denote the values stored in the X-th cell of D and C, respectively.

• X is an l_value and D[X] is the corresponding r_value.

• Modification of the value stored in a cell is performed by instruction set, with two parameters: the address of the cell whose contents is to be set, and the expression evaluating the new value.

• Ex: instruction set 10, D[20] is to assign the value stored at location 20 into location 10

• set 15, read means that the value read from the input device is to be stored at location 15

Page 138: Subjects Studied so far? Procedural to object oriented

• set write, D[50] means that the value stored at location 50 is to be transferred to the output device.

• for example, D[15]+D[33]*D[41] would be a an acceptable expression, and

set 99, D[15]+D[33]*D[41] would be an acceptable instruction to modify the contents of location 99

• The machine, in fact, operates by executing the following steps repeatedly, until it encounters a special halt instruction:

1. Get the current instruction to be executed (i.e., C[ip]);2. Increment ip;3. Execute the current instruction.

Page 139: Subjects Studied so far? Procedural to object oriented

• unconditional jump to a certain instruction ,jump 47 forces the instruction stored at address 47 of C to be the next instruction to be executed; that is, it sets ip to 47

• jumpt 47, D[3] > D[8] the jump occurs only if the value stored in cell 3 is greater than the value stored in cell 8.

• allows indirect addressing set D[10], D[20] assigns the value stored at location 20 into the cell whose address is the value stored at location 10.

Page 140: Subjects Studied so far? Procedural to object oriented
Page 141: Subjects Studied so far? Procedural to object oriented

Run Time Structure• Run Time Storage : the compiler demands for block of memory to

operating system• Run Time Storage: 1) Code Memory 2) Data Memory• Data Memory keeps a track of procedure activation and store data objects

and information• DM 1) Static allocation 2) Stack based allocation 3) Heap.• Static Language: for data object at compile time Size ,name of data objects bound to storage at compile time only

amount of storage allocated do not change at run time. Activation record find the addresses of these record. Can fill the addresses at which target code can operate it. FORTAN and COBOL.

Limitation : Recursive procedures are not supported

Page 142: Subjects Studied so far? Procedural to object oriented

Run Time Structure

• Stack Language: manages the allocation at run time storage Control Stack

Activation record push the element onto the stack, popped is performed accordingly, dynamically stack allocation is created for data structure.

Limitation: Allocation is slower as compared to static allocation as pointer and index register are required for addressing

Page 143: Subjects Studied so far? Procedural to object oriented

Run Time Structure

• Heap allocation Continuous block of memory Deallocation i.e free space is reused by heap managerLinked list is used for free allocation

Page 144: Subjects Studied so far? Procedural to object oriented

CASE STUDY: Run Time Structure of C

main ( ){int i, j;get (i, j);while (i != j)if (i > j)i -= j;elsej -= i;print (i);}

• C1: A language with only simple statements

Page 145: Subjects Studied so far? Procedural to object oriented
Page 146: Subjects Studied so far? Procedural to object oriented

Introduction• A programming paradigm is a fundamental style of computer

programming.

• Compare with a software development methodology, which is a style of solving specific software engineering problems.

• Different methodologies are more suitable for solving certain kinds of problems or applications domains.

• Same for programming languages and paradigms. • Programming paradigms differ in:– the concepts and abstractions used to represent the elements of a program

(such as objects, functions, variables, constraints, etc.)– the steps that compose a computation (assignation, evaluation, data flow,

control flow, etc.).

Page 147: Subjects Studied so far? Procedural to object oriented

• Some languages are designed to support one particular paradigm –Smalltalk supports object-oriented programming–Haskell supports functional programming

• Other programming languages support multiple paradigms –Object Pascal, C++, C#, Visual Basic, Common Lisp,

Scheme, Perl, Python, Ruby, Oz and F#.

• The design goal of multi-paradigm languages is to allow programmers to use the best tool for a job, admitting that no one paradigm solves all problems in the easiest or most efficient way.

Page 148: Subjects Studied so far? Procedural to object oriented

Introduction to Various Programming Paradigms

To comprehend how languages are constructed, one needs to look deeper.

The four basic computational models that describe most programming today are :

1) Imperative or procedural Language 2) Applicative or functional Language 3) Rule based or logic Language 4) Object oriented Language 5) Abstract level 6) Generic Programming Language

Page 149: Subjects Studied so far? Procedural to object oriented

Procedural programming. Programs are decomposed into computation steps that

perform complex operations.Procedures and functions (collectively called routines) are

used as modularization units to define such computation steps.

Functional programming. functions are the primary building blocks of the program

Abstract data type programming. recognizes as the unit of program modularity.

Module-based programming. groupings of entities such as variables, procedures, functions,

types, etc.

Page 150: Subjects Studied so far? Procedural to object oriented

Object-oriented programming. definition of classes of objects. Instances of classes are created by the program as needed

during program execution. Generic programming.

instantiated, either at compile-time or runtime, to create the entities—data structures, functions, and procedures— needed to form the program.

encourages the development of high-level, generic, abstractions as units of modularity.

Declarative programming. declarative description of a problem, rather than the

decomposition of the problem into an algorithmic implementation.

Page 151: Subjects Studied so far? Procedural to object oriented

Imperative languages

Page 152: Subjects Studied so far? Procedural to object oriented

Procedural programming is a type of imperative programming in which the program is built from one or more procedures (also termed subroutines or functions)

The hardware implementation of almost all computers is imperative. Nearly all computer hardware is designed to execute machine code, which is native to the computer, written in the imperative style.

The main concept in imperative or procedural languages is the machine state. It majorly focuses on which memory location contains which value. These languages are statement oriented or command driven.

On every statement execution, value stored at memory location is changed. This results into change of state. Thus procedural language program contains sequence of statements. General program structure is like :

Statement1;Statement2;...

Page 153: Subjects Studied so far? Procedural to object oriented

2 5

3

Fig. describes the process .Memory consists of collection of boxes, the execution of a statement can be represented as accessing the memory location. Eg: two boxes carry marbles, are added and stored in third box.(in new location).Program development consist of building the successive machine state needed to arrive to this solution. This is the basic view of programming. Languages like C,C++,FORTRAN,ALGOL,PL/I, Pascal, Ada , Smalltalk and COBOL supports this model.

Page 154: Subjects Studied so far? Procedural to object oriented

Applicative or functional Language

In this model program development is the process of development of functions from previously developed functions which can be used for developing more complex functions. These functions, then, can manipulate the initial set of data until the final function can be used to compute an answer from the initial data.

Once the final answer is obtained, we apply that to the initial data and arrive at a result. Such languages have following general syntax:

Function,, ( ... f unction2 (function1 (data)) ... )e.g. LISP and ML are two functional languages .

Page 155: Subjects Studied so far? Procedural to object oriented

Rule based languagesRule based languages checks for the existence

of a certain enabling condition. If such conditions are present, they execute an appropriate action.

Prolog is the most common rule based language. Since basic enabling conditions are certain classes of predicate logic expressions, it is also called as logic programming language.

In rule based language execution is similar to an imperative language except that order of execution of statements is not sequential but depends on enabling conditions.

The syntax of such languages generally is similar to the following :

enabling condition1 action1,enabling condition2 action2,……………….enabling condition n action n

e.g. Apart from Prolog, the most common language in this class, many other languages use this paradigm. The common business application of decision tables is a form of rule based programming.

Page 156: Subjects Studied so far? Procedural to object oriented

Object-oriented programmingIn OO-Programming model, focus is on data. So complex data

objects are created and then to manipulate those objects some functions are built.

To built the complex objects, simpler objects are built first and then extended to complex objects by using the properties of simpler objects.

Building of Separate functions, which use a restricted data provides reliability to the application being developed.

Languages coming under object oriented paradigm are characterized by following features :

(1) Abstract data type(2) Inheritance and(3) A particular kind of dynamic binding.

Page 157: Subjects Studied so far? Procedural to object oriented

Figure by Brian Hayes(who credits, in part, Éric Lévénez and Pascal Rigaux):

Brian Hayes, “The

Semicolon Wars.” American Scientist,

July-August 2006,

pp.299-303

Page 158: Subjects Studied so far? Procedural to object oriented

Some programming languages, namely, functional and logic

languages, have abandoned the Von Neumann computation model. Imperative, functional, and logic paradigms reflect the different

underlying computation model of the language.

ML provides a functional computation model and abstract data type programming

CLOS is a functional language that supports the object-oriented style