Download Prof. Necula's CS 164: Compiling Higher-Order Languages with Function Types and UI Code and more Study notes Computer Science in PDF only on Docsity!
Prof. Necula CS 164 1
Compiling Higher-Order Languages
Lecture 24
Prof. Necula CS 164 2
Overview
- Why higher-order languages?
- Higher-order constructs for Cool
- Type checking
- Code generation
Prof. Necula CS 164 3
Motivating Example
- Consider a Graphical User Interface (GUI)
- Listens to events from the user (key press, mouse move) and invokes application-specific code
- Let’s write a GUI that counts the total number of events, and also prints a message for all mouse events
- We use a toolkit similar to AWT with classes:
Event
KeyEvent MouseEvent
Prof. Necula CS 164 4
User Interface Code
class KeyListener { key(e: KeyEvent) : Object { … } } class MouseListener { mouse(e: MouseEvent) : Object { … } }
class Ui { klsn: KeyListener; mlsn: MouseListener; // Application-specific listeners
setKeyListener(k: KeyListener) { klsn <- k } setMouseListener(m: MouseListener) { mlsn <- m }
dispatchEvent(e: Event) { // Dispatch event to listeners case e of k: KeyEvent => klsn.key(k); m: MouseEvent => mlsn.mouse.(m); } }
Prof. Necula CS 164 7
Overview
9 Why higher-order languages?
- Higher-order constructs for Cool
- Type checking
- Code generation
Prof. Necula CS 164 8
New Syntax for Constructing Functions
- Add new syntax for function expressions fun (x: T 1 ) : T 2 { E }
- An anonymous function with one argument x of type T 1 and result of type T 2 , and body E
- Same syntax as methods
- But can appear anywhere, not just as a features let c : Counter <- new Counter in fun (e: KeyEvent) : Object { c.incr(1) }
- The body of the function can refer to all identifiers in scope, not just to self and the attributes
- Similar syntax to lambda from Scheme or Lisp
- With types, fewer parentheses, and “modern Greek” keywords
Prof. Necula CS 164 9
New Syntax for Invoking Functions
- We add the syntax E 1 (E 2 )
- Evaluate E 1 to a function, evaluate E 2 to a value, and invoke the function with that value let listener <- (fun (e: KeyEvent) … ) in … listener(e) …
- How is E1 (E 2 ) different than E 1 ’.m(E 2 )?
- E 1 must evaluate to a function that is invoked
- E 1 ’ must evaluate to an object with a method m. The actual code that is invoked is obtained from the dispatch table of E 1 ’
- In method calls we pass both a “self” argument and actual arguments
- In function calls we pass only the actual argument
Prof. Necula CS 164 10
Extended Cool Types
- Cool expression used to evaluate to objects
- All types were Cool classes (we ignore SELF_TYPE today)
- We need to declare fields with function values
- We need types for such fields
- A function is characterized by
- The type of the arguments that it expects
- The type of the result it yields
- We add the function type T 1 → T (^2)
- type of functions with argument of type T 1 and result of type T (^2)
- We consider only functions with one argument here
- Thus, new syntax for types: T ::= C | T 1 → T 2
Prof. Necula CS 164 13
Client Code with Higher-Order Functions
class Counter { count : Int <- 0; incr(x: Int) { count <- count + x } } class Log { …; print(x: String) { ... } }
… let c : Counter <- new Counter in { ui.setKeyListener( fun (e: KeyEvent) : Object { c.incr(1) } ); ui.setMouseListener( fun (e: MouseEvent) : Object { c.incr(1); l.print(”got one”) } ) }
- No need to define the adapters MyKeyListener and MyMouseListener
- The functions can access the variables in scope
Prof. Necula CS 164 14
Side Note on Java
- Java addresses the verbosity associated with adapters in a (slightly) different way
- Java allows one to write anonymous nested classes let c : Counter <- new Counter in ui.setKeyListener(new KeyListener { key(e: KeyEvent) { c.incr(1) } });
- The KeyListener { … } is an inner class derived from KeyListener
- Advantages:
- No need to invent the name MyKeyListener
- The body of the new class can access c directly
- We have a more ambitious construct, that reduces verbosity even more
Prof. Necula CS 164 15
Overview
9 Why higher-order languages?
9 Higher-order constructs for Cool
- Type checking
- Code generation
Prof. Necula CS 164 16
Typing Rules: Function Invocation
- Typing rule for function invocations
O, M, C ` e(e 1 ) : T 2
O, M, C e : T 1 → T 2 O, M, C e 1 : T 1
- Examples: let lsn: KeyEvent → Object … in lsn(new KeyEvent)
- This rule is not sufficient: let lsn : Event → Object … in lsn(new KeyEvent)
- Is not well-typed
- We must relax the typing of actual arguments, like for method calls
Prof. Necula CS 164 19
Subtyping with Function Types
- We must also extend the · and lub operations on types
- Recall: T · T’ means that a value of type T supports all operations of values of type T’ - C · D when C is a subclass of D
- Can we have T1 → T2 · C?
- No, a function does not support method dispatch
- Can we have C · T 1 → T 2?
- No, we cannot apply an object to an argument
- Can we have S 1 → S 2 · T1 → T 2?
Prof. Necula CS 164 20
When can we have S 1 → S 2 · T 1 → T 2?
- Consider a value v of type S 1 → S (^2)
- When can we use v in place of a value of type T 1 → T 2?
- We must be able to
- Apply v to an object of type T 1 and obtain a result of type T 2
- Ok if T 1 · S 1 and S 2 · T 2
- Note the direction of subtyping on T 1 · S (^1)
- Example:
- We had this code: ui.setKeyListener( fun (e: KeyEvent) : Object { c.incr(1) });
- Another correct variant: ui.setKeyListener( fun (e: Object) : Int { c.incr(1) } );
- Because Object → Int · KeyEvent → Object
Prof. Necula CS 164 21
Least-Upper-Bound with Function Types
- lub(T 1 → T2, C) is not defined
- It is an error to return a function in a branch and an object in another
- lub(T 1 → T2, S 1 → S 2 ) = glb(T 1 , S 1 ) → lub(T 2 , S 2 )
- glb(T 1 , S 1 ) is the greatest lower bound of T 1 and S (^1)
- glb(T 1 , S 1 ) · T 1 and glb(T 1 , S 1 ) · S (^1)
- glb(C, D) = C if D · C and undefined otherwise
- glb(T 1 → T 2 , S 1 → S 2 ) = lub(T 1 , S 1 ) → glb(T 2 , S 2 )
Prof. Necula CS 164 22
Overview
9 Why higher-order languages?
9 Higher-order constructs for Cool
9 Type checking
Prof. Necula CS 164 25
Global Functions
- Case 1: Functions whose body does not refer to self, attributes, or local variables … let f: Int → Int <- fun (x: Int) : Int { x + 1 } in f(5) …
- Such functions could just as well appear at top-level
- Like functions in C or C++
- We could generate code like for a regular function
- Or, we compile this into Cool
- We create an adapter (proxy object) for the function
class MyFun { apply(x: Int) : Int { x + 1 } } … let fa: MyFun <- new MyFun in fa.apply(5) …
Prof. Necula CS 164 26
Member Functions
- Case 2: Functions that do not access local variables
- But may access self and attributes class Counter { count: Int <- 0; listener() : Object → Object { fun (x: Object): Object { count <- count + 1 } } } … let f: Object → Object = (new Counter).listener () in f(1) …
- The proxy object must have access to the host Counter
Prof. Necula CS 164 27
Translation of Member Functions
- Code from previous slide is translated as follows: class Counter { count: Int <- 0; get_count() : Int { count } set_count(x: Int) { count <- x } listener() : CounterListener { (new CounterListener).init(self) } } class CounterListener { host : Counter; init(c: Counter) { host <- c } apply(x: Object) : Object { host.set_count(host.get_count() + 1) } } … let fp: CounterListener <- (new Counter).listener () in fp.apply(1) …
Prof. Necula CS 164 28
Translation of Member Functions. Notes.
- The compiler generates the code for the adapter classes - The programmer does not have to write, or maintain it!
- This is how Java inner classes are compiled
- The compiler might have to add access methods for private fields
- This is a security hole in Java:
- if your class has inner classes that access the private fields, they will be made accessible
- Same might happen even if a subclass of your class has inner classes!
- This could be fixed by not doing source-to-source translation
Prof. Necula CS 164 31
Complications with Nested Functions
- Changes to attributes are visible because they are made in the same object
- Java inner classes can only access “final” local variables - Cannot be assigned-to in the code nor in the proxy
- Similar restrictions in all higher-order languages
- Functional languages even discourage “assignable” variables
Prof. Necula CS 164 32
Conclusions
- Higher-order functions can lead to more compact and elegant code - Heavily used in graphical toolkits, callbacks, iterators, …
- We can combine the OO and functional paradigm
- Source-to-source translation is an easy way to add language features