Weeks 6&7: Procedures and Parameter Passing
|
|
- Clarissa Golden
- 5 years ago
- Views:
Transcription
1 CS320 Principles of Programming Languages Weeks 6&7: Procedures and Parameter Passing Jingke Li Portland State University Fall 2017 PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 1 / 45
2 Program Abstractions There are two main approaches for abstractions in a program: Procedural abstractions: Organizing large programs into collections of procedures and functions procedural programming paradigm relies on this approach Data abstractions: Organizing large programs into collections of communicating data objects object-oriented programming paradigm relies on this approach These two approaches share the same goal of treating complex things as simple black boxes, and hiding details inside the boxes. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 2 / 45
3 Issues Concerning Procedural Abstractions Runtime support for function activations Nested functions (handling scopes) Higher-order functions (handling function values) Parameter passing methods Polymorphism (later) In this unit, we treat the two words, procedure and function, asinterchangeable. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 3 / 45
4 Function Activations Each instance of function invocation at runtime is called an activation. Each activation has an associated state, which includes things such as return address, values of arguments, values of local variables, etc. The storage for these activation data is called an activation record: Saved Registers Local Variables Arguments... Return Address Normally, an activation record is created when a function is invoked and is destroyed when the function returns. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 4 / 45
5 Stack-Based AR Allocation For most non-functional programming languages, a sequence of function calls in a program are always nested, i.e. The callee function returns before the caller function does. This makes it easy to allocate activation records on a stack. Activation records, therefore, are also called stack frames. Example: f calls g. Before the call:. Caller f s AR Dynamic Link Saved Registers Local Variables Arguments... Return Address Stack PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 5 / 45
6 Stack-Based AR Allocation Example: f calls g. During the call:. Caller f s AR Callee g s AR Stack Dynamic Link Saved Registers Local Variables Arguments... Return Address Dynamic Link Saved Registers Local Variables Arguments... Return Address always pointing to caller s AR PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 6 / 45
7 Stack-Based AR Allocation Example: f calls g. After the call:. Caller f s AR Dynamic Link Saved Registers Local Variables Arguments... Return Address Stack PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 7 / 45
8 Free Variables Recall that variables in a function are either bound or free: function s parameters and local variables are bound other variables that are referenced in the function are free Example: In the following programs, the varaible x is a free variable: C int g(int z) { return x + z; Haskell g z = x + z Note: Free variables can happen in functions of both imperative and functional programs Free variables are still defined, it s just that they are not defined inside the function where they are being referenced PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 8 / 45
9 Free Variables Question: In the functional language s case, does the occurrence of free variables in a function violate the referential transparent property? Haskell g z = x + z Answer: No. At the time a function is defined, all its free variables must be bound to immutable values. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 9 / 45
10 Free Variables There are three situations where free variables may occur. Case 1. In languages such as C, functions are all defined at the global scope level, but they can still reference global variables that are defined outside of their own scope: int x = 100; int g(int z) { return x + z; C // x is a global variable No special handling is needed for this case. Global variables are stored in the static area; their references can be handled at compile time through the use of symbolic addresses. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 10 / 45
11 Free Variables Case 2. In object-oriented languages such as Java, methods are defined within classes, and they can reference objects instance variables that are defined outside of their scope: class Test { int x = 100; int g(int z) { return x + z; Java // x is an instance variable Since objects are stored in the heap area, the addresses of instance variables are not known at compile time. Special treatment is needed for accessing these variables. (We ll see the treatment a little later.) PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 11 / 45
12 Free Variables Case 3. In block-structure languages such as Algol and Pascal, and functional languages such as ML and Haskell, functions can be defined in other functions. A nested function can reference variables defined in any of the outer scopes: Pseudo C int f(int x, int y) { // x is a param in outer scope int g(int z) { return x + z; return g(x + y); Variables defined in outer function scopes are stored in their respective function s activation records, which are allocated at runtime. Therefore, their addresses are not known at compile time. Similar to the previous case, special treatment is needed. Let s first look at why some languages support the nested function feature. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 12 / 45
13 Benefits of Nested Functions Example: Sketch of a quicksort-based sorting program. Assume initial data and final results are both in files. Steps: 1. Read data from input file to an array 2. Quicksort the array 2.1 Find a pivot element 2.2 Partition the array into two sub-arrays using the pivot 2.3 Recursively quicksort the two sub-arrays 3. Write the sorted array to output file PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 13 / 45
14 Benefits of Nested Functions Version 1: All functions are defined at the top scope level: C void sort(file in, File out) { int[] a;... a... readarray... quicksort... writearray... void readarray(file in, int *a) {... in... a... void writearray(int *a, File out) {... a... out... void quicksort(int *a, int lo, int hi) { int pivot =...;... a... pivot... partition... quicksort... void partition(int *a, int pivot, int lo, int hi) {... a... pivot... swap... void swap(int *a, int i, int j) {... a[i]... a[j]... Each function is only referenced in a local scope. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 14 / 45
15 Benefits of Nested Functions Version 2: After moving swap inside partition: Pseudo C void sort(file in, File out) { int[] a;... a... readarray... quicksort... writearray... void readarray(file in, int *a) {... in... a... void writearray(int *a, File out) {... a... out... void quicksort(int *a, int lo, int hi) { int pivot =...;... a... pivot... partition... quicksort... void partition(int *a, int pivot, int lo, int hi) { void swap(int i, int j) {... a[i]... a[j] a... pivot... swap... Function swap now has fewer parameters. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 15 / 45
16 Benefits of Nested Functions Version 3: After moving partition inside quicksort: Pseudo C void sort(file in, File out) { int[] a;... a... readarray... quicksort... writearray... void readarray(file in, int *a) {... in... a... void writearray(int *a, File out) {... a... out... void quicksort(int *a, int lo, int hi) { int pivot =...; void partition() { void swap(int i, int j) {... a[i]... a[j] a... pivot... swap a... pivot... partition... quicksort... Function partition now has no parameter at all! PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 16 / 45
17 Benefits of Nested Functions Version 4: After moving readarray, writearray, quicksort inside sort: Pseudo C void sort(file in, File out) { int[] a; void readarray() {... in... a... void writearray() {... a... out... void quicksort(int lo, int hi) { int pivot =...; void partition() { void swap(int i, int j) {... a[i]... a[j] a... pivot... swap a... pivot... partition... quicksort a... readarray... quicksort... writearray... Now all functions are defined in the scope they are referenced; and all nested functions have fewer parameters! PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 17 / 45
18 Free Variables and Dynamic Scoping In dynamic-scoped languages, nested scopes always exist, even if there is no lexical nest in the program: Pseudo C int x = 0; /* global scope level */ void level1() { int y = 1; /* dynamic scope level 1 */ level2(); void level2() { int z = 2; /* dynamic scope level 2 */ level3(); void level3() {... /* dynamic scope level 3 */ print(x+y+z); From within level3(), variables defined in all levels can be accessed. In dynamic-scoped languages, a function s free variables can come from other, non-enclosing functions. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 18 / 45
19 Handling Free Variables To support calls to nested functions, we can give the callee a pointer to the activation record of the lexically enclosing function This is known as a static link (or access link). Caller AR Callee AR Stack Dynamic Link Saved Registers Local Variables Arguments Static Link Return Addr Dynamic Link Saved Registers Local Variables Arguments Static Link Return Addr enclosing function s AR enclosing functions s AR * In the case of an OOP method, the pointer points to the heap object it belongs to. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 19 / 45
20 Handling Free Variables Example: Given the following definition: int f(int x, int y) { int g(int z) { return x+z; return g(x+y); and a call f(4,2), thestackmight look something like the display to the right during the call to g. In particular, the value for x can be found by following the static link g to function f s AR (f happens to be g s caller) f s AR g s AR y=2 x=4 static link f return addr f dynamic link f z=6 static link g return addr g dynamic link g PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 20 / 45
21 Handling Free Variables Note that the enclosing function is not always the caller function, i.e. static link dynamiclink Suppose we have the definition: int f(int x, int y) { int g(int z) { return h(x+h(z)); int h(int u) { return y*u; return g(x+y); The static link that g uses in calls to h points to f s AR, not g s AR f s AR g s AR h s AR y x static link f return addr f dynamic link f z static link g return addr g dynamic link g u static link h return addr h dynamic link h PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 21 / 45
22 Handling Free Variables For dynamic-scoped languages, handling free variables is easier After the current AR, the next AR to visit is always the caller s AR! There is no need to introduce a static link, just use the dynamic link: Pseudo C int x = 0; /* global scope */ void level1() { int y = 1; /* dynamic scope level 1 */ level2(); void level2() { int z = 2; /* dynamic scope level 2 */ level3(); void level3() {... /* dynamic scope level 3 */ print(x+y+z); level1 s AR level2 s AR level3 s AR y=1 return addr f dynamic link f z=2 return addr g dynamic link g... return addr h dynamic link h PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 22 / 45
23 Higher-Order Functions Recall that functions that take other functions as arguments or return other functions as results are sometimes called higher-order functions. Example: int(int) f(int x) { int g(int z) { return x+z; return g; Note: int(int) represents atypeforfunctionsthat take an int argument and return an int result. In this case, g may be called after f has returned... so g may need to access f s x parameter after f has returned... so we can t just dispose of the activation record as soon as a function exits PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 23 / 45
24 Handling Higher-Order Functions A solution in this case is to allocate the activation record for f on the heap, and not on the stack Compared to stack allocation, a high overhead incurs every time an activation record is to be allocated in the heap, since a search for suitable block may need to be performed However, unused activation records can be recovered by garbage collection instead of by popping them off the stack PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 24 / 45
25 Handling Higher-Order Functions An alternative solution exists. If we don t want to keep the activation records in the heap, then we will need to save a copy of free variable x s value in the representation for g before f returns. Such a representation is called a closure. While closures are generally still allocated in the heap, they take up much less space than activation records Furthermore, closures serve as a clean representation for function values This scheme is used in many functional language implementations (and, increasingly now, also in other settings such as C++, Python, and Javascript implementations) PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 25 / 45
26 Representing Function Values Recall lambda expressions They provide a way to write functions without giving them a name. x λx.e e Many modern languages include support for anonymous functions with lambda expressions: Haskell \x -> x + 1 LISP (lambda (x) (+ x 1)) Python lambda x: x + 1 Javascript function (x) x + 1 C++11 [](int x) -> int { return x + 1; Java 8 (int x) -> x + 1 PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 26 / 45
27 Representing Function Values Example: The previous function definition: int(int) f(int x, int y) { int g(int z) { return x+z; return g; Rewritten using a lambda expression: int(int) f(int x, int y) { return (\z -> x+z); PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 27 / 45
28 Representing Function Values Question: How should we represent function values of type int(int)? There are many different values, including: (\z -> x+z), (\x -> x+1), (\x -> x*2), (\x -> f(g(x))),... We need a uniform, but flexible way to represent them A common answer is to represent functions like these by a pointer to a closure, a heap allocated record that contains: a code pointer (i.e., the code for the function) the values of its free variables Note: Because we re making copies of the free variables, we usually require them to be immutable. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 28 / 45
29 Closures Every function of type int(int) will be represented using the same basic structure: codeptr The code pointer and list of free variables vary from one function value to the next: (\z -> x+z) codeptr1 x (\x -> x+1) (\x -> x*2) codeptr2 codeptr3 (\x -> f(g(x))) codeptr4 f g PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 29 / 45
30 Constructing and Calling Closures Constructing a closure: make an runtime system call to allocate the closure record store the values of the free variables into the record Calling a function via a closure: add a pointer to the closure as an extra initial argument (to provide access to any free variables) make an indirect call to the code pointed to by the first field of the closure Accessing free variables: within the function code, free variables are referenced via the closure argument known functions without free variables don t need a closure argument and can be called directly PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 30 / 45
31 Closures vs. Objects Invoking an unknown function through a closure is very similar to invoking a method of an object: Method invocations pass the object itself as an implicit argument Closures are like objects with a single method Free variables correspond to object fields In Java 8, lambda expressions are just a convenient way to write local, anonymous definitions of single-method classes. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 31 / 45
32 Parameter Passing Each function operates in in its own local environment plus surrounding environments defined by the language s scope rules. When a function is invoked, it is necessary to pass parameters from the caller to the callee. A basic question concerning parameter passing is: Question: For each parameter, what exactly is passed from the caller to the callee the parameter s address (l-value)? its content (r-value)? or something else? Answers to this question define parameter passing methods: Call-by-value (passing r-values) Call-by-reference (passing l-values) Call-by-name (passing via name substitutions) Call-by-value-result (hybrid between by-value and by-reference) PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 32 / 45
33 Call-by-Value Each actual argument is evaluated to a value before call. On entry, value is copied to formal parameter; which behaves just like a local variable. Advantages: Simple; easy to understand! Formal parameters can be used as local variables, Updating them doesn t affect actuals in calling function: double hyp(double a, double b) { a = a * a; b = b * b; return sqrt(a+b); PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 33 / 45
34 Problems with Call-by-Value Can be inefficient if value is large: typedef struct {double a1, a2,..., a10; vector; double dotprod(vector v, vector w) { return v.a1 * w.a1 + v.a2 * w.a v.a10 * w.a10; vector v1,v2; double d = dotprod(v1,v2); // copy 20 doubles Cannot affect calling environment directly: void swap(int i, int j) { int t; t = i; i = j; j = t; swap(a[p], a[q]); // has no effect on array a! Can return result only through (the single) return value. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 34 / 45
35 Call-by-Reference Pass the address of each actual parameter. On entry, the formal is bound to the address, providing a reference to the actual parameter from within the callee. If actual argument doesn t have an l-value (e.g., ), either: evaluateitintoatemporarylocationandpassitsaddress,or treatasanerror Advantages: No more large copying Actual parameter can be updated Now swap, etc.,workfine! PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 35 / 45
36 Problems with Call-by-Reference Accesses are slower address must be dereferenced to get value Lots of opportunity for aliasing problems, e.g., // multiplying matrices a and b into c int** mtxmult(int n, int **a, int **b, int **c) { int i, j, k; for (i=0; i<n; i++) for (j=0; j<n; j++) for (k=0; k<n; k++) c[i][j] += a[i][k] * b[k][j]; return c; mtxmult(a, b, a); // oops! Question: Can we combine the simplicity of call-by-value with the efficiency for large values of call-by-reference? PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 36 / 45
37 CandC++ ssolutions Calwaysusescall-by-value. But record (struct) r-values are the actual contents, while array r-values are pointers to the contents; hence array contents do not get copied when arrays are passed as parameters In addition, programmers can take the address of a variable explicitly, and pass that to obtain call-by-ref-like behavior swap(int *a, int *b) { int t; t = *a; *a = *b; *b = t; swap(&a[p],&a[q]); PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 37 / 45
38 CandC++ ssolutions C++ inherits the above properties of C. Furthermore, it supports call-by-reference parameters through the use of reference variables. swap(int &a, int &b) { int t; t = a; a = b; b = t; swap(a[p], a[q]); Note: Mixing explicit and implicit pointers can be very confusing! swap(int &a, int *b) { int t; t = a; a = *b; *b = t; swap(a[p],&a[q]); PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 38 / 45
39 Pascal and Ada s Solutions In Pascal, Ada, and similar languages, r-values of both arrays and records are the actual contents. However, they permit the programmer to specify the intended use of each parameter: in param is for passing value of the actual into the function out param is for passing value of the formal param back to the actual in out param is for passing value into as well as out from the function The idea is to let the compiler to decide which parameter passing method to use for each parameter. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 39 / 45
40 Java s Solution Java has only call-by-value mode. However, in Java, a variable representing an object is a reference to the object, instead of its content. When an object is passed as a parameter, only its reference is copied. This reference model of variables also provides some call-by-reference-like benefits when an object is passed as an actual parameter, its content can be updated in the function: class A { int i = 0;... class B { void sub(a a) { a.i = 5; void test() { A x = new A(); sub(x); System.out.println(x.i); // prints 5 PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 40 / 45
41 How Does This Differ from Call-by-Reference? Consider: class A { int i = 0;... class B { void sub(a a) { a = new A(); // parameter a gets modified here a.i = 5; void test() { A x = new A(); sub(x); System.out.println(x.i); // prints 0 Updating formal parameters in the function affects only local copy. PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 41 / 45
42 Call-by-Name The idea is from β-reduction of functional programming. In C and some other languages, macros are used to define simple functions. The user interface of a macro resembles that of a function: #define max(a,b) ((a)>(b)? (a) : (b)) v = max(x,y); When a macro is called, each formal parameter is literally replaced by the corresponding actual parameter: max(x+1,y-2) ((x+1)>(y-2)? (x+1) : (y-2)) However, macros and functions are fundamentally different: Macros are called at compile-time (or pre-compile-time), functions are called at runtime Macros can not contain recursion PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 42 / 45
43 Call-by-Name (cont.) But blind substitution is dangerous because of possible variable capture : #define swap(x,y) {int t; t=x; x=y; y=t; swap(a[t],a[q]); The call expands to {int t; t=a[t]; a[t]=a[q]; a[q]=t; Here t is captured by the declaration in the macro, and is undefined at its first use. Call-by-name is actually substitution with renaming where necessary. Flexible, but potentially very confusing, and inefficient to implement If language has no updatable variables (as in pure functional languages), call-by-name gives a beautifully simple semantics for function calls PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 43 / 45
44 Call-by-Value-Result Each actual argument is evaluated to a value before call On entry, value is bound to formal parameter just like a local variable Updating formal parameters doesn t affect actuals in calling function... so far it looks just like call-by-value Upon exit, the final contents of the formal parameters are copied into the actuals It behaves very much like call-by-reference in most normal situations, but may give different results when concurrency or aliasing are involved: type t is record a,b: integer; end record; r : t; procedure foo(s: in out t) is begin r.a := 2; s.a := s.a + 3; end foo; r.a := 1; foo(r); print(r.a); (* what's the value of r.a? *) PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 44 / 45
45 Summary Each function invocation requires a storage to keep its state information, which is called an activation record (AR); For non-functional languages, ARs are allocated on the runtime stack For handling nested functions, a common approach is to set up a static link in a function AR to point to the enclosing function s AR Function values can be represented by closure records that pair a code pointer with a list of variable values For a language with higher-order functions, ARs or closures need to be allocated on the heap, because a function value may have a longer lifetime than the function that created it There are several parameter passing methods: by value, by reference, by name, and by value-result; each method has its unique advantages over the others PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 45 / 45
CS558 Programming Languages
CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.
More informationCS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University
CS558 Programming Languages Winter 2018 Lecture 4a Andrew Tolmach Portland State University 1994-2018 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.
More informationConcepts Introduced in Chapter 7
Concepts Introduced in Chapter 7 Storage Allocation Strategies Static Stack Heap Activation Records Access to Nonlocal Names Access links followed by Fig. 7.1 EECS 665 Compiler Construction 1 Activation
More informationCS558 Programming Languages. Winter 2013 Lecture 4
CS558 Programming Languages Winter 2013 Lecture 4 1 PROCEDURES AND FUNCTIONS Procedures have a long history as an essential tool in programming: Low-level view: subroutines give a way to avoid duplicating
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter
More informationScope, Functions, and Storage Management
Scope, Functions, and Storage Management Implementing Functions and Blocks cs3723 1 Simplified Machine Model (Compare To List Abstract Machine) Registers Code Data Program Counter (current instruction)
More informationG Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University
G22.2110-001 Programming Languages Spring 2010 Lecture 4 Robert Grimm, New York University 1 Review Last week Control Structures Selection Loops 2 Outline Subprograms Calling Sequences Parameter Passing
More informationProcedure and Object- Oriented Abstraction
Procedure and Object- Oriented Abstraction Scope and storage management cs5363 1 Procedure abstractions Procedures are fundamental programming abstractions They are used to support dynamically nested blocks
More informationTypical Runtime Layout. Tiger Runtime Environments. Example: Nested Functions. Activation Trees. code. Memory Layout
Tiger Runtime Environments Compile-time environments are just symbol tables; they are used to assist static semantic analysis, code generation and code optimization. Run-time environments are about how
More informationCSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:
Expression evaluation CSE 504 Order of evaluation For the abstract syntax tree + + 5 Expression Evaluation, Runtime Environments + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 1 2 (. Contd
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 15: Review and Functional Programming Zheng (Eddy) Zhang Rutgers University March 19, 2018 Class Information Midterm exam forum open in Sakai. HW4 and
More informationRun Time Environment. Activation Records Procedure Linkage Name Translation and Variable Access
Run Time Environment Activation Records Procedure Linkage Name Translation and Variable Access Copyright 2015, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at the University
More informationExample. program sort; var a : array[0..10] of integer; procedure readarray; : function partition (y, z :integer) :integer; var i, j,x, v :integer; :
Runtime Environment Relationship between names and data objects (of target machine) Allocation & de-allocation is managed by run time support package Each execution of a procedure is an activation of the
More informationChapter 9 Subprograms
Chapter 9 Subprograms We now explore the design of subprograms, including parameter-passing methods, local referencing environment, overloaded subprograms, generic subprograms, and the aliasing and problematic
More informationFunctions - Lecture 7. Nested functions. Another example. A Nested Function. Josef Svenningsson
Functions - Lecture 7 Josef Svenningsson Nested functions A Nested Function Suppose we extended Javalette with nested functions. double hypsq(double a, double b) { double square(double d) { return d *
More informationCS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline
CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can
More informationCSC 533: Organization of Programming Languages. Spring 2005
CSC 533: Organization of Programming Languages Spring 2005 Language features and issues variables & bindings data types primitive complex/structured expressions & assignments control structures subprograms
More informationChapter 5. Names, Bindings, and Scopes
Chapter 5 Names, Bindings, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Scope Scope and Lifetime Referencing Environments Named Constants 1-2 Introduction Imperative
More informationTopics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited
CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation
More informationNames, Bindings, Scopes
Names, Bindings, Scopes Variables In imperative l Language: abstractions of von Neumann machine Variables: abstraction of memory cell or cells Sometimes close to machine (e.g., integers), sometimes not
More informationCSc 520 final exam Wednesday 13 December 2000 TIME = 2 hours
NAME s GRADE Prob 1 2 3 4 5 I II III Σ Max 12 12 12 12 12 26 26 26 100(+... ) Score CSc 520 exam Wednesday 13 December 2000 TIME = 2 hours Write all answers ON THIS EXAMINATION, and submit it IN THE ENVELOPE
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions
More informationProgramming Languages Third Edition. Chapter 7 Basic Semantics
Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol
More informationProgramming Languages Third Edition. Chapter 10 Control II Procedures and Environments
Programming Languages Third Edition Chapter 10 Control II Procedures and Environments Objectives Understand the nature of procedure definition and activation Understand procedure semantics Learn parameter-passing
More informationTypes and Type Inference
CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level
More informationCA Compiler Construction
CA4003 - Compiler Construction David Sinclair When procedure A calls procedure B, we name procedure A the caller and procedure B the callee. A Runtime Environment, also called an Activation Record, is
More informationcs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides.
cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. We are looking for homework graders. If you are interested, send mail to cs242cs.stanford.edu
More informationChapter 5 Names, Binding, Type Checking and Scopes
Chapter 5 Names, Binding, Type Checking and Scopes Names - We discuss all user-defined names here - Design issues for names: -Maximum length? - Are connector characters allowed? - Are names case sensitive?
More informationCompilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1
Compilers 8. Run-time Support Laszlo Böszörmenyi Compilers Run-time - 1 Run-Time Environment A compiler needs an abstract model of the runtime environment of the compiled code It must generate code for
More informationRun-time Environments
Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction
More informationRun-time Environments
Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction
More informationNames, Scopes, and Bindings II. Hwansoo Han
Names, Scopes, and Bindings II Hwansoo Han Scope Rules A scope is textual region where bindings are active A program section of maximal size Bindings become active at the entry No bindings change in the
More informationCS 345. Functions. Vitaly Shmatikov. slide 1
CS 345 Functions Vitaly Shmatikov slide 1 Reading Assignment Mitchell, Chapter 7 C Reference Manual, Chapters 4 and 9 slide 2 Procedural Abstraction Can be overloaded (e.g., binary +) Procedure is a named
More informationClosures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming
Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming Summary 1. Predictive Parsing 2. Large Step Operational Semantics (Natural) 3. Small Step Operational Semantics
More informationRun-time Environments - 2
Run-time Environments - 2 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.
More informationDesign Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8
Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns
More informationInformatica 3 Marcello Restelli
Informatica 3 Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Operational Semantics We describe the semantics of a programming language by means of an abstract semantic
More informationPrinciples of Programming Languages
Ting Zhang Iowa State University Computer Science Department Lecture Note 16 October 26, 2010 Control Abstraction: Subroutines 1 / 26 Outline 1 Subroutines 2 Parameter Passing 3 Generic Subroutines 2 /
More informationClosures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming
Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming t ::= x x. t t t Call-by-value big-step Operational Semantics terms variable v ::= values abstraction x.
More informationReferences and pointers
References and pointers Pointers are variables whose value is a reference, i.e. an address of a store location. Early languages (Fortran, COBOL, Algol 60) had no pointers; added to Fortran 90. In Pascal,
More informationProcedures and Run-Time Storage
Procedures and Run-Time Storage Compiler Design CSE 504 1 Parameterless Procedures 2 Parameter Passing 3 Storage Organization Last modifled: Mon Mar 21 2016 at 12:11:19 EDT Version: 1.3 20:58:09 2012/04/09
More informationCSE 307: Principles of Programming Languages
1 / 26 CSE 307: Principles of Programming Languages Names, Scopes, and Bindings R. Sekar 2 / 26 Topics Bindings 1. Bindings Bindings: Names and Attributes Names are a fundamental abstraction in languages
More informationCIT Week13 Lecture
CIT 3136 - Week13 Lecture Runtime Environments During execution, allocation must be maintained by the generated code that is compatible with the scope and lifetime rules of the language. Typically there
More informationPrinciples of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004
Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?
More informationCompiler construction
Compiler construction Lecture 7: Functions Nested functions Magnus Myreen Spring 2018 Chalmers Uniersity of Technology Gothenburg Uniersity A Nested Function Another example To make nested functions useful
More informationCS 415 Midterm Exam Spring 2002
CS 415 Midterm Exam Spring 2002 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Good Luck! Score Fortran Algol 60 Compilation Names, Bindings, Scope Functional Programming
More informationNOTE: Answer ANY FOUR of the following 6 sections:
A-PDF MERGER DEMO Philadelphia University Lecturer: Dr. Nadia Y. Yousif Coordinator: Dr. Nadia Y. Yousif Internal Examiner: Dr. Raad Fadhel Examination Paper... Programming Languages Paradigms (750321)
More informationProcedures and Run-Time Storage
Procedures and Run-Time Storage Compiler Design CSE 504 1 Parameterless Procedures 2 Parameter Passing 3 Storage Organization Last modifled: Mon Mar 21 2016 at 12:11:19 EDT Version: 1.3 20:58:09 2012/04/09
More informationRun Time Environment. Procedure Abstraction. The Procedure as a Control Abstraction. The Procedure as a Control Abstraction
Procedure Abstraction Run Time Environment Records Procedure Linkage Name Translation and Variable Access Copyright 2010, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at
More informationTypes and Type Inference
Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion
More informationFunctions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)
CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,
More informationRun-time Environments - 3
Run-time Environments - 3 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time
More informationOrganization of Programming Languages CS 3200/5200N. Lecture 09
Organization of Programming Languages CS 3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Control Flow Control flow = the flow of control, or execution
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and
More informationCS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
More informationSubprograms. Copyright 2015 Pearson. All rights reserved. 1-1
Subprograms Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling Subprograms Indirectly
More informationCOP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen
COP4020 Programming Languages Subroutines and Parameter Passing Prof. Robert van Engelen Overview Parameter passing modes Subroutine closures as parameters Special-purpose parameters Function returns COP4020
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 4a Andrew Tolmach Portland State University 1994-2017 Semantics and Erroneous Programs Important part of language specification is distinguishing valid from
More informationProgrammiersprachen (Programming Languages)
2016-05-13 Preface Programmiersprachen (Programming Languages) coordinates: lecturer: web: usable for: requirements: No. 185.208, VU, 3 ECTS Franz Puntigam http://www.complang.tuwien.ac.at/franz/ps.html
More informationModule 27 Switch-case statements and Run-time storage management
Module 27 Switch-case statements and Run-time storage management In this module we will discuss the pending constructs in generating three-address code namely switch-case statements. We will also discuss
More informationDeclaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:
Declarations Based on slides from K. N. King Declaration Syntax General form of a declaration: declaration-specifiers declarators ; Declaration specifiers describe the properties of the variables or functions
More informationSubprograms. Bilkent University. CS315 Programming Languages Pinar Duygulu
1 Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University Introduction 2 Two fundamental abstraction facilities Process abstraction Emphasized from early days Data abstraction Emphasized
More informationCS 314 Principles of Programming Languages. Lecture 13
CS 314 Principles of Programming Languages Lecture 13 Zheng Zhang Department of Computer Science Rutgers University Wednesday 19 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:
More informationCS558 Programming Languages. Winter 2013 Lecture 3
CS558 Programming Languages Winter 2013 Lecture 3 1 NAMES AND BINDING One essential part of being a high-level language is having convenient names for things: variables constants types functions etc. classes
More informationInformal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility
Informal Semantics of Data semantic specification names (identifiers) attributes binding declarations scope rules visibility 1 Ways to Specify Semantics Standards Documents (Language Definition) Language
More informationThe Procedure Abstraction
The Procedure Abstraction Procedure Abstraction Begins Chapter 6 in EAC The compiler must deal with interface between compile time and run time Most of the tricky issues arise in implementing procedures
More informationProgramming Languages & Paradigms PROP HT Course Council. Subprograms. Meeting on friday! Subprograms, abstractions, encapsulation, ADT
Programming Languages & Paradigms PROP HT 2011 Lecture 4 Subprograms, abstractions, encapsulation, ADT Beatrice Åkerblom beatrice@dsv.su.se Course Council Meeting on friday! Talk to them and tell them
More informationProgramming Languages Third Edition. Chapter 9 Control I Expressions and Statements
Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE
More informationChapter 9. Subprograms
Chapter 9 Subprograms Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling
More informationProgrammin Languages/Variables and Storage
Programmin Languages/Variables and Storage Onur Tolga Şehitoğlu Computer Engineering 4 Mart 2007 Outline 1 Storage Array Variables 2 Semantics of Assignment 3 Variable Lifetime Global Lifetime Local Lifetime
More informationChapter 9. Subprograms
Chapter 9 Subprograms Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling
More informationTypes. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus
Types Type checking What is a type? The notion varies from language to language Consensus A set of values A set of operations on those values Classes are one instantiation of the modern notion of type
More informationLecture 16: Static Semantics Overview 1
Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing
More informationCompiler construction
Compiler construction Lecture 7: Functions Nested functions Alex Gerdes Vårtermin 2016 Chalmers Uniersity of Technology Gothenburg Uniersity A Nested Function Another example To make nested functions useful
More informationCSE 504: Compiler Design. Runtime Environments
Runtime Environments Pradipta De pradipta.de@sunykorea.ac.kr Current Topic Procedure Abstractions Mechanisms to manage procedures and procedure calls from compiler s perspective Runtime Environment Choices
More informationUNIT V Sub u P b ro r g o r g a r m a s
UNIT V SubPrograms Outline Subprograms Parameter Passing Parameter correspondence Main Issues when designing subroutine in programming languages Parameter passing techniques Characteristics of Subprogram
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 13: Names, Scopes and Bindings Zheng (Eddy) Zhang Rutgers University February 28, 2018 Review: Names, Scopes and Binding What s in a name? Each name means
More informationCMSC 4023 Chapter 9. Fundamentals of Subprograms Introduction
9. 9.1. Introduction Two fundamental abstraction facilities Process abstraction Emphasized from early days Data abstraction Emphasized in the1980s 9.2. 9.2.1. General Subprogram Characteristics Each subprogram
More information1 Lexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler
More informationProgramming Languages: Lecture 11
1 Programming Languages: Lecture 11 Chapter 9: Subprograms Jinwoo Kim jwkim@jjay.cuny.edu Chapter 9 Topics 2 Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments
More informationMemory Management and Run-Time Systems
TDDD55 Compilers and Interpreters TDDB44 Compiler Construction Memory Management and Run-Time Systems Part of the Attribute Grammar Material Presented at the Beginning of this Lecture Peter Fritzson IDA,
More informationCPS 506 Comparative Programming Languages. Programming Language
CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support
More informationTypes, Type Inference and Unification
Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2017 Lecture 3a Andrew Tolmach Portland State University 1994-2017 Binding, Scope, Storage Part of being a high-level language is letting the programmer name things: variables
More informationThe PCAT Programming Language Reference Manual
The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language
More informationCS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych
CS125 : Introduction to Computer Science Lecture Notes #38 and #39 Quicksort c 2005, 2003, 2002, 2000 Jason Zych 1 Lectures 38 and 39 : Quicksort Quicksort is the best sorting algorithm known which is
More informationLectures Basics in Procedural Programming: Machinery
Lectures 3-4-5-6 Basics in Procedural Programming: Machinery February 21-28, 2014 2014-03-01 11:04:07 1/48 Lecture3-6E-2014.pdf (#21) Basics in Procedural Programming: Machinery Naming and Binding Mutable
More informationLecture 9: Procedures & Functions. CS 540 George Mason University
Lecture 9: Procedures & Functions CS 540 George Mason University Procedures/Functions Control Abstraction call/return semantics, parameters, recursion Controlled Namespace Scope (local/non-local), binding,
More informationHigh Performance Computing and Programming, Lecture 3
High Performance Computing and Programming, Lecture 3 Memory usage and some other things Ali Dorostkar Division of Scientific Computing, Department of Information Technology, Uppsala University, Sweden
More informationRun-time Environments. Lecture 13. Prof. Alex Aiken Original Slides (Modified by Prof. Vijay Ganesh) Lecture 13
Run-time Environments Lecture 13 by Prof. Vijay Ganesh) Lecture 13 1 What have we covered so far? We have covered the front-end phases Lexical analysis (Lexer, regular expressions,...) Parsing (CFG, Top-down,
More informationAttributes of Variable. Lecture 13: Run-Time Storage Management. Lifetime. Value & Location
Attributes of Variable Lecture 13 Run-Time Storage Management CSC 131 Kim Bruce Scope Lifetime Location Value Done! Lifetime Value & Location FORTRAN - all allocated statically - Stack-based (C/C++/Java/Pascal/...)
More informationAdministration CS 412/413. Advanced Language Support. First-class vs. Second-class. First-class functions. Function Types
Administration CS 412/413 Introduction to Compilers and Translators Andrew Myers Cornell University Lecture 33: First-class functions 21 April 00 Programming Assignment 6 handed out today register allocation
More informationCSE 504: Compilers. Expressions. R. Sekar
CSE 504: Compilers Expressions R. Sekar Expression evaluation 1 / 83 Order of evaluation For the abstract syntax tree + + 5 + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 Expression evaluation
More informationCSCI312 Principles of Programming Languages!
CSCI312 Principles of Programming Languages! Scope Xu Liu ! 4.1 Syntactic Issues! 4.2 Variables! 4.3 Scope! 4.4 Symbol Table! 4.5 Resolving References! 4.6 Dynamic Scoping! 4.7 Visibility! 4.8 Overloading!
More informationIntermediate Representations & Symbol Tables
Intermediate Representations & Symbol Tables Copyright 2014, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at the University of Southern California have explicit permission
More informationSemantic Analysis and Type Checking
Semantic Analysis and Type Checking The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on
More informationCompiler Theory. (Semantic Analysis and Run-Time Environments)
Compiler Theory (Semantic Analysis and Run-Time Environments) 005 Semantic Actions A compiler must do more than recognise whether a sentence belongs to the language of a grammar it must do something useful
More information