5-1 © 2004, D.A. Watt, University of Glasgow 5 Procedural Abstraction  Proper procedures and function procedures.  Parameters and arguments.  Implementation.

Slides:



Advertisements
Similar presentations
1) Scope a] Ada scope rules b] C scope rules 2) Parameter passing a] Ada parameter modes b) Parameter passing mechanisms COMP205 IMPERATIVE LANGUAGES 13.
Advertisements

Programming Languages and Paradigms
Names and Bindings.
Introduction to Programming Languages Nai-Wei Lin Department of Computer Science and Information Engineering National Chung Cheng University.
Subprogram Control - Data sharing Mechanisms to exchange data Arguments - data objects sent to a subprogram to be processed. Obtained through  parameters.
Chapter 7: User-Defined Functions II
Lecture 16 Subroutine Calls and Parameter Passing Semantics Dragon: Sec. 7.5 Fischer: Sec Procedure declaration procedure p( a, b : integer, f :
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
CS 330 Programming Languages 10 / 16 / 2008 Instructor: Michael Eckmann.
1 Chapter 7: Runtime Environments. int * larger (int a, int b) { if (a > b) return &a; //wrong else return &b; //wrong } int * larger (int *a, int *b)
More on Recursive Recursion vs. Iteration Why Recursion?
PSUCS322 HM 1 Languages and Compiler Design II Parameter Passing Material provided by Prof. Jingke Li Stolen with pride and modified by Herb Mayer PSU.
Semantics of Calls and Returns
The environment of the computation Declarations introduce names that denote entities. At execution-time, entities are bound to values or to locations:
ISBN Chapter 9 Subprograms and Functions –Design Issues –Local Referencing Environments –Parameter-Passing Methods –Parameters that are Subprogram.
CSC321: Programming Languages1 Programming Languages Tucker and Noonan Chapter 9: Functions 9.1 Basic Terminology 9.2 Function Call and Return 9.3 Parameters.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 9 Functions It is better to have 100 functions.
Types(2). 2 Recursive Problems  One or more simple cases of the problem have a straightforward, nonrecusive solution  The other cases can be redefined.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
CS 2104 Prog. Lang. Concepts Subprograms
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Bindings and scope  Bindings and environments  Scope and block structure  Declarations Programming Languages 3 © 2012 David A Watt, University.
Subprograms Support process abstraction and modularity –characteristics of subprograms are that they have a single entry point the calling entity is suspended.
Compiler Construction
6-1 © 2004, D.A. Watt, University of Glasgow 6 Data Abstraction  Packages and encapsulation.  Abstract types.  Classes, subclasses, and inheritance.
Introduction A variable can be characterized by a collection of properties, or attributes, the most important of which is type, a fundamental concept in.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Basic Semantics Associating meaning with language entities.
Slide: 1 Copyright © AdaCore Subprograms Presented by Quentin Ochem university.adacore.com.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Dr. Philip Cannata 1 Functions and Recursion. Dr. Philip Cannata 2 10 Java (Object Oriented) ASP RDF (Horn Clause Deduction, Semantic Web) Relation Jython.
CPS120: Introduction to Computer Science Decision Making in Programs.
9-1 9 Variables and lifetime  Variables and storage  Simple vs composite variables  Lifetime: global, local, heap variables  Pointers  Commands 
Programming Languages and Paradigms Imperative Programming.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 9.
Procedural programming in Java Methods, parameters and return values.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Copyright © 2006 The McGraw-Hill Companies, Inc. Basic Terminology Value-returning functions: –known as “non-void functions/methods” in C/C++/Java –called.
Homogeneous tuples What are they? –S 2 = S x S –S n = S x S x … x S Cardinalities –#(S 2 )= (#S) 2 –#(S n )= (#S) n –#(S 0 )= (#S) 0 =1 What is S 0 ? –It.
Structure of Programming Languages Names, Bindings, Type Checking, and Scopes.
CSI 3125, Subprograms, page 1 Subprograms General concepts Parameter passing Functions Subprograms as parameters.
Concepts of programming languages Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil 1-1.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Programming Languages (CS 550) Lecture 2 Summary Mini Language Interpreter Jeremy R. Johnson.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
Procedure Definitions and Semantics Procedures support control abstraction in programming languages. In most programming languages, a procedure is defined.
Dr. Philip Cannata 1 Functions and Recursion Programming Languages.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering CSCE 330 Programming Language Structures Operational Semantics (Slides mainly.
Procedure Activations Programming Language. Exploration Name ocurrenceDeclarationLocationValue scopeactivationstate a.From names to their declarations.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
CS314 – Section 5 Recitation 9
Run-Time Environments Chapter 7
Implementing Subprograms Chapter 10
Functions.
Principles of programming languages 4: Parameter passing, Scope rules
CSCI 3370: Principles of Programming Languages Chapter 9 Subprograms
Mini Language Interpreter Programming Languages (CS 550)
UNIT V Run Time Environments.
Chapter 9 Subprograms Fundamentals of Subprograms
Subprograms General concepts Parameter passing Functions
Corresponds with Chapter 5
SPL – PS2 C++ Memory Handling.
Chapter 11 Abstraction - The concept of abstraction is fundamental in
Presentation transcript:

5-1 © 2004, D.A. Watt, University of Glasgow 5 Procedural Abstraction  Proper procedures and function procedures.  Parameters and arguments.  Implementation notes.

5-2 Abstraction  In programming, abstraction means the distinction between what a program unit does and how it does it.  This supports a separation of concerns between the application programmer (whose uses the program unit) and the implementor (who codes the program unit).  This separation of concerns is essential in large-scale program development.  Program units include: procedures (here) abstract types and classes (Chapter 6). René Magritte, Piet Mondrian Grey TreeGrey Tree, Piet MondrianPiet Mondrian Construção sobre o vazio, Piet MondrianPiet Mondrian Broadway Boogie-woogieBroadway Boogie-woogie (1943), Piet MondrianPiet Mondrian Princesse Albert de BrogliePrincesse Albert de Broglie (1853), IngresIngres

5-3 Function procedures (1)  A function procedure (or just function) embodies an expression to be evaluated.  When called, the function procedure yields a result value.  Separation of concerns: The application programmer is concerned only with the function procedure’s result (its observable behaviour). The implementer is concerned only with how the function procedure works (its algorithm).

5-4 Function procedures (2)  A Haskell function definition has the form: I ( FPs ) = E expression formal parameters  The function body is an expression E.  A call to the function simply evaluates E to determine the result.

5-5 Example: Haskell function procedure  Function definition: power (x: Float, n: Int) = if n = 0 then 1.0 else x * power(x, n-1)  Function call: power(y, 3) where y :: Float

5-6 Function procedures (3)  An Ada function definition has the form: function I ( FPs ) return T is D begin C end; local declaration command result type formal parameters  The function body “D begin C end; ” is syntactically a block command.  A call to the function executes the block command. The latter must execute “ return E ; ”, which evaluates E to determine the result.  Thus the function body acts like an expression!

5-7 Example: Ada function procedure (1)  Function definition: function power (x: Float, n: Integer) return Float is p: Float := 1.0; begin for i in 1.. n loop p := p * x; end loop; return p; end;  Function call: power(y, 3) where y: Float

5-8 Example: Ada function procedure (2)  Recursive function definition: function power (x: Float, n: Integer) return Float is begin if n = 0 then return 1.0; else return x * power(x, n-1); end if; end;

5-9 Function procedures (4)  A C function definition has the form: T I ( FPs ) B block command result type formal parameters  The function body is a block command.  Pros and cons of C/Ada style of function definition: +The full expressive power of commands is available in the function body. –Executing a block command is a roundabout way to compute a result. –Side effects are possible. –There’s no guarantee that “ return E ; ” will actually be executed.

5-10 Proper procedures (1)  A proper procedure (or just procedure) embodies a command to be executed.  When called, the proper procedure updates variables.  Separation of concerns: The application programmer is concerned only with the updates effected by the proper procedure (its observable behaviour). The implementer is concerned only with how the proper procedure works (its algorithm).

5-11 Proper procedures (2)  Ada procedure definitions have the form: procedure I ( FPs ) is D begin C end; local declaration command formal parameters  The procedure body “D begin C end; ” is a block command.  A call to the procedure executes the block command.

5-12 Example: Ada proper procedure  Procedure definition: procedure sort (a: in out Int_Array) is p: Integer range a'first.. a'last; begin if a'first < a'last then partition(a, p); sort(a(a'first..p-1)); sort(a(p+1..a'last)); end if; end;  Procedure call: sort(nums); where nums: Int_Array

5-13 The Abstraction Principle (1)  In summary: A function procedure abstracts over an expression. That is to say, a function procedure has a body that is an expression (in effect), and a function call is an expression that will yield a value by evaluating the function procedure’s body. A proper procedure abstracts over a command. That is to say, a proper procedure has a body that is a command, and a proper procedure call is a command that will update variables by executing the proper procedure’s body.  There is a close analogy.  We can extend this analogy to other types of procedures.

5-14 The Abstraction Principle (2)  PL designers should bear in mind the Abstraction Principle: It is possible to design procedures that abstract over any syntactic category, provided only that the constructs in that syntactic category specify some kind of computation.  For instance, a variable access yields a reference to a variable. So a PL designer could consider: A selector procedure abstracts over a variable access. That is to say, a selector procedure has a body that is a variable access (in effect), and a selector call is a variable access that will yield a variable by evaluating the selector procedure’s body.

5-15 Example: C++ selector procedure (1)  Suppose that values of type Queue are queues of integers.  Function definition: int first (Queue q) { … // return the first element of q }  Function calls: int i = first(qA); first(qA) = 0; Illegal, since first returns an int value, not an int variable.

5-16 Example: C++ selector procedure (2)  Selector definition in outline: int& first (Queue q) { … // return a reference to the first element of q }  Selector calls: int i = first(qA); first(qA) = 0; Now legal, since first returns a reference to an int variable.

5-17 Example: C++ selector procedure (3)  Possible selector definition in full: struct Queue { int elems[100]; int front, rear, length; } int& first (Queue q) { return q.elems[q.front]; }  Now the selector call first(qA) yields a reference to the variable qA.elems[qA.front].

5-18 Parameters and arguments (1)  An argument is a value or other entity that is passed to a procedure.  An actual parameter is an expression (or other construct) that yields an argument.  A formal parameter is an identifier through which a procedure can access an argument.  What may be passed as arguments? first-class values (in all PLs) either variables or pointers to variables (in many PLs) either procedures or pointers to procedures (in some PLs).

5-19 Parameters and arguments (2)  Each formal parameter is associated with the correspond- ing argument. The exact nature of this association is called a parameter mechanism.  Different PLs support a bewildering variety of parameter mechanisms: value, result, value-result, constant, variable, procedural, and functional parameters.  These can all be understood in terms of two underlying concepts: A copy parameter mechanism binds the formal parameter to a local variable that contains a copy of the argument’s value. A reference parameter mechanism binds the formal parameter directly to the argument itself.

5-20 Copy parameter mechanisms (1)  A copy parameter mechanism allows for a value to be copied into and/or out of a procedure: The formal parameter denotes a local variable of the procedure. A value is copied into the local variable on calling the procedure, and/or copied out of the local variable (to an argument variable) on return.  Three possible copy parameter mechanisms: copy-in parameter copy-out parameter copy-in-copy-out parameter.

5-21 Copy parameter mechanisms (2)  Copy-in parameter (or value parameter) The argument is a value. On call, a local variable is created and initialized with the argument value. On return, that local variable is destroyed.  Copy-out parameter (or result parameter) The argument is a variable. On call, a local variable is created but not initialized. On return, that local variable is destroyed and its final value is assigned to the argument variable.

5-22 Copy parameter mechanisms (3)  Copy-in-copy-out parameter (or value-result parameter) The argument is a variable. On call, a local variable is created and initialized with the argument variable’s current value. On return, that local variable is destroyed and its final value is assigned back to the argument variable.

5-23 Example: Ada copy parameters (1)  Procedure: type Vector is array (1.. n) of Float; procedure add ( v, w: in Vector; sum: out Vector) is begin for i in 1.. n loop sum(i) := v(i) + w(i); end loop; end; … add(a, b, c); Local variables v, w are initialized to values of a, b. Local variable sum is created but not initialized. Final value of sum is assigned to c. copy-in copy-out Assume:

5-24 Example: Ada copy parameters (2)  Procedure: procedure normalize ( u: in out Vector) is s: Float := 0.0; begin for i in 1.. n loop s := s + u(i)**2; end loop; s := sqrt(s); for i in 1.. n loop u(i) := u(i)/s; end loop; end; … normalize(c); Local variable u is initialized to value of c. Final value of u is assigned to c. copy-in- copy-out Assume:

5-25 Copy parameter mechanisms (3)  Summary: Parameter mechanism ArgumentOn callOn return Copy-invalueFP := argument value— Copy-outvariable—argument variable := FP Copy-in- copy-out variableFP := argument variable’s value argument variable := FP  Pros and cons: +pleasingly symmetrical –unsuitable for types that lack assignment (e.g., Ada limited types) –copying of large composite values is inefficient.

5-26 Reference parameter mechanisms (1)  A reference parameter mechanism allows for the formal parameter FP to be bound directly to the argument itself.  Reference parameter mechanisms appear under several guises: constant parameters variable parameters procedural parameters.

5-27 Reference parameter mechanisms (2)  Constant parameter The argument is a value. On call, FP is bound to that value.  Variable parameter The argument is a variable. On call, FP is bound to that variable.  Procedural parameter The argument is a procedure. On call, FP is bound to that procedure. Thus any inspection of FP is actually an indirect inspection of the argument value. Thus any inspection (or updating) of FP is actually an indirect inspection (or updating) of the argument variable. Thus any call to FP is actually an indirect call to the argument procedure.

5-28 Example: Ada reference parameters (1)  Procedure: type Vector is array (1.. n) of Float; procedure add ( v, w: in Vector; sum: out Vector) is begin for i in 1.. n loop sum(i) := v(i) + w(i); end loop; end; … add(a, b, c); v, w are bound to values of a, b. sum is bound to variable c. const. params. var. param. Assume:

5-29 Example: Ada reference parameters (2)  Procedure: procedure normalize ( u: in out Vector) is s: Float := 0.0; begin for i in 1.. n loop s := s + u(i)**2; end loop; s := sqrt(s); for i in 1.. n loop u(i) := u(i)/s; end loop; end; … normalize(c); u is bound to variable c. var. param. Assume:

5-30 Reference parameter mechanisms (3)  Summary:  Pros and cons: +simple and uniform semantics +suitable for all types of values (not just first-class values) –indirect reference to primitive values is rather inefficient –variable parameters can cause aliasing. Parameter mechanism ArgumentOn callOn return Constantvaluebind FP to argument value— Variablevariablebind FP to argument variable— Proceduralprocedurebind FP to argument procedure—

5-31 C and Java parameter mechanisms  C supports only the copy-in parameter mechanism. However, we can achieve the effect of a variable parameter by passing a pointer: If a C function has a parameter of type T *, the corresponding argument must be a pointer to a variable of type T. The function can then inspect or update that variable.  Java supports the copy-in parameter mechanism for primitive types, and the reference parameter mechanism for object types: Parameters of type int, float, etc., are passed by copy. Parameters of type T [], String, List, etc., are passed by reference.

5-32 Ada parameter mechanisms  Ada mandates copy mechanisms for primitive types, but allows the compiler to choose between copy and reference mechanisms for composite types: Parameters of type Integer, Float, etc., are passed by copy. Parameters of type Vector may be passed either by copy or by reference. Either way, procedure calls such as ‘ add(a, b, c); ’ will usually have the same effect. (But aliasing might make a difference.)  Why leave the compiler to choose? Reference mechanisms are usually more efficient, but: Copy mechanisms may be more efficient for small composite types. Copy mechanisms are more efficient for remote procedure calls.

5-33 Aliasing  Aliasing occurs when two or more formal parameters are bound to the same argument variable.  Aliasing sometimes has unexpected effects.  In general, aliasing cannot be detected by the compiler. The onus is on programmers to avoid harmful aliasing.

5-34 Example: Ada aliasing  Procedure: type Position is range 1.. 9; type Board is array (Position) of Character; procedure move ( mark: in Character; pos: in Position; old: in Board; new: out Board) is begin new := old; new(pos) := mark; display(old, new); end; … move('X', 9, bd, bd); old is bound to bd. var. param. Assume: var. param. new is bound to bd. What is displayed? bd

5-35 Implementation of procedure calls  When a procedure is called, an activation frame is pushed on to the stack. The activation frame contains enough space for all of the procedure’s local variables, together with space for the return address and other housekeeping data. When the procedure returns, the activation frame is popped off the stack.  At any given time, the stack contains activation frames for all currently-active procedures, in the order in which they were called.  Recursive procedures require no special treatment.

5-36 Implementation of parameter mechanisms  Arguments are passed by being deposited either in registers or in the procedure’s activation frame.  Each copy parameter is implemented by creating (and later destroying) a variable local to the procedure: Copy-in parameter: On call, pass in the argument value and use it to initialize the local variable. Copy-out parameter: On return, pass out the local variable’s final value and use it to update the argument variable. Copy-in-copy-out parameter: On call, pass in the argument variable’s value. On return, pass out the updated value.  A reference parameter is implemented by passing the argument’s address. The procedure accesses the argument by indirect addressing.