(1) ICS 313: Programming Language Theory Module 12: Subprograms.

Slides:



Advertisements
Similar presentations
ICE1341 Programming Languages Spring 2005 Lecture #16 Lecture #16 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Advertisements

Programming Languages and Paradigms
Names and Bindings.
Subprograms A subprogram allows process abstraction (as opposed to data abstraction). Characteristics –single entry point –caller suspended until control.
Overview Fundamentals of Subprograms (Sec )
Chapter 9 Subprograms Specification: name, signature, actions Signature: number and types of input arguments, number and types of output results –Book.
ISBN Chapter 9 Subprograms. Copyright © 2007 Addison-Wesley. All rights reserved.1-2 Chapter 9 Topics Introduction Fundamentals of Subprograms.
1 CHAPTER 9 SUBPROGRAM. 2 SUBPROGRAM Topics: b Definitions of subprogram b general subprogram characteristics b parameters b Functions and procedures.
Chapter 9 Subprograms.
Chapter 9 Subprograms.
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
(1) ICS 313: Programming Language Theory Chapter 10: Implementing Subprograms.
Chapter 9 Subprogram Control Consider program as a tree- –Each parent calls (transfers control to) child –Parent resumes when child completes –Copy rule.
Chapter 9 Subprograms Sections 1-5 and 9. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Two fundamental abstraction facilities.
Subprograms A subprogram allows process (as opposed to data) abstraction. Characteristics –single entry point –caller suspended until control returns from.
ISBN Chapter 9 Subprograms. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Introduction Two fundamental abstraction facilities.
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.
ISBN Chapter 9 Subprograms. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.9-2 Chapter 9 Topics Introduction Fundamentals.
ISBN Chapter 9 Subprograms and Functions –Design Issues –Local Referencing Environments –Parameter-Passing Methods –Parameters that are Subprogram.
© 2003 G. Drew Kessler and William M. Pottenger1 Subroutines (Part 1) CSE 262, Spring 2003.
1 Subprograms Fundamentals of subprograms Design issues for subprograms –Parameter-passing methods –Type checking of parameters –Static or dynamic storage.
Chapter 9 Subprograms.
Chapter Nine: Subprograms Lesson 09. What are they  Modularized code  Might return a value  Functions  Or not  Procedures  Subroutines  In object.
Programming Languages and Design Lecture 7 Subroutines and Control Abstraction Instructor: Li Ma Department of Computer Science Texas Southern University,
Runtime Environments Compiler Construction Chapter 7.
Subprograms Support process abstraction and modularity –characteristics of subprograms are that they have a single entry point the calling entity is suspended.
Chapter 9 Subprograms Fundamentals of Subprograms
Chapter 10 Implementing Subprograms. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 10 Topics The General Semantics of Calls and Returns.
April 23, ICE 1341 – Programming Languages (Lecture #16) In-Young Ko Programming Languages (ICE 1341) Lecture #16 Programming Languages (ICE 1341)
1 Chapter 9 © 2002 by Addison Wesley Longman, Inc. 9.2 Fundamentals of Subprograms - General characteristics of subprograms: 1. A subprogram has a single.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 8 Fundamental Characteristics of Subprograms 1. A subprogram has a single entry point 2. The.
CSC3315 (Spring 2008)1 CSC 3315 Subprograms Hamid Harroud School of Science and Engineering, Akhawayn University
Week 7 Subprograms. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for.
Subprograms subroutines, procedures, functions, methods.
ISBN Chapter 9 Subprograms. Copyright © 2015 Pearson. All rights reserved.1-2 Chapter 9 Topics Introduction Fundamentals of Subprograms.
Programming Languages and Paradigms Imperative Programming.
1 Languages and Compilers (SProg og Oversættere) Bent Thomsen Department of Computer Science Aalborg University With acknowledgement to Angela Guercio.
1 Subprograms In Text: Chapter 8. 2 Chapter 8: Subprograms Outline Definitions Referencing environments Parameter passing modes and mechanisms Independent.
Chapter 9 Subprograms. 2 Fundamentals of Subprograms Each subprogram has a single entry point The calling program is suspended during execution of the.
C HAPTER 9 Subprograms. CCSB314 Programming Language C HAPTER 9 T OPICS Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
1 Subroutines Structure of Programming Language. 2 Procedures and Functions There are two categories of subprograms Function: subroutine that returns.
ISBN Chapter 9 Subprograms Sections
Concepts of programming languages Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil 1-1.
Chapter 9 Subprograms. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues.
Chapter 9: Subprograms Introduction Fundamentals of Subprograms
ISBN Chapter 9 Subprograms. Corrected and improved by Assoc. Prof. Zeki Bayram, EMU, North Cyprus. Original Copyright © 2007 Addison-Wesley.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
ISBN Chapter 10 Implementing Subprograms.
Procedure Definitions and Semantics Procedures support control abstraction in programming languages. In most programming languages, a procedure is defined.
ISBN Chapter 10 Implementing Subprograms.
1 CSC 533: Programming Languages Spring 2014 Subprogram implementation  subprograms (procedures/functions/subroutines)  subprogram linkage  parameter.
Chapter 9 Chapter 9 Subprograms. The Structure of Run-Time Memory.
ISBN Chapter 9 Subprograms. Copyright © 2007 Addison-Wesley. All rights reserved.1-2 Chapter 9 Topics Introduction Fundamentals of Subprograms.
Chapter 9 Subprograms. Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing.
Chapter 9 Subprograms.
Chapter 9 Subprograms.
Principles of programming languages 4: Parameter passing, Scope rules
CSCI 3370: Principles of Programming Languages Chapter 9 Subprograms
Chapter 9 Subprograms.
CSC 533: Programming Languages Spring 2015
Chapter 9: Subprograms Sangho Ha
Subprograms In Text: Chapter 9.
Subject : T0152 – Programming Language Concept
Chapter 9 Subprograms Fundamentals of Subprograms
CSC 533: Programming Languages Spring 2018
Chapter 9 Subprograms Subprograms are the fundamental building blocks of programs and are therefore the most important concepts in programming language.
CSC 533: Programming Languages Spring 2019
Presentation transcript:

(1) ICS 313: Programming Language Theory Module 12: Subprograms

(2) Objectives Understand design issues in subprograms: parameter passing type checking overloading and parameterized procedures Subprograms Single entry One executing at a time Returns to caller

(3) Basic Subprogram Definitions Subprogram definition: - Describes the actions of the subprogram Subprogram call: - Explicit request that the subprogram be executed Subprogram header: - specifies name, parameters, return type Parameter profile (signature): - number, order, and types of parameters Protocol: - Parameter profile and return type

(4) Parameters Parameters allow the subprogram to manipulate data external to the subprogram Provide local names for external data Allow binding of local names to different data during each call Alternative: non-local variable referencing Also allows access to external data Reduces readability of subprogram Reduces flexibility of programming - Requires changing external state before passing

(5) Positional, Keyword, Defaults Positional: Matching of formal to actual parameters done via position in parameter list Keyword: labels used to match formal to actual parameters Default: Enables only a subset of actual parameters to be provided in the call

(6) Ada, C, Common Lisp, Python function COMPUTE_PAY(INCOME : FLOAT; TAX_RATE : FLOAT; EXEMPTIONS : INTEGER := 1) return FLOAT; float compute_pay(float income, float tax_rate, int exemptions = 1) (defun compute-pay (income tax-rate &key (exemptions 1)) def compute_pay(income, tax-rate, exemptions=1):

(7) Scheme and Lisp Examples (define (collectem. args) args) (define (displayall. args) (map display args)) (defun MAKE-GRAPHIC-SHAPE (instance &key (x-dimension 10 x-dimension-supplied-p) (y-dimension 20 y-dimension-supplied-p) (x-offset 0 x-offset-supplied-p) (y-offset 0 y-offset-supplied-p) &rest other-args) …) Defaults evaluated at function call time

(8) Python Examples def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): parrot(1000) parrot(action = 'VOOOOOM', voltage = ) parrot('a thousand', state = 'pushing up the daisies') parrot('a million', 'bereft of life', 'jump’) def cheeseshop(kind, *arguments, **keywords): cheeseshop('Limburger', "It's very runny, sir.", "It's really very, VERY runny, sir.", client='John Cheese', shopkeeper='Michael Palin', sketch='Cheese Shop Sketch') Defaults evaluated at function definition time! (Let’s see an example…)

(9) Procedures vs. Functions Procedures: No return value Computation results provided via: - side effects upon non-local variables. - “result” parameters (in languages that provide this facility) Functions: Invocation results in a value (the result) No side effect necessary (and typically not desired)

(10) Design Issues for Subprograms Allocation of local variables Parameter passing methods Type checking of parameters Subprograms as parameters and their evaluation environments Overloading Separate compilation

(11) Local Referencing Environments Local variables: Variables declared inside subprograms Static local variables: - Allocated once, at beginning of execution - Retains value between invocations - Fast direct addressing - Prevents recursive subprograms Stack-dynamic local variables: - Rebound each time subprogram invoked - Supports recursive subprograms - Values lost between invocations - Slower indirect addressing

(12) Parameter Passing Methods Two issues: data direction flow and data access style. Data direction flow: In mode: From actuals to formals Out mode: from formals to actuals In-out mode: both directions Data access style: Value: data value is provided. Reference: access path to data value provided See diagram p. 359

(13) Pass by Value (Call by Value) An implementation of in-mode Value of Actual used to initialize Formal Usually done by data transfer Cost of additional storage and copy Formal acts as local variable in subprogram Access usually more efficient once copied

(14) Pass by value example: Swap void swap (int x, int y) { int z; z = x; x = y; y = z; } main () { int a = 1; int b = 2; swap (a, b); return a; } What is the return value of this program? 1. Main’s a is not changed.

(15) Pass by Result (Return by Value) An implementation of out-mode Formal acts as local variable in subprogram Efficient access Value of Formal copied to Actual upon exit Also requires extra space and time to copy Combined with Pass by Value this is “Pass by Value-Result”, implementing inout-mode

(16) Pass by Result Examples Problems with actual parameter collision Header: sub(a, b) Call: sub(p, p) Value of p depends on order in which a, b copied Sub(list[i], i) Values depend on time at which address of actuals determined

(17) Pass (Call) by Reference Like pass-by-value-result, this implements inout-mode Formal receives access path (e.g., pointer) to memory cell of Actual Passing is efficient Access slower due to indirect addressing Formal used as local variable in subprogram, but assignments change the Actual Flexible but dangerous unintended changes

(18) Pass by Reference: Swap void swap (int *px, int *py) { int z; z = *px; *px = *py; *py = z; } main () { int a = 1; int b = 2; swap (&a, &b); return a; } What does this program return? 2. It works as intended.

(19) Pass by value-result pseudocode foo (x,y) { x = y; } pseudo main () { int i = 2; int j = 3; foo (i, j); return i; } What does this program return? (Ans: 3) What would this program return under pass- by-value or pass-by-reference? (Ans: 2, 3)

(20) Pass (Call) by Name As if actual textual substitution of arguments for parameters Late binding: Arguments evaluated each time they are assigned or referenced (rather than at call time) Can be flexible Potential for name conflicts Slow and difficult to implement Not common in modern programming languages

(21) Pass (Call) by Name: Swap void swap (int x, int y) { int z; z = x; x = y; y = z; } swap(a, b) => z = a; a = b; b = z; // works swap(i, A[i]) => z = i; i = A[i]; A[i] = z; // does not assign the A[i] expected

(22) Parameter passing conventions C++ Default is call-by-value & operator provides call-by-reference Java Pass by value (including references) Objects effectively passed by reference Common Lisp, Scheme, Prolog, Python Pass by value

(23) Parameter Type Checking Good for reliability but less flexible Weakly typed: LISP, Python Doesn’t check: FORTRAN 77 Do: Pascal, FORTRAN 90, Java, Ada … Optional: ANSI C double sin(x) double x; { … } double sin (double x) { … } Optional: C++ printf(const char*, …); printf(“the sum is %d\n”, sum); // sum not checked

(24) Passing Arrays Pass by reference preferred How are mapping functions computed? Java - Arrays are (single dimensional) objects - Size passed with array C, C++ - Need to know size of arrays at compile time - Separate compilation complicates this - Let’s look at the mapping function for two dimensional C arrays …

(25) Multidimensional Arrays in C

(26) Passing Arrays in C: Conclusion Thus the compiler needs to know M, the number of columns void fun (int matrix[][10]) { … } - Can’t write generic functions! Workaround: Pass pointer to array and pass array dimensions as arguments. void fun(float *mat, int rows, int cols); - Programmer does the math: *(mat + (i * cols) + j) = x - Avoid this uglyness with macros …

(27) Passing Subprograms as Parameters Examples: Accumulator (e.g., Scheme assignment) (accumulate + 0 f a next b)) (accumulate * 1 f a next b)) Numerical Integration (sampling a function) Mapping (e.g., in Python:) >>> def consquare(x):... return (x, x*x) >>> map(consquare, [1,2,3,4,5]) [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

(28) Passing Subprograms: Type Checks In typed languages, need to tell the compiler the type of the subprogram. Subprogram type is its protocol Example: Numeric Integration in Pascal procedure integrate( function f (x:real) :real; lowerbd, upperbd : real; var result : real); var funval, currarg : real; begin... funval := f(currarg);... end;

(29) Passing Subprograms: Type Checks Example: C - Only pointers can be passed - “Pointer contains protocol information” - In Caller: int strcmp(), numcmp(); swap() … sort(ptr, nlines, numcmp, swap) - In called: int (*comp)(), (*exch)(); … if ((*comp) (v[j], v(j+1]) <= 0) …

(30) Passing Subprograms: Execution Environment Shallow binding: Environment that subprogram is executed within Consistent with dynamically scoped variables Deep binding: Environment that subprogram is declared within Consistent with lexically scoped variables Ad-hoc binding: Environment that subprogram is passed from Not used

(31) Example

(32) Overloaded Subprograms Multiple subprograms with the same name Distinguished by different protocols Each subprogram has its own implementation “Ad-hoc” in the sense that there is no abstraction for the generalized program (the programmer writes each version)

(33) Overloaded Subprograms public static void foo(Integer i) { do some Integer stuff … } public static void foo(String s) { do some String stuff … } public static void foo(String s, int len) { do some other String stuff … } // More than one way of overloading: public int compareTo(Object rhs) { … }

(34) Another Use of Overloading public static void writeBackwards(String s) { int len = s.length(); if (len == 0) { System.out.println(); } else { System.out.print(s.charAt(len - 1)); writeBackwards(s.substring(0, len - 1)); }

(35) Another Use Continued public static void writeBackwards2(String s) { writeBackwards2(s, s.length()); } public static void writeBackwards2(String s, int len) { if (len == 0) { System.out.println(); } else { System.out.print(s.charAt(len - 1)); writeBackwards2(s, len - 1); }

(36) Generic Subprograms Subprogram templates that can be “instantiated” for different types of parameters Each subprogram shares a common “shell” of code Differences are restricted to parameters: “parametric polymorphism” Example: C++ Templates template Type max(Type first, Type second) { return first > second ? first : second; } Compiler makes copy of code for each type Dynamic binding of types avoids this (e.g., Java methods)

(37) Compilation Large system development must avoid total recompilation whenever possible Separate compilation (e.g., Java): Compilation units can be compiled at different times Requires access to other units during compilation for type checking Independent compilation (e.g., FORTRAN 77): Units can be compiled without access to others Errors at compilation unit interfaces are caught at link-time or run-time

(38) Coroutines Symmetric control (“quasi-concurrency”) Mutually invoke each other Multiple entry points Invocation resumes computation at an entry point State is remembered Let’s look at some examples in Scheme Implemented with Call-with-current- continuation (prepare for mind-warp) This captures the state of the runtime stack … a radical idea!

(39) End of module