This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: TYPE INFERENCE AND LACKWIT GILBERT BERNSTEIN 1. TYPE CHECKING Im going to use a running example to make this easier to follow f : (int, int, int) > int let f x y z = if x > 0 then x = y else x = z Suppose were compiling this code. The first thing wed do is parse it into an abstract syntax tree. Here is the AST for the func tion f : AST PIC Notice at the beginning of the code snippet provided, there is a type signature: f : (int, int, int) > int The goal of type checking is to ensure that the programmer is not lying when they make statements like f is a function that takes three int s and returns an int . Now suppose that someone gave us (totally out of the blue) a complete labeling of our AST with a type for every node. We might write down these labels like this TYPED AST PIC where x : int is a label on the expression x meaning that the ex pression x has type int . Now our task of type checking is very sim ple. All we need to do is make sure that all of these labels are con sistent with each other, according to some set of typing rules . These typing rules are usually written like this: e 1 : bool e 2 : 1 e 3 : 1 if e 1 then e 2 else e 3 : 1 In english, we would read this rule as follows. Given that we know the following: that e 1 is an expression of type bool , that e 2 is an ex pression of type 1 , and that e 3 is an expression of type 1 , then we 1 2 GILBERT BERNSTEIN can conclude that the compound expression if e 1 then e 2 else e 3 has type 1 . More importantly, notice that if we just flip this rule up side down, superimpose it on our AST and substitute in the specific value int for the placeholder 1 then we get a perfect match with our labeling. In reality, we are not handed a complete labeling of our AST, so we have to generate it ourselves. We would start with our goal. To prove that the ifthenelse statement has type int : PARTIAL AST PIC Then, we would reason in reverse that the subexpressions must have the following types: PROPAGATED LABELING AST PIC Obviously, doing this gives us a simple recursive algorithm to typecheck with. However, look what happens when we reach the leaf node x : BOOLEAN EXPRESSION X BRANCH ZOOM We need some way to be sure that x is of type int here, but in general x might be any type. To solve this problem we need to make some assumptions (to use Milnors language). In modern parlance,(to use Milnors language)....
View
Full
Document
 Winter '11
 DavidNotikin

Click to edit the document details