CS 342 Lecture -*- Outline -*- * Type checking in Pascal ** The basic type checking problem every variable has a type (declared) every expression has a type (inferred) -some expressions have more than one type (usually built-in constants) empty set constructor [], set constructors [1,2] are both packed and unpacked nil (has all pointer types) -simpler type system if each expression has at most 1 type suppose variable v: T and expression E: S (where S is suitably chosen) *Is v := E legal? Can E be passed as actual if formal is v? (more regular if same answer for both, not in Pascal) ** two approaches *** pure name equivalence legal only if S = T -types used for type checking are type names. Anonymous types: (non-simple) types appearing in variable declarations *example 3, statement 3.2 usually not, with name equivalence => anonymous types not useful for name equivalence ------------- program Example3; type cmplx = record re: real; im: real end; comp = record im: real; re: real end; var x: cmplx; y: comp; w: record re: real; im: real end; z: record re: real; im: real end; begin {initialize y and z here} x := y; {statement 3.1} w := z {statement 3.2} end. ------------- *** pure structural equivalence legal if meaning of S has same structure as meaning of T. -types used for type checking are type expressions, type names denote type expresions ------------------ program Example1; type feet = real; metre = real; var f: feet; m: metre; begin f := 1.0; {statement 1.1} m := f {statement 1.2} end. ------------------- 1.2 legal only if use structural equivalence Pascal was concieved as using name equivalence (first compilers used name equivalence) but the report is ambiguous. *** pure structural vs. pure name equivalence name: more secure, easier to implement, faster at compile time but needs exceptions to be practical structural: functions will be more general, due to less scoping problems rule may be more regular ** Ways to relax the pure rules *** coercions: implicit conversion of representations allow assignment of int to real, etc. *** ISO Pascal's type compatibility rules S is compatible with T iff (a) S is the same name as T (b) S is a subrange of T, vice versa!, or both are subranges of some other type U (c) S and T are be set types with compatible base types and both or neither is packed (d) both are string types with same number of components. (it's symmetric) Some types are not assignable: in ISO Pascal, cannot assign a file variable (prevents copies) ISO assignment compatible: S is assignment compatible with T iff (a) S and T are the same assignable type (b) S is real and T is integer (c) S is compatible with T ---------------- program Example2; var x: integer; y: 1..150; begin y := 3; {statement 2.1} x := y {statement 2.2} end. --------------- all legal in ISO pascal