22
Types and Programming Languages Lecture 1 Simon Gay Department of Computing Science University of Glasgow 2006/07

lec21

Embed Size (px)

DESCRIPTION

lecture

Citation preview

  • Types and Programming LanguagesLecture 1Simon GayDepartment of Computing ScienceUniversity of Glasgow2006/07

    CS1Q Computer Systems - Simon Gay

  • IntroductionType definitions and declarations are essential aspects ofhigh-level programming languages.Example (Java):class Example {int a;void set(int x) {a=x;}int get() {return a;}}

    Example e = new Example();

    CS1Q Computer Systems - Simon Gay

  • Compile-time (static) typechecking is standard7.e.set(Hello);^------------^*** Semantic Error: No applicable overload forthe method named set was found in typeExample. Perhaps you wanted the overloadedversion void set(int x); instead?

    8.e.show();^------^*** Semantic Error: No method named show wasfound in type Example.From the Jikes Java compiler (applied to some other code):

    CS1Q Computer Systems - Simon Gay

  • Compile-time (static) typechecking9.i = e + 1; ^*** Semantic Error: The type of thisexpression, Example, is not numeric.

    CS1Q Computer Systems - Simon Gay

  • Type declarationsOrganize data into high-level structures essential for high-level programmingDocument the program basic information about the meaning of variables and functionsInform the compiler example: how much storage each value needsSpecify simple aspects of the behaviour of functions types as specifications is an important idea

    CS1Q Computer Systems - Simon Gay

  • TypecheckingStatic (compile-time) or dynamic (run-time) static is better: finds errors sooner, doesnt degrade performance (we will concentrate on static typechecking)Verifies that the programmers intentions (expressed by declarations) are observed by the programA program which typechecks is guaranteed to behave well at run-time at least: never apply an operation to the wrong type of value more: eg. security propertiesA program which typechecks respects the high-level abstractions eg: public/protected/private access in Java

    CS1Q Computer Systems - Simon Gay

  • Why study types (and programming languages)?The type system of a language has a strong effect on the feelof programming.Examples: In original Pascal, the result type of a function cannot be an array type. In Java, an array is just an object and arrays can be used anywhere. In Haskell, programming with lists is very easy; in Java it is much less natural.To understand a language fully, we need to understand its typesystem. We will see underlying typing concepts appearing indifferent languages in different ways, helping us to compareand understand language features.

    CS1Q Computer Systems - Simon Gay

  • Why study types (and programming languages)?How does a language designer (or a programmer) know thatcorrectly-typed programs really have the desired run-timeproperties?To answer this question we need to see how to specify typesystems, and how to prove that a type system is sound.To prove soundness we also need to specify the semantics(meaning) of programs - what happens when they are run.So studying types will lead us to a deeper understanding ofthe meaning of programs.Example of the issue of soundness: variant records in Pascal

    CS1Q Computer Systems - Simon Gay

  • Variant records in Pascaltype kind = (staff,student);type person =recordname : string;case k : kind ofstaff : (office : string)student : (year : integer)end;The following error cannot be detected by static typechecking:var simon : person;begin simon.name := Simon; simon.k := staff;simon.office := G093; write(simon.year + 5);end

    CS1Q Computer Systems - Simon Gay

  • Variant records in Adatype kind = (staff,student);type person(k : kind) isrecordname : String;case k iswhen staff => (office : String)when student => (year : Integer)end case;end record;Now we must declare simon : person(staff) and thensimon.year is never allowed.

    CS1Q Computer Systems - Simon Gay

  • Possibilities and limitations of typecheckingIf types are specifications, can typechecking be used to verifyprogram properties beyond correct use of data and functions?Yes, for example: secrecy and authenticity properties of security protocols behavioural properties (eg. deadlock-freedom) in concurrent systemsBut there are limits: most interesting properties cannot beautomatically verified, even in principle, so types can only evergive a safe approximation to correctness.Also, in practice we want typechecking to be efficient.

    CS1Q Computer Systems - Simon Gay

  • Typechecking as a safe approximationFor any static type system, and the notion of correctness whichit aims to guarantee: It is essential that every typable program is correct.It is usually impossible to ensure that every correct program istypable.Typechecking must not accept any incorrect programs butalways rejects some correct programs.Exercise: write down a fragment of Java code which will nottypecheck but which, if executed, would not misuse any data.

    CS1Q Computer Systems - Simon Gay

  • Answer to exerciseif (1 == 2) {int x = Hello * 5;}The Java typechecker assumes that every branch of aconditional statement may be executed (even if the condition isa compile-time constant or even a boolean literal).In general it is impossible to predict the value of an arbitraryexpression at compile-time.

    CS1Q Computer Systems - Simon Gay

  • PrinciplesProgramming is difficult and we need all the automated help wecan get!Static typechecking is one approach to program analysis.It has been enormously beneficial.Exact program analysis is impossible in general. Typecheckingaims for limited guarantees of correctness, and inevitablyrejects some correct programs.A type system restricts programming style, sometimes to anundesirable extent.The challenge in type system design: allow flexibility inprogramming, but not so much flexibility that incorrect programscan be expressed.

    CS1Q Computer Systems - Simon Gay

  • Why exact program analysis is impossibleThis is probably familiar from any course on computabilitySome problems are undecidable - it is impossible to constructan algorithm which will solve arbitrary instances.The basic example is the Halting Problem: does a given programhalt (terminate) when presented with a certain input?Problems involving exact prediction of program behaviour aregenerally undecidable, for example: does a program generate a run-time type error? does a program output the string Hello?We cant just run the program and see what happens, becausethere is no upper limit on the execution time of programs.

    CS1Q Computer Systems - Simon Gay

  • Undecidability of the Halting Problem (HP)Instance of HP: a legal program P and an input string S for P.Question: does P halt when run on S?Theorem: HP is undecidableProof: by contradiction - we assume that we have an algorithmA that solves HP, and discover that the consequence of thisassumption is a logical impossibility. Therefore the assumptionmust be false.Concretely, say P is a Java function:void P(String S);Let H be an implementation of algorithm A as a Java function:boolean H(String X, String S);Any language can be substituted for Java.

    CS1Q Computer Systems - Simon Gay

  • Undecidability of the Halting Problem (HP)Using H we can define a Java function Q: Q is given a legal Java function W Q uses H to determine whether or not W halts when given its own text as input if W halts then Q enters an infinite loop, otherwise Q haltsvoid Q(String W) {if (H(W,W)) {while (true) {}}}

    CS1Q Computer Systems - Simon Gay

  • Undecidability of the Halting Problem (HP)Now we run Q with its own text as input. What happens?Q(void Q(String W) {}) Q calls H(Q,Q) which returns either true or false. If H returns true then: from the definition of H, Q halts on input Q. from the definition of Q, Q loops on input Q. CONTRADICTION! If H returns false then: from the definition of H, Q loops on input Q. from the definition of Q, Q halts on input Q. CONTRADICTION!Therefore Q cannot exist.

    CS1Q Computer Systems - Simon Gay

  • Consequences for program analysisThe question Does program P generate a run-time type errorwith input S? is undecidable. If R were a decision procedurefor this question then we could solve HP for program Pby using R to analyse

    void NewP(String S) {P(S);int x = 1 + Hello;}because NewP generates a type error if and only if P halts. Similarly for any other behavioural property of programs.

    CS1Q Computer Systems - Simon Gay

  • All is not lostThis sounds rather bleak, but: static analysis (including type systems) is a huge and successful area incomplete analysis (remember: safe approximation) is better than no analysis, as long as not too many correct programs are ruled outA major trend in programming language development has beenthe inclusion of more sophisticated type systems in mainstreamlanguages.By studying more powerful type systems, we can get a glimpseof what the next generation of languages might look like.

    CS1Q Computer Systems - Simon Gay

  • Administrative detailsTwo lectures + one tutorial per week (Mon 11, Wed 9, Fri 10).Copies of presentations will be handed out.Some additional notes will be produced.There will be an assessed exercise (worth 20%) and an exam.A sample exam paper will be produced.I can be contacted by email ([email protected]), or in myoffice (G093) within reason.Books: Types and Programming Languages, B. C. Pierce compiler books Type Systems, L. Cardelli (material for reading course)Course web page:www.dcs.gla.ac.uk/~simon/teaching/tpl

    CS1Q Computer Systems - Simon Gay

  • Reading and ExercisesRead Chapter 1 of Pierce.Refer to Chapter 2 of Pierce as necessary, during the rest ofthe course.For each hour of timetabled teaching you should expect tospend at least another hour on private study. After each lectureI will recommend reading from Pierces book; often I will alsoassign exercises from the book or from additional worksheets.During the tutorial sessions we can discuss any problemswhich arise from the reading or the exercises.For now:Read Sections 1 and 2 of Linear Types for Packet Processing.

    CS1Q Computer Systems - Simon Gay