Lecture 11: TypesFrom material by G. Necula and P. HilfingerType Checking PhaseTypes and Type SystemsUses of TypesReview: Dynamic vs. Static TypesSubtypingExampleType SoundnessTyping Options``Type Wars''Using SubtypesImplicit CoercionsCoercion ExamplesType InferenceProlog: A Declarative Programming LanguageProlog SugaringInference DatabasesExamples: From English to an Inference RuleSoundnessExample: A Few Rules for JavaThe EnvironmentDefining the Environment in PrologExamples RevisitedExample: lambda (Python)Example: Same Idea for `let' in the Cool LanguageExample of a Rule That's Too ConservativeLoosening the RuleAs Usual, Can Always Screw It UpFunction ApplicationConditional ExpressionsLecture 11: Types1Administrivia• Test in class on 10 March.• Preliminary autograder run Wednesday night (sometime). No moreruns until deadline.• Please use bug-submit when asking for debugging help.1From material by G. Necula and P. HilfingerLast modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 1Type Checking Phase• Determines the type of each expression in the program, (each nodein the AST that corresponds to an expression)• Finds type errors.– Examples?• Thetype rulesof a language define each expression’s type and thetypes required of all expressions and subexpressions.Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 2Types and Type Systems• A type is a set ofvaluestogether with a set ofoperationson thosevalues.• E.g., fields and methods of a Java class are meant to correspond tovalues and operations.• A language’stype systemspecifies which operations are valid forwhich types.• Goal of type checking is to ensure that operations are used with thecorrect types, enforcing intended interpretation of values.• Notion of “correctness” often depends on what programmer has inmind, rather than what the representation would allow.• Most operations are legal only for values of some types– Doesn’t make sense to add a function pointer and an integer in C– It does make sense to add two integers– But both have the same assembly language implementation:movl y, %eax; addl x, %eaxLast modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 3Uses of Types• Detect errors:– Memory errors, such as attempting to use an integer as a pointer.– Violations of abstraction boundaries, such as using a private fieldfrom outside a class.• Help compilation:– When Python sees x+y, its type systems tells it almost nothingabout types of x and y, so code must be general.– In C, C++, Java, code sequences for x+y are smaller and faster,because representations are known.Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 4Review: Dynamic vs. Static Types• Adynamic typeattaches to an object reference or other value. It’sa run-time notion, applicable to any language.• Thestatic typeof an expression or variable is a constraint on thepossible dynamic types of its value, enforced at compile time.• Language isstatically typedif it enforces a “significant” set ofstatic type constraints.– A matter of degree: assembly language might enforce constraintthat “all registers contain 32-bit words,” but since this allowsjust about any operation, not considered static typing.– C sort of has static typing, but rather easy to evade in practice.– Java’s enforcement is pretty strict.• In early type systems,dynamic type(E) = static type(E) for all ex-pressionsE, so that in all executions, E evaluates to exactly type ofvalue deduced by the compiler.• Gets more complex in advanced type systems.Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 5Subtyping• Define a relation X Y on classes to say that:An object (value) of typeX could be used when one of type Y isacceptableor equivalentlyX conforms to Y• In Java this means that X extends Y .• Properties:–X X– X Y if X inherits from Y .–X Z if X Y and Y Z.Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 6Exampleclass A { ... }class B extends A { ... }class Main {void f () {A x;// x has static type A.x = new A(); // x’s value has dynamic type A....x = new B();// x’s value has dynamic type B....}}Variables, with static typeA can hold values with dynamic type A,or in general. . .Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 7Type SoundnessSoundness Theorem on Expressions.∀E. dynamic type(E) static type(E)• Compiler uses static type(E) (call this type C).• All operations that are valid on C are also valid on values with types C (e.g., attribute (field) accesses, method calls).• Subclasses only add attributes.• Methods may be overridden, but only with same (or compatible) sig-nature.Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 8Typing Options•Statically typed:almost all type checking occurs at compilation time(C, Java). Static type system is typically rich.•Dynamically typed:almost all type checking occurs at program exe-cution (Scheme, Python, Javascript, Ruby). Static type system canbe trivial.•Untyped:no type checking. What we might think of as type errorsshow up either as weird results or as various runtime exceptions.Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 9“Type Wars”• Dynamic typing proponents say:– Static type systems are restrictive; can require more work to doreasonable things.– Rapid prototyping easier in a dynamic type system.– Useduck typing:define types of things by what operations theyrespond to (“if it walks like a duck and quacks like a duck, it’s aduck”).• Static typing proponents say:– Static checking catches many programming errors at compile time.– Avoids overhead of runtime type checks.– Use various devices to recover the flexibility lost by “going static:”subtyping, coercions,andtype parameterization.– Of course, each such wrinkle introduces its own complications.Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 10Using Subtypes• In languages such as Java, can define types (classes) either to– Implement a type, or– Define the operations on a family of types without (completely)implementing them.• Hence, relaxes static typing a bit: we may know that somethingis aYwithout knowing precisely which subtype it has.Last modified: Tue Apr 14 00:06:40 2009 CS164: Lecture #10 11Implicit Coercions• In Java, can writeint x = ’c’;float y = x;• But relationship between char and int, or int and float not usuallycalled
View Full Document