Ada 95 A brief History 1975 1979 strawmansteelman
Ada 95: A brief History • • 1975 -1979: strawman-steelman requirements, Pascal is base 1981 : Green wins, becomes preliminary Ada 1983 : ANSI Standard, first validated compiler 1987 : ISO Standard 1990 -1994 : Revision Process 1995 : ANSI - ISO Ada 95 Standard 1995 : First validated GNAT compiler ada-types. I- 1
Design principles (Why Ada? ) • Software Engineering: programming in the large • Readability over writability • Rigorous standard for portability • Precise semantics • Built-in concurrency • Strong-Typing: all unsafe code is explicit ada-types. I- 2
Ada, C++ and Java • • Big, capable languages strong typing : Ada, C++, Java Generics : Ada C++ Concurrency : Ada Java Packages: Ada C++ and Java Ahead of its time in design Out of step in implementation Between language generations ada-types. I- 3
Key Goals • • Readability : wordy but readable strong typing : find errors when you compile, don’t debug Programming in the large: package it and offer interfaces Exception Handling: Expect errors, deal with them. Data abstraction : apples are not oranges (user defined types will not be set to equal without casting) Object orientation : Inheritance and late binding Tasking : walk, chew gum, etc. (I. e. threads) Generic units : similar functionality across different types ada-types. I- 4
The canonical example with Text_Io; use Text_Io; procedure example is -- Does not have to be called “main” begin Put_Line (“easier than we thought!”); end; ada-types. I- 5
A small package interface Package Math_Functions is -- Here we are defining the interfaces function Sqrt (X : Float) return Float; function Exp (Base : Float; Exponent : Float) return Float; end Math_Functions; ada-types. I- 6
Using the package with Math_Functions; with Gnat_IO; use Gnat_IO; procedure Example 2 is Val : Float; begin get (Val); put (“Sqrt (“); put (Val); put (“) = “); put (Math_Functions. Sqrt (Val)); new_line; end; ada-types. I- 7
Dissection of this package Package body Math_Functions is -- Separately compiled unit Epsilon : constant : = 1. 0 e-7; -- Declared variable function Sqrt (X : Float) return Float is -- functions have in params and ret Result : Float : = X / 2. 0; -- initialize a variable. begin while abs (Result * Result - X ) > Epsilon loop Result : = 0. 5 * (X / Result + Result); -- X/Result = Result if done end loop; return Result; end Sqrt; . . . end Math_Functions; -- Could be many functions here. ada-types. I- 8
Summary of Package Features Package has data and functions. It can be accessed by writing “with” (and avoid qualifying by writing “use”). A full program is normally a bunch of packages together with a “main” procedure (lexically a subprogram) that starts the program. Define the interface by giving the signatures (types in and out), also known as the specification or declaration, and then define the body separately (and privately). Functions have in parameters and a return value. Procedures can have in, out or in out parameters. While loop is a nice way of programming this. ada-types. I- 9
Packages and Compilation The compiler compiles one or more compilation units (compiler is not obligated to compile more than one at a time). These start with “with” and “use” clauses and then proceed to either a package declaration, a package body, a subprogram declaration, or a subprogram body. ada-types. I- 10
A larger package interface (visible part) (p. 28 of Barnes) Package Buffer_System is -- Here we are defining the interfaces type Buffer is private; -- Means insides are inaccessible to other packages procedure Load (B : out Buffer; S : in String); procedure Get (B : in out Buffer; C: out Character) ; -- in out because Buffer is changed by the Get. private Max: constant Integer: = 80 ; type Buffer is record Data: String(1. . Max); Start: Integer: = 1; Finish: Integer: = 0; end record; end Buffer_System; ada-types. I- 11
Body of Buffer (repeats declarations) Package body Buffer_System is -- Separately compiled unit procedure Load(B: out Buffer; S: in String) is Begin B. Start : = 1; B. Finish : = S’Length; B. Data(B. Start. . B. Finish): = S; end Load; . . . end Buffer_System; -- Could be many functions here. ada-types. I- 12
Using the Buffer as a Type My_Buffer: Buffer; -- declare a variable of type Buffer Load(My_Buffer, Some_String); Get(My_Buffer, A_Character); -- Key point. Given a package, can declare variables of types -- in the package (e. g. package is Buffer_System; declare object -- of type Buffer). -- Package is like a C++ library. ada-types. I- 13
Access Types (Pointer) Typed pointers, for type safety and to minimize aliasing. Want to be sure that a pointer points to a single type (at least for now): type Handle is access Buffer; Ptr : Handle : = new Buffer; Ptr. all is a Buffer. – could be an argument to a copy constructor Can write Ptr. Start, Ptr. Data, etc. ada-types. I- 14
Enumeration Types (for colors, days of weeks etc. ) • Simplest Implementation: literals are mapped into successive integers • Very common abstraction: list of names, properties • Expressive of real-world domain, hides machine representation • type suit is (hearts, diamonds, spades, clubs) ; • type direction is (east, west, north, south, lost); • Order of list implies that spades > hearts, etc. ada-types. I- 15
Enumeration types and strong typing type Fruit is (Apple, Orange, Grape, Apricot); type Vendor is (Apple, IBM, Hewlett Packard); My_PC : Vendor; Dessert : Fruit; … My_PC : = Apple; Dessert : = My_PC; -- ERROR (caught at compile time) ada-types. I- 16
Built-in enumeration types type Boolean is (False, True); type Character is (…. -- full ASCII. type Wide_Character is ( … -- Unicode, or ISO 646 ada-types. I- 17
Array Types Index is typed: type weekday is (Mon, Tue, Wed, Thu, Fri); type workhours is array (Weekday) of integer; -- domain is Weekday, range is -- an int representing number of hours Predefined array: type String is array (Positive range <>) of Character; ada-types. I- 18
Abstraction mechanisms • • • Packages Private types Objects and Inheritance Classes, polymorphism, dynamic dispatching Generic units Concurrency : tasks and protected types ada-types. I- 19
Object-oriented Programming • • • Type extension Inheritance and overriding Run-time dispatching Polymorphism Class-wide programming Abstract types and subprograms ada-types. I- 20
Inheritance • Three goals: • 1. Define one type in terms of another with extensions. (like java class inheritance) • 2. Allow derived type (one with extensions) to redefine operations. • 3. Be able to determine which operation to use at runtime. ada-types. I- 21
Type Hierarchies called “class” in Ada • A class is a family of types with the same ancestor (unlike C++/Java classes • • • which are themselves hierarchically related) An object of the class is identified at run-time by its tag. Dynamic dispatching uses the tag of the object to determine the operation that applies. Dynamic = runtime. (This responds to third goal above. ) A classwide operation applies uniformly to all member of the class. • Reminder: Ada type is similar to Java class • Ada class is similar to hierarchically related Java classes. ada-types. I- 22
Type Extension • Mechanism to define new types by enrichment (i. e. add fields): type Geo. Thing is tagged record X_Coord, Y_Coord : Integer; end record; type Circle is new Geo. Thing with record Radius : Float; end record; ada-types. I- 23
Functions in type hierarchies function Distance(O: in Geo. Thing) return Float is begin return Sqrt(O. X_Coord ** 2 + O. Y_Coord**2); end record; function Area(O: in Geo. Thing) return Float is begin return 0. 0; -- make it 0 because a Geo. Thing by default is a point end Area; ada-types. I- 24
Functions in type hierarchies function Area(O: in Circle) return Float is begin return 3. 14*C. Radius**2; -- circle has a different area from generic Geo. Thing end Area; -- So, distance function will apply to Geo. Thing and Circle but Area must be -- redefined for Circle. -- This implies that the function Area that is going to be called should depend - on the type of the object. ada-types. I- 25
Use of these functions O: Geo. Thing : = (3. 2, 2. 1); -- a geothing at location 3. 2, 2. 1 C: Circle: = (1. 0, 0. 0, 4. 2); -- a circle with center 1. 0, 0. 0 and radius 4. 2 Area(O); -- returns 0. 0 Area( C ); -- returns the area of the circle having radius 4. 2 -- All of these facts can be determined at compile time. So this is called -- static binding. ada-types. I- 26
Class-wide Functions In Ada, unlike Java and C++, a class is a hierarchy of types. (Types are analogous to classes in those languages). Suppose we want to define a function that applies to all types of a class and that does something different for different types in the class. In contrast: the function distance applies to all types of a class but does the same thing for the different types in the class. ada-types. I- 27
Example of Class function Square. Area(O: in Geo. Thing’Class) return Float is begin return (Area(O))**2; -- Call the area function for the object passed. end Square. Area; -- Unlike the distance function this one depends on the type -- Area function. Which version of Area to call is determined at runtime and -- the proper version is then “dispatched”. -- Please check out pp. 30 -38 of Barnes (Point, Circle, Moment examples). ada-types. I- 28
Implications of not using Class function Square. Area(O: in Geo. Thing) return Float is begin return (Area(O))**2; -- Call the area function for Geo. Things always end Square. Area; -- Even if you called this one with a Circle, you’d call the Area function for -- Geo. Things. This would be bad. ada-types. I- 29
Advanced Considerations: overdoing inheritance It’s not always a good idea to use inheritance. Consider the following (Barnes chap 19): type Cylinder is new Circle with record Height: Float; -- cyliner is circle with height; sounds plausible… end Cylinder; -- To see whether it is good: ask can the class wide procedures apply to -- this new object (e. g. what is distance to a cylinder? ). -- It just doesn’t make sense. ada-types. I- 30
Advanced Considerations: has vs. isa A Cylinder isa Circle doesn’t seem right. How about a Cylinder has a Circle. type Cylinder is tagged record Base: Circle; Height: Float; end Cylinder; -- We express “has” by making a Circle a member of Cylinder. -- This way we don’t get spurious inheritance. ada-types. I- 31
Generic Units (Barnes chapter 11) • The basic tool for software reuse that cuts across types whether members of • • • the same class or not. Parameters can be types, objects, subprograms, packages. Akin to C++ templates. Absent from Java so far. ada-types. I- 32
A Generic Procedure (does not depend on nature of T) Generic type Item is private; procedure Exchange (X, Y : in out Item) is T: Item; begin T: = X; X : = Y; Y : = T; end; ada-types. I- 33
Instantiating the Generic Procedure for other types procedure Swap is new Exchange(Float); procedure Swap is new Exchange(Integer); procedure Swap is new Exchange(Date); … -- So we can use Swap on many different types ada-types. I- 34
A Generic Package (interface) Generic type T is private; package Stacks is type Stack is private; procedure Push (Thing : T ; On : in out Stack); … private type Arr is array (1. . Max) of T; type stack is record Top : Integer : = 0; contents : Arr; end record; end Stacks; -- Body is pretty conventional (see section 11. 1 of Barnes) ada-types. I- 35
Use of Stack Package (Barnes 17. 1) declare package mystack is new Stack(129, Float); -- stack package of a certain size and type -- mystack is now instantiated and can be used just as the Math_Functions -- package was used before. begin X: Float: = 3. 2; mystack. push(X); … ada-types. I- 36
Other Topics You Should Understand for project/core exam Abstract base classes (define interfaces to functions but no bodies, e. g. p. 38) Mixin Inheritance (mix generics and inheritance e. g. p. 466) Reflection (asking the type of an object). Tasking – we will discuss later Exceptions – we will discuss later ada-types. I- 37
The Type Model • • Types and Subtypes Declarations and their scope Objects, constants and variables Scalar types Array types Record types Access types ada-types. I- 38
Types and Subtypes • A type is a set of values and a group of operations • Types with different names are distinct and incompatible (part of strong typing): name equivalence everywhere, instead of structural equivalence. (As we saw, if colors and days of the week are represented by integers, don’t want to be able to assign Wednesday to a color. ) • Subtypes of the same base type are compatible. ada-types. I- 39
Built-in subtypes type Integer is. . -- implementation defined subtype Positive is integer range 1. . Integer’Last; -- useful attribute subtype Natural is integer range 0. . Integer’Last; X : integer : = 500; Y : Positive : = 2 * X; Z : Natural : = - Y; -- illegal, raises constraint error ada-types. I- 40
Compile-time vs. run-time • Type properties are enforced by the compiler whenever possible: • x : integer : = false; l -- program rejected • x : positive : = f (z); 1. -- if f returns a non-integer, then program rejected, else need to check value at run-time (in this sense dynamic) ada-types. I- 41
Declarations and Scope • Declarations are elaborated in order of appearance in the program. • Entities become visible at the end of their declaration (usually) • Block structure allows arbitrary nesting of declarative regions. • Declarations can appear in 1. subprograms 2. packages 3. blocks 4. . ada-types. I- 42
Blocks Declare X : Integer : = F (5); Y : Integer : = 2 * X; Z : Integer : = Y * Z; X : Float ; begin declare X : Float : = Float (Y); begin Put_Line (Float’Image (X)); end; -- Error: premature use of Z -- Error: duplicate -- hides outer X ada-types. I- 43
Variables and Constants 1. Variable declaration: 2. 3. Limit : Integer : = 25; Offset : Integer range 1. . 20; 4. Constant declaration: 5. 6. Sqrt 2 : constant float : = Sqrt (2. 0); Always : constant Boolean : = True; 1. Never : constant Boolean : = not Always; ada-types. I- 44
Variables must be constrained Subtype is constrained: First_Name : String (1. . 5) : = “Ralph”; but not necessarily static (i. e. could depend on runtime values): Last_Name : String (1. . X * 2); else subtype is indefinite but initial value provides bounds: Comment : String : = “this is obvious”; -- bounds are 1. . 15 ada-types. I- 45
Multiple Declarations This, That : T : = F (1, 2, 3); Is equivalent to This : T : = F (1, 2, 3); That : T : = F (1, 2, 3); F is called twice. Important if expression has side-effect: type Ptr is access R; P 1, P 2 : Ptr : = new R; two R’s are allocated. ada-types. I- 46
Number Declarations Pi : constant : = 3. 14159265; -- type deduced from value Half_Pi : constant : = Pi / 2; -- mixed arithmetic OK Big : constant : = 2 ** 200; -- legal One : constant : = 2 * Big / (Big + Big); -- must be exact ada-types. I- 47
Scalar Types • Discrete types l Integer types l Enumeration Types • Real types l Floating-point types l Fixed_point types ada-types. I- 48
Integer Types Several predefined types: Integer, Long_Integer, Short_Integer Specific bounds of type must be static: type My_Int is range -2 ** 16. . 2 ** 16 - 1; type Tiny is range 0. . 10; By giving explicit bounds, program is more portable: each compiler will figure out what hardware type corresponds (because integers can be 16 bits on some machines and 64 bits on others). Modular types: type Byte is mod 2 ** 8; ada-types. I- 49
Integer Operations Comparison Operators: = /= < <= > >= Addition Operators: + Unary operators + - Multiplying operators * Highest precedence Operators: ** / mod rem abs ada-types. I- 50
Boolean Operations All attributes of discrete types Boolean binary operators : and Boolean unary operators : not Short-circuit operations : and then Membership operations : in or xor or else not in When in doubt, parenthesize! ada-types. I- 51
Control Structures Conventional sequential constructs: If-Statement Loop Case statement Goto and labels More novel forms for task communication. ada-types. I- 52
If-Statement If Done (X, Y) then Success; Close_Up; elsif Almost_Done (X) then -- the only keyword that isn’t English Hurry (Y); else if X = 0 then Call_For_Help (X) else Panic; end if; ada-types. I- 53
Loops Infinite loop: loop Put_Line (“Forever”); end loop; In general, better to stop: loop Put_Line (“Still_Going”); exit when Time_Is_Up; end loop; -- must be boolean value ada-types. I- 54
Loops over discrete ranges 1. 2. 3. for J in 1. . 1000 loop -- declares J for K in 1. . 0 loop -- empty range 4. 5. for Month in Feb. . Nov loop for Month in Months range Feb. . Nov loop 6. for K in Positive loop -- might take a long time 7. for Num in reverse 1. . 1000 loop -- descending order ada-types. I- 55
While-Loops while abs (Result * Result - X ) > Epsilon loop Result : = 0. 5 * (X / Result + Result); end loop; Effect of Until can be obtained with while and exit statements. ada-types. I- 56
Named Loops 1. 2. 3. 4. 5. 6. 7. 8. search : while X > 0 loop X : = F(X, Y); refine: for J in 1. . N loop Y : = G (Z); exit search when X = 0. 0; end loop refine; if T > 20 then exit; end if; end loop search; -- alternate form 9. . 10. ada-types. I- 57
Case Statements Most programs are interpreters for some abstract machine => case statement is most useful control structure! Works naturally with discrete types, in particular enumerations. Case alternatives must cover all values of the range ada-types. I- 58
Case Statements X : Integer; . . Case (X+1) is -- Expression of integer type when Integer’First. . 0 => Handle_Non_Positive; when 2. . 4 | 6 | 8 => Process (X); when 9. . 12 | 2 => null; when others => Use_Default (X); -- Required Display (X); end case; can use qualification to restrict range: case Int’(x+1) is. . . ada-types. I- 59
Goto Statement Occasionally useful. Syntax of maximum ugliness to discourage use: while Going loop Compute_Some; if Hopeless then goto next_try; end if; Compute_Some=More; <<next_try>> Adjust_Computation; end loop; Restricted range. Raise statement is wild jump. ada-types. I- 60
Subprograms • Functions and procedures. • Functions only have in-parameters. • Functions may return unconstrained types. • Function execution must end in return statement • Parameter passing by copy-return for scalar types. • Parameter passing not specified for non-tagged types. • Positional and named notation in calls. • Defaults for in-parameters. ada-types. I- 61
Functions function F (X : integer : = 0; Y : Float : = Pi; Maybe : Boolean : = True) return Integer; … F (10, 0. 0, False) F (5) F (Maybe => False) -- equivalent to F (5, Pi, True) -- equivalent to F(0, Pi, False) ada-types. I- 62
Operators Like functions, but usable in infix notation. Package Bignums is type Bignum is private; Zero : constant Bignum; function “+” (X, Y : Bignum) return Bignum; function “*” (X, Y : Bignum) return Bignum; function Image (X : Bignum) return String; private. . End Bignums; -- deferred constant Must respect syntax: no defaults, no unary “*”, etc. ada-types. I- 63
Attributes • Attributes denote properties of a type, or type-specific properties of a value - Boolean’Size -character’size -month’pos (Jul) -table’length (1) -- 1, because single bit 8 bits involves type and literal specify array and dimension • Could be written as a function, but functions don’t take types as arguments => so need new syntax. ada-types. I- 64
Attributes on Discrete Types Byte’First, Long_Integer’Last -- applies to type or subtype Weekday’Succ (Today) -- like function call Integer’Succ (X*Y) -- like adding one Boolean’Pred (True) -- Yields False Boolean’Succ (True) -- Exception Weekday’Pos (Mon) -- Yields 0 Weekday’Val (3) -- Yields Thu Positive’Max (X, Y) -- function with two args ada-types. I- 65
Real Types All computations are approximate: Fixed point type: absolute bound on error: type temp is delta 2 ** (-16) range -100. 0. . 100. 0; Floating point type: relative bound on error: type Angle is digits 7 range -2. 0. . 2. 0; Predefined floating point types: Float, Long_Float, etc. ada-types. I- 66
Array Types Index types can be of any discrete type Component type must be definite: type class_list is array ( 1. . 100) of String (1. . 10); -- OK type class_list is array ( 1. . 100) of String; -- Error, which kind of string? Subtype constrains all indices or none: type Matrix is array (positive range <>, positive range <>) of Long_Float; -- positive matrix subtype Table is Matrix; subtype Rotation is Matrix (1. . 3, 1. . 3); ada-types. I- 68
Anonymous Array Types Grades : array (1. . Num_Students) of Natural; Grades is a variable. type of Grades has no name: distinct from any other array types. Ar 1, Ar 2 : array (1. . 10) of Boolean; … Ar 1 : = Ar 2; -- Error: different (anonymous) types. If type is useful, it deserves to have a name. ada-types. I- 69
Array Attributes type Matrix is array (Positive range <>, Positive range <>) of Float; subtype Rect is Matrix (1. . 3, 1. . 5); M 3 : Rect; M 3’First (1) -- Yields 1 M 3’First -- same. Rect’length (2) -- Yields 5 (applies to type) M 3’range (2) -- equivalent to 1. . 5 String’Length -- ERROR: unconstrained ada-types. I- 70
Array Aggregates Expression that yields an array value: A : = (1, 2, 3, 10); -- positional A : = (1, others => 0); -- notation for default. A : = (1. . 3 => 1, 4 => -999); -- component associations Default can only be used if bounds are known: A : String (1. . 10) : = (others => ‘? ’); -- OK A : String : = (others => ‘? ’); -- Error : unknown bounds. ada-types. I- 71
Multidimensional Arrays Aggregates given in row-major order with subaggregates: type Square is array (1. . 3, 1. . 3) of Integer; Unit : constant Square : = ( (1, 0 , 0), (0, 1, 0), (0, 0, 1)); Two-dimensional array is NOT array of arrays: type vector is array (1. . 3) of Integer; type V 3 is array (1. . 3) of vector; -- not convertible to Square ada-types. I- 73
Operations on One_Dimensional Arrays Boolean operations extend pointwise: type Set is array (1. . Card) of Boolean; S 1, S 2, S 3 : Set; … S 3 : = S 1 and S 2; -- Intersection lexicographic comparisons on arrays of discrete types: S 1 : = (T, T, T); S 2 : = (T, T, F); . . S 2 < S 1 -- yields True ada-types. I- 74
Concatenation and Slicing Both operations yield the base type: type Table is array (1. . 10) of Integer; T 1, T 2 : Table; … T 1 & T 2 -- What type? Declaration equivalent to: type Anon is array (integer range <>) of Integer; subtype Table is Anon (1. . 10); T 1 & T 2 , T 1 (X. . Y) are of type Anon ada-types. I- 75
Specifying a range subtype Sub is Positive range 2. . 4; Label : String (1. . 10) : = “transcends” ; … Label (2. . 4) -- Yields “ran” Label (Integer range 2. . 4) -- Same Label (Sub) -- Ditto Also used in loops and case statements. ada-types. I- 76
- Slides: 74