
Tail Calls CMSC 330: Organization of •A tail call is a function call that is the last thing a Programming Languages function does before it returns let add x y = x + y let f z = add z z (* tail call *) let rec length = function More on Scope [] -> 0 | (_::t) -> 1 + (length t) (* not a tail call *) Operational Semantics let rec length a = function [] -> a | (_::t) -> length (a + 1) t (* tail call *) CMSC 330 2 Tail Recursion Tail Recursion (cont’d) • Recall that in OCaml, all looping is via recursion let rec length l = match l with l [1;2] – Seems very inefficient [] -> 0 [2] – Needs one stack frame for recursive call | (_::t) -> 1 + (length t) l [] length [1; 2] l • A function is tail recursive if it is recursive and eax: 012 the recursive call is a tail call • However, if the program is tail recursive... – Can instead reuse stack frame for each recursive call CMSC 330 3 CMSC 330 4 Tail Recursion (cont’d) Names and Binding • Programs use names to refer to things let rec length a l = match l with a 012 – E.g., in x = x + 1, x refers to a variable [] -> a | (_::t) -> (length (a + 1) t) l [1;2][2][] •A binding is an association between a name and what it refers to length 0 [1; 2] – int x; /* x is bound to a stack location containing an int */ eax: 2 – int f (int) { ... } /* f is bound to a function */ – class C { ... } /* C is bound to a class */ – let x = e1 in e2 (* x is bound to e1 *) • The same stack frame is reused for the next call, since we’d just pop it off and return anyway CMSC 330 5 CMSC 330 6 1 Name Restrictions Names and Scopes • Languages often have various restrictions on • Good names are a precious commodity names to make lexing and parsing easier – They help document your code – Names cannot be the same as keywords in the – They make it easy to remember what names language correspond to what entities – OCaml function names must be lowercase – OCaml type constructor and module names must be • We want to be able to reuse names in different, uppercase non-overlapping regions of the code – Names cannot include special characters like ;,:etc • Usually names are upper- and lowercase letters, digits, and _ (where the first character can’t be a digit) • Some languages also allow more symbols like ! or - CMSC 330 7 CMSC 330 8 Names and Scopes (cont’d) Example void w(int i) { •iis in scope •A scope is the region of a program where a ... binding is active } – in the body of w, the body of y, and after the – The same name in a different scope can refer to a void x(float j) { declaration of j in z different binding (refer to a different program object) ... – but all those i’s are } different • A name is in scope if it's bound to something void y(float i) { ... •jis in scope within the particular scope we’re referring to } – in the body of x and z void z(void) { int j; char *i; ... } CMSC 330 9 CMSC 330 10 Ordering of Bindings Order of Bindings – OCaml • Languages make various choices for when • let x = e1 in e2 – x is bound to e1 in scope of e2 declarations of things are in scope • let rec x = e1 in e2 – x is bound in e1 and in e2 let x = 3 in let y = x + 3 in... (* x is in scope here *) let x = 3 + x in ... (* error, x not in scope *) let rec length = function [] -> 0 | (h::t) -> 1 + (length t) (* ok, length in scope *) in ... CMSC 330 11 CMSC 330 12 2 Order of Bindings – C Order of Bindings – Java • All declarations are in scope from the • Declarations are in scope from the declaration declaration onward onward, except for methods and fields, which int i; are in scope throughout the class int j = i; /* ok, i is in scope */ i = 3; /* also ok */ class C { void f(){ void f(...) { ... } ...g()... // OK } int i; int j = j + 3; /* error */ void g(){ f(...); /* ok, f declared */ ... } } f(...); /* may be error; need prototype (or oldstyle C) */ void f(...) { ... } CMSC 330 13 CMSC 330 14 Shadowing Names Namespaces • Shadowing is rebinding a name in an inner • Languages have a “top-level” or outermost scope scope to have a different meaning – Many things go in this scope; hard to control collisions – May or may not be allowed by the language • Common solution seems to be to add a hierarchy – OCaml: Modules C OCaml •List.hd, String.length, etc. int i; letg=3;; •opento add names into current scope letgx=x+3;; void f(float i) { – Java: Packages Java • java.lang.String, java.awt.Point, etc. { void h(int i) { • import to add names into current scope char *i = NULL; { ... – C++: Namespaces float i; // not allowed } ... • namespace f { class g { ... } }, f::g b, etc. } • using namespace to add names to current scope } } CMSC 330 15 CMSC 330 16 Mangled Names Static Scope Recall • What happens when these names need to be •In static scoping, a name refers to its closest seen by other languages? binding, going from inner to outer scope in the – What if a C program wants to call a C++ method? program text • C doesn’t know about C++’s naming conventions – Languages like C, C++, Java, Ruby, and OCaml are statically scoped • For multilingual communication, names are int i; often mangled into some flat form { – E.g., classC{intf(int *x, int y) { ... } } int j; becomes symbol __ZN1C3fEPii in g++ – E.g., native valueOf(int) in java.lang.String { float i; corresponds to the C function Java_java_lang_String_valueOf__I j = (int) i; } } CMSC 330 17 CMSC 330 18 3 Free and Bound Variables Static Scoping and Nested Functions • The bound variables of a scope are those • To allow arbitrary nested functions with higher- names that are declared in it order functions and static scoping, we needed • If a variable is not bound in a scope, it is free closures – The bindings of variables which are free in a scope let add x = (fun y -> x + y) are "inherited" from declarations of those variables in outer scopes in static scoping (add3)4 <closure> 4 3+4 7 {/*1*/ j is bound in int j; scope 1 {/*2*/ float i; i is bound in j is free in j = (int) i; scope 2 scope 2 } } CMSC 330 19 CMSC 330 20 Nested Functions (cont’d) Example • We need closures for upward funargs x letfx= – Functions that are returned by other functions letgy=x+y g y = x + y in y g3 • If we only have downward funargs, then we don’t need full closures – These are functions that are only passed inward – So when they’re called, any nonlocal variables they • When g is called, x is still on the stack access from outer scopes are still around CMSC 330 21 CMSC 330 22 Example Downward Funargs x • It turns out that if we only pass functions letappfz=fz app f z = f z downward, there are cheaper implementation f let f x = strategies for static scoping than closures letgy=x+yingy=x+y z app g 3 y • They're called static links and displays, and they're used by – Pascal and Algol-family languages • When g is called, x is still on the stack – gcc nested functions • We won’t go into details, though (CMSC 430 covers these in exciting detail.) CMSC 330 23 CMSC 330 24 4 Dynamic Scope Nested Dynamic Scopes • In a language with dynamic scoping, a name • Full dynamic scopes can be nested refers to its closest binding at runtime – Static scope relates to the program text – LISP was the common example – Dynamic scope relates to program execution trace Perl (the keyword local introduces dynamic scope) Scheme (top-level scope only is dynamic) $l = "global"; (define f (lambda () a)) ; defines a no-argument function which returns a sub A { local $l = "local"; (define a 3) ; bind a to 3 B(); } (f) ; calls f and returns 3 global (define a 4) (f) ; calls f and returns 4 sub B { print "$l\n"; } local global B(); A(); B(); CMSC 330 25 CMSC 330 26 Static vs. Dynamic Scope Static scoping Dynamic scoping CMSC 330: Organization of – Local understanding of – Can be hard to Programming Languages function behavior understand behavior of functions – Know at compile-time – Requires finding name what each name refers bindings at runtime to Operational Semantics – Easier to implement (just – A bit trickier to keep a global table of implement stacks of variable/value bindings ) CMSC 330 27 Introduction Roadmap: Compilation of program • So far we’ve looked at regular expressions, Grammar: Program: (Rec Des) Parsing: Postorder: SA X = 2 + 3 ast postfix A id = E X 2 3 + = automata, and context-free grammars E T+E | T = T P * T | P – These are ways of defining sets of strings P id | n | (E) X + – We can use these to describe what programs you 2 3 can write down in a language • (Almost...) Compilation: Program semantics: Push X – I.e., these describe the syntax of a language What does program Push 2 mean Push 3 Add top 2 Assign top to • What about the semantics of a language? ? second – What does a program “mean”? Is this correct? What is program supposed to do? CMSC 330 29 CMSC 330 30 5 Operational Semantics Roadmap: Semantics of a program • There are several different kinds of semantics Grammar: Program: (Rec Des) Parsing: Postorder: SA X = 2 + 3 ast postfix – Denotational: A program is a mathematical function A id = E X 2 3 + = E T+E | T = T P * T | P – Axiomatic: Develop a logical proof of a program P id | n | (E) X + • Give predicates that hold when a program (or 2 3 part) is executed Program semantics: Compilation: • We will briefly look at operational semantics Push X = Push 2 Push 3 – A program is defined by how you execute it on a value Add top 2 X + mathematical model of a machine Assign top to 2 3 second • We will look at a subset of OCaml as an example CMSC 330 31 CMSC 330 32 Evaluation OCaml Programs • We’re going to define a relation E v • E ::= x | n | true | false | [] | if E then E else E – This means “expression E evaluates to v” | fun x = E | E E • So we need a formal way of defining programs –xstands for any identifier and of defining things they may evaluate to –nstands for any integer – true and false stand for the two boolean values • We’ll use grammars to describe each of these –[]is the empty list – One to describe abstract syntax trees E – Using = in fun instead of -> to avoid some confusion later – One to describe OCaml values v CMSC 330 33 CMSC 330 34 Values Grammars for Trees • We’re just using grammars to describe trees • v ::= n | true | false | [] | v::v E ::= x | n | true | false | [] | if E then E else E – n is an integer (not a string corresp.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages9 Page
-
File Size-