CPS 506 Comparative Programming Languages Type Systems Type
Total Page:16
File Type:pdf, Size:1020Kb
CPS 506 Comparative Programming Languages Type Systems, Semantics and Data TpsTypes Type Systems • A comple te ly dfidefine d language: Defined syntax, semantics and type system • Type: A set of values and operations – int • Values=Z • Operations={+, -, *, /, mod} – Boolean • Values={true, false} • Operations={AND, OR, NOT, XOR} 2 Type Systems • Type SSstystem – A system of types and their associated variables and objects in a program – To formalize the definition of data types and their usage in a programming language – A bridge between syntax and semantics • Type checked in compile time: a part of syntax analysis • Type checked in run time: a part of semantics 3 Type Systems (con’t ) • SillStatically TdTyped: each variiblable is associated with a singgyple type during its life in run time. –Could be explicit or implicit declaration –Example: C and Java, Perl –Type rules are defined on abstract syntax (Static Semantics) 4 Type Systems (con’t ) • DillDynamically TdTyped: a varibliable type can be changed in run time – Example: LISP, JavaScript, PHP Java Script example: Lis t = [10. 2 , 3. 5] … List = 47 – Less reliable, difficult to debug – More flexible – Fast compilation – Slow execution (Type checking in run-time) 5 Type Systems (con’t ) • Type Error: a non well-defined operation on a variable in run time – Example: union in C union flexType { int i; float f; }; union flexType u; floa t x; … u.I = 10; x=x = ufu.f; … – Another example in C ? 6 Type Systems (con’t ) • Strongly Typed: All type errors are detected in compile or run time before execution – More reliable – Exampl e: Java is nearly strongl y typed , bbtut C is not x+1 regardless of the type x – Coercion (implicit type conversion) rules have an effect on strong tityping • Weak type examp le x = 2; y = “5”; print x+y Visual Basic: 7 JavaScript: “25” 7 Type Systems (con’t ) • Type Safe: A language without type error –Stronggyly Typ ed -> Type Saf e –Example: Java, Haskell, and ML 8 Type Binding • The process of associitiating an attribute, name, location, value, or type, to an objbjtect • Example int i; Identifier i is bound to the integer type and to a location specified by the underlying compiler i = 10; Identifier i is bound to value 10 or value 10 is bound to a location 9 Type Binding (con’t ) • Binding time – Language definition time • Java: Integers are bound to int, and real numbers are bound to float – Language implementation time • Bounding real values to IEEE 754 standard – Program writing time • Declaration of variables – Cil/LdCompile/Load time • Bounding static objects to stack or fixed memory • Execution code is assiggyned to a memory block – Run time • Value are bound to variables 10 Type Binding (con’t ) • Early binding – An element is bound to a property as early as possible – The earlier the binding the more efficient the language • Late Binding – Delayyg binding until the last p ossible time – The later the binding the more flexible the language – Supports overloading and overriding in Object Oriented languages – C++ example ? 11 Type Checking • Typ e checkin g is the activ ity of ensur ing tha t the operands of an operator are of compatible types • A compatible type is one that is either legal for the oppggerator, or is allowed under language rules to be implicitl y converted, by compiler- generated code, to a legal type • If all type binding s are static, nearly all type checking can be static • If type bindings are dynamic, type checking must be dynamic 12 Type Conversion • A narrowing conversion is one thtthat converts an object to a type that cannot incl ud e all of the values of the origgypginal type e.g. float to int • A widening conversion is one in which an object is converted to a type that can include at least approximations to all of the values of the original type e.g. int to float 13 Type Conversion (con’t ) • Implicit type conversion (Coercion) –decreases type error detection ability. In most languages, all numeric types are coerced in expressions, using widening conversions. Ada has no iliitimplicit Convers ion 14 Type Conversion (con’t ) – C – Java double d; int x; long l; double d; int i; x = 5; … d2d = x + 2; d = i; l=l = i; if (d == l) d = 2 * l; 15 Type Conversion (con’t ) • Explicit type conversion (Casting) – ( type-name ) cast-expression • C double d = 3.14; int i = (int) d; • Java boolean t = true; byte b = (byte) (t ? 1 : 0); • Ada (similar to function call) 3 * Integer(2.0) 2. 0 + Floa t(2) 16 Semantic Domains • StiSemantic DiDomain – A set with well-defined properties and operations – Environment • A set of pairs <variable, location> – Memory • A set of pairs <location, value> • State – Product of environment and its memory σ = { <Var1, Val1>, <Var2, Val2>,…, <Varn, Valn>} 17 Semantic Domains (con’t ) • Three ways to ddfiefine the meaning of a program –Operational Semantics • Program is interpreted as a set of seqqppuences of computational steps • A set of execution rules Premise -> Conclusion σ(x) => 4 and σ(y) => 2 -> σ(x+y) => 6 18 Semantic Domains (con’t ) • Three ways to defi ne the meaning of a program – OilOperational Semantics (con’t) • Usage – Language manuals and textbbkooks – Teaching programming languages • Structural: define program behavior in terms of the behavior of its parts • Natural: define program behavior in terms of its overall effects, and not from its single steps 19 Semantic Domains (con’t ) – Axiom ati c Sem anti c s • The program does what it is supposed to do • Agreement of the program result and specification • Formal verification of a ppgrogram using gg logic expressions, assertions • Hoare triple {Pre-condition} s {Post-condition} • Example {a = 2} b = a; {b = 2} • Weakest Pre-condition {?} a = b+1; {a > 1} 20 Semantic Domains (con’t ) – Axiom ati c Se ma ntic s (connt’t) • Axioms {P}a{Q}, P′ ⇒ P,Q ⇒ Q′ – Rule of Consequence {P′}a{Q′} {P}a{Q},{P}a{R} – Rule of Conjunction {P}a{Q ∧ R} true – Rule of Assignment (s : b = a) {Q[a \ b]}s{Q} {P}s {R},{R}s {Q} – Rule of sequence 1 2 {P}s1s2{Q} – RlRule of CditiCondition {P ∧ c}a{Q},{P ∧ ¬c}b{Q} s : if c then a else b {P}s{Q} 21 Semantic Domains (con’t ) –AiAxioma tic Semanti cs (con’t) • Axioms – Rule of Loop {I ∧ c}b{I} s : while c do b end {I}s{I ∧ ¬c} – I is loop invariant – Looppfp, Invariant is true before the loop, at the bottom of the loop in each iteration, and when the loop is terminated. – Find the loop invariant to prove the correctness of the loop 22 Semantic Domains (con’t ) – DilDenotational Semantics • Define the meaning of statement as a state- tran sform ing mathemati cal func tion • A state of a program indicates the current values of the active objects • Example – Denotational semantics of Integer arithmetic expressions » Production rules: Number ::= N D | D Digit ::= 0 | 1 | … | 9 Expressi on ::= E1 + E2 | E1 – E2 | E1 * E2 | E1 / E2| (E) | N 23 Semantic Domains (con’t ) – DttilDenotational StisSemantics (con’t) – Semantic domain: Integer = { …, -1, 0, 1, …} – Semantic functions: Value: Numner => Number Digit: Digit => Number Expr: Expression => Integer – Auxiliary functions: plus: Number + Number => Number … – Semantic equations: Expr[[E1+E2 ]] = plus (Expr[[],E1] , Expr[[])E2]) 24 Data Types • Elem ents of a ddtata ttpype – Set of possible values – Set of operations – Internal representation – External representation • Type information – Implicit • 5 is implicitly integer • I is integer, implicitly, in Fortran – Explicit • Using variable or function declaration 25 Data Types (con’t ) • Data type cllifiiassifications –Built-in • Included in the language definition – Primitive – Composite – Recursive –User-defined • Data types defined by users • DDffgeclared and defined before usage 26 Primitive Data Types • Unst ruc ture d and idiindiv is ible entities • Integer, Real, Boolean, Char • Depends to the language application domain – COBOL: fixed-length strings and fixed-ppmoint numbers – SNOBOL: Strings with different length – Scheme: integer, rational, real, complex 27 Primitive Data Types (con’t ) • ElExample – C • int, float, char – Java • itint, floa t, char, blboolean – Pascal • Integer, Char, Real, Longint – ML • bool, real, int, word, char – Scheme • integer?, real?, boolean?, char? 28 Primitive Data Types (con’t ) • Integer –Almost always an exact reflection of the hardware so the mapping is triilivial –There may be as many as eight different integer types in a language –J’Java’s sidigned itinteger sizes: byte, short, int, long 29 Primitive Data Types (con’t ) • Float – Model real numbers, but only as approxitiimations – Languages for scientific use support at leas t two floa ting-poitint types (e.g., float and double; sometimes more – Usuall y exactly like the hhdardware, bbtut not always – IEEE Floati ng-PitPoint – Standard 754 30 Primitive Data Types (con’t ) • ClComplex –Some languages support a complex type, e.g., C99, Fortran, and Python –Each value consists of two floats, the real part and the imaginary part –Literal form (in Python): (7 + 3j), where 7 is the real part and 3 is the imaginary part 31 Primitive Data Types (con’t ) • DiDecima l – For business applications (money) • Essential to COBOL • C# offers a decimal data type – Store a fixed number of decima l digits, in coded form (BCD) (Binary-Coded Diml)Decimal) – Advantage: accuracy – DdDisadvantages: limited range, wastes memory 32 Primitive Data Types (con’t ) • Boolean –Simplest of all –Range of values: two elements, one for “true” and one for “false” –Could be implemented as bits, but often as bytes 33 Primitive Data Types (con’t ) • Charact er