An Introduction to Ada Programming Languages Winter 2004

  • Slides: 55
Download presentation
An Introduction to Ada Programming Languages Winter 2004 R. Dewar © 2004

An Introduction to Ada Programming Languages Winter 2004 R. Dewar © 2004

Basic Structure of a Program l. A program is a collection of units l

Basic Structure of a Program l. A program is a collection of units l Packages l Functions l Procedures l Bound together to form a program l Typically a unit is stored in a file l Units reference other units R. Dewar © 2004 2

Procedure l procedure H (M : Integer) is declarations begin statements return; end H;

Procedure l procedure H (M : Integer) is declarations begin statements return; end H; l Typical use is procedure Main is … which defines the main program R. Dewar © 2004 3

Function l function Max (A : Integer; B : Integer) return Integer is Result

Function l function Max (A : Integer; B : Integer) return Integer is Result : Integer; begin if A > B then Result : = A; else Result : = B; end if; return Result; end Max; R. Dewar © 2004 4

Packages l Packages define a related collection of types, and subprograms (procedure and functions)

Packages l Packages define a related collection of types, and subprograms (procedure and functions) l A package provides a set of services to a client l A package may be a client of another package R. Dewar © 2004 5

Package Spec (Declaration) l package X is declarations types subprogram specs (but not subprogram

Package Spec (Declaration) l package X is declarations types subprogram specs (but not subprogram bodies) end X; R. Dewar © 2004 6

Subprogram Specs l procedure Print_In_Hex (X : Integer); l function Max (A, B :

Subprogram Specs l procedure Print_In_Hex (X : Integer); l function Max (A, B : Integer) return Integer; l Note the semicolon instead of is l A subprogram spec has everything you need to know to use the subprogram l A client needs only the spec R. Dewar © 2004 7

Package Bodies l package body X is declarations subprograms local to body variables/constants local

Package Bodies l package body X is declarations subprograms local to body variables/constants local to body subprogram bodies for subprogram specs appearing in the package spec begin initialization statements end X; R. Dewar © 2004 8

How to be A Client l To access a package, use a WITH: with

How to be A Client l To access a package, use a WITH: with Calendar; procedure Main is Today : Calendar. Time; … end Main; R. Dewar © 2004 9

The Use Clause l Accessing Stuff in Calendar without dots l with Calendar; use

The Use Clause l Accessing Stuff in Calendar without dots l with Calendar; use Calendar; procedure Main is Today : Time; … end Main; R. Dewar © 2004 10

Package Bodies as Clients l with Calendar; package body Julian_Calendar_Stuff is … end Julian_Calendar_Stuff;

Package Bodies as Clients l with Calendar; package body Julian_Calendar_Stuff is … end Julian_Calendar_Stuff; l Here we have the implementation of a package done using stuff in another package R. Dewar © 2004 11

Package Specs as Clients l. A package spec can build on another spec l

Package Specs as Clients l. A package spec can build on another spec l with Calendar; use Calendar package To_Do_List is … procedure Enter (T : Time; M : String); -- Enter new item in todo list. Time is -- deadline. M is description. end To_Do_List; R. Dewar © 2004 12

The Idea of a Package Spec l Write the package spec l It is

The Idea of a Package Spec l Write the package spec l It is like a contract between client and body of the spec l Write the body l Write the client l Last two activities are completely independent (and should not talk to one another except “via” the spec) R. Dewar © 2004 13

Integer Type Declarations l Type Integer is built in l But you don’t want

Integer Type Declarations l Type Integer is built in l But you don’t want to use it l Because its range is implementation defined l Because it is defined to match the machine not your problem l Because it does not take advantage of strong typing to prevent errors R. Dewar © 2004 14

Defining Integer Types l Define type according to use l type Day_In_Year is range

Defining Integer Types l Define type according to use l type Day_In_Year is range 1. . 366; type Age is range 0. . 130; type Temperature is range -20. . +180; l Now we can define variables of the type l Today_Day : Day_In_Year; Employee_Age : Age; Machine_Room_Temp : Temperature; R. Dewar © 2004 15

Why Define Integer Types l No dependence on implementation l Unlike l Range l

Why Define Integer Types l No dependence on implementation l Unlike l Range l Get of types matches problem an error or warning at compile time l Age l Or type int in C : = 200; an exception at runtime l Age : = Age + 1000; R. Dewar © 2004 16

Strong Typing l Cannot mix integer types: l Current_Temp : Temperature; Current_Pressure : Pressure;

Strong Typing l Cannot mix integer types: l Current_Temp : Temperature; Current_Pressure : Pressure; l Current_Temp : = Current_Pressure + 1; l Error, cannot assign pressure to temperature l Current_Temp : = Current_Temp + Current_Pressure l Error, cannot add temperature to pressure R. Dewar © 2004 17

Integer Subtypes l. A subtype creates a limited range l But is still the

Integer Subtypes l. A subtype creates a limited range l But is still the same type l subtype OK_Operating_Range is Temperature range 70. . 80; Room_Temp : Temperature; Machine_Room_Temp : OK_Operating_Range … Machine_Room_Temp : = Room_Temp; l Raises exception if Room_Temp out of range R. Dewar © 2004 18

Catching Exceptions l You can catch an exception at run time l begin …

Catching Exceptions l You can catch an exception at run time l begin … Machine_Room_Temp : = Room_Temp … exception when Constraint_Error => recovery stuff end; R. Dewar © 2004 19

Unsigned (Modular) Types l Modular types have wrap around: l type M is mod

Unsigned (Modular) Types l Modular types have wrap around: l type M is mod 7; -- values are 0, 1, 2, 3, 4, 5, 6 q : m : = 6; -- initialization … q : = q + 2; -- result is 1 l Most common use, conventional unsigned l type Uns_32 is mod 2 ** 32; l Remember that twos complement arithmetic is equivalent to arithmetic mod 2**wordsize R. Dewar © 2004 20

Real Types l Float types (control relative accuracy) type My_Float is digits 7; type

Real Types l Float types (control relative accuracy) type My_Float is digits 7; type Xfloat is digits 7 range 1. 0. . 10. 0; subtype F 1 is My_Float range 1. 0. . 5. 0; l Digits is decimal digits of relative precision l l There is a formal model for fpt in Ada Target independent (parametrized) l Guarantees minimal accuracy l Operations defined in terms of model numbers l Results fall in defined model interval l R. Dewar © 2004 21

Fixed-Point Types l Fixed-point types are real types where you control the absolute accuracy.

Fixed-Point Types l Fixed-point types are real types where you control the absolute accuracy. Typically implemented as scaled integers l type Velocity is delta 0. 125 range 0. 0. . 10. 0; l l Decimal fixed-point types Decimal small l Typical use in financial programming l type Money is digits 10 delta 0. 01 range 0. 00. . 999_999. 00; l R. Dewar © 2004 22

Character Types l Built in types l Character (8 -bit Latin-1) l Wide_Character (16

Character Types l Built in types l Character (8 -bit Latin-1) l Wide_Character (16 -bit Unicode/ISO 10646) l Good enough for most purposes, but you can define your own types: l type l Note My_Character is (‘A’, ‘B’, ‘C’, …. ); on standard types l Standard types are in package Standard that is automatically visible in every unit. R. Dewar © 2004 23

Enumeration Types l An enumeration type is a sequence of ordered enumeration literals: l

Enumeration Types l An enumeration type is a sequence of ordered enumeration literals: l type State is (Off, Powering_Up, On); l No arithmetic defined l S 1, S 2 : State; S 1 : = S 1 + S 2; -- Illegal l Can add/subtract l State’Pred (S 1) State’Succ (S 2) l These one are examples of attributes R. Dewar © 2004 24

Boolean Types l Predefined l type enumeration type Boolean is (False, True); l Expressions

Boolean Types l Predefined l type enumeration type Boolean is (False, True); l Expressions of type boolean used in l if statements l while loops l exit statements l Etc. R. Dewar © 2004 25

Access Types l Access types function like pointers l But are not necessarily implemented

Access Types l Access types function like pointers l But are not necessarily implemented that way l type r is access integer; type s is access all integer; l The allows the access value to reference any item at all. Without all, you can only reference objects specifically allocated for the pool in question. R. Dewar © 2004 26

Using Access Types l Allocate an object using new l type AI is access

Using Access Types l Allocate an object using new l type AI is access all integer; Ptr : AI; … Ptr : = new Integer; -- uninitialized Ptr : = new Integer’(12); -- initialized l To obtain value dereference: l. V : Integer; … V : = Ptr. all; R. Dewar © 2004 27

Array Types l Arrays can have 1 or more subscripts l type Vector is

Array Types l Arrays can have 1 or more subscripts l type Vector is array (Integer range 1. . 10) of Integer; type Matrix is array (Integer range 0. . 10, Character range ‘A’. . ‘Z’) of Vector; VV : Vector : = (others => 10); -- aggregate MM : Matrix; … MM (5, ‘C’) : = VV; VV (1. . 5) : = VV (2. . 6); -- slicing (one dim only) R. Dewar © 2004 28

Array Bounds and Types l Are the bounds of an array answer part of

Array Bounds and Types l Are the bounds of an array answer part of the properties of the array type? l Things are much cleaner if we answer yes, as in Pascal, but this is very limiting l For example, a sort routine cannot take a vector of any size to sort. l Instead we consider the bounds to be like the range of an integer type R. Dewar © 2004 29

Unconstrained Arrays l Unconstrained array type has no bounds l type UA is array

Unconstrained Arrays l Unconstrained array type has no bounds l type UA is array (Int range <>) of Int; -- cannot use UA to declare a variable -- instead must build a subtype UA 5 is UA (1. . 5); UAV 5 : UA 5 : = (6, 5, 4, 3, 2); -- can also set bounds for a variable UAV 2 : UA (1. . 2); R. Dewar © 2004 30

String Types l. A string type is an array whose elements are a character

String Types l. A string type is an array whose elements are a character type. l Two standard built in string types l type String is array (Natural range <>) of Character; type Wide_String is array (Natural range <>) of Wide_Character; S : String (1. . 5) : = “Hello”; l Note: Natural is a predefined subtype of Integer with bounds 0. . Integer’Last; R. Dewar © 2004 31

Record Types l Like struct in C l type Date is record Year :

Record Types l Like struct in C l type Date is record Year : Year_Number : = 2002; -- default Month : Month_Number; Day : Day_Number; end record; DD : Date; EE : Date : = (2001, 8, Day => 27); … DD. Month : = EE. Month – 1; R. Dewar © 2004 32

Arrays/Records and Access Types l Access types and records/arrays l type A is array

Arrays/Records and Access Types l Access types and records/arrays l type A is array (Int range 0. . 10) of Int; type AP is access A; AV : AP; … AV. all (3) : = AV (4); -- can omit. all here l Similarly do not need. all for fields of records l DP. Month : = DP. all. Month + 1; R. Dewar © 2004 33

What about Union Types? l The union type in C is fundamentally unsafe, and

What about Union Types? l The union type in C is fundamentally unsafe, and therefore unacceptable l union (int, float) puzzle; l Now puzzle has either an int or a float l But at runtime, cannot tell which l So we have to trust the programer l In Ada we are short on trust R. Dewar © 2004 34

Instead, Discriminated Types l. A record can have discriminants: l type IF is (Int,

Instead, Discriminated Types l. A record can have discriminants: l type IF is (Int, Float); type Int_Float (V : IF : = Int) is record case V is when Int => Int_Val : Integer; when Float => Float_Val : Float; end case; end record; l Now the value of the discriminant V shows what type is currently present R. Dewar © 2004 35

More on Discriminated Records l Referencing l Puzzle a discriminanted type : Int_Float; …

More on Discriminated Records l Referencing l Puzzle a discriminanted type : Int_Float; … Puzzle : = (Float, 1. 0); F : = Puzzle. Float_Val; -- OK I : = Puzzle. Int_Val; -- raise exception … Puzzle. V : = Int; -- not allowed! R. Dewar © 2004 36

More on Discriminated Records l Can make subtypes l subtype Puzzle. I is puzzle

More on Discriminated Records l Can make subtypes l subtype Puzzle. I is puzzle (Int); -- this type only holds int values l Can dimension arrays from discriminant: l Subtype Vlen is Integer range 1. . 10; type Vstr (Vlen : Integer : = 0) is record Data : String (1. . Vlen); end record; VV : Vstr : = (5, “hello”); R. Dewar © 2004 37

Other Types l Derived types (copying a type) l Extended types (object oriented stuff)

Other Types l Derived types (copying a type) l Extended types (object oriented stuff) l Task types (active threads) l Protected types (passive synchronization) l More on all these later! R. Dewar © 2004 38

Statement Forms l Assignment statement (is not an expression) l l Variable : =

Statement Forms l Assignment statement (is not an expression) l l Variable : = expression; If statements l if condition then statements elsif condition then statements … else statements end if; R. Dewar © 2004 39

Statement Forms (cont) l Loops l for J in Integer range 1. . 10

Statement Forms (cont) l Loops l for J in Integer range 1. . 10 loop statements end loop; l while condition loop statements end loop; l loop statements end loop; R. Dewar © 2004 40

Statements (cont) l Exit statement l exit; exit when condition; l Can only be

Statements (cont) l Exit statement l exit; exit when condition; l Can only be used in a loop l Can use labels: l Outer : loop Inner : loop … exit Inner when Done; end loop Inner; end loop Outer; R. Dewar © 2004 41

Statements (cont) l Case statements expression is when 0 => statements when 1 |

Statements (cont) l Case statements expression is when 0 => statements when 1 | 10 => statements when 2. . 9 => statements l case end case; l All values in when branches must be static l All possible values of expression must be included exactly once l Can use when others => to cover rest R. Dewar © 2004 42

Statements (cont) l Return statement l return; -- procedure -- function return expression; l

Statements (cont) l Return statement l return; -- procedure -- function return expression; l Only in procedure/function l Function must have at least one return l Raise statement l raise exception-name; R. Dewar © 2004 43

Declaring and Handling Exceptions l Declaring l Error, l Raising an exception Disaster :

Declaring and Handling Exceptions l Declaring l Error, l Raising an exception Disaster : exception; an exception l raise Disaster; -- strips stack frames till a handler is found l Handling an exception l exception when Disaster => statements R. Dewar © 2004 44

More on Exception Handling l Anywhere we have begin end, we can do: l

More on Exception Handling l Anywhere we have begin end, we can do: l begin statements exception when handler => statements; end; R. Dewar © 2004 45

Block Statement l Block statement can be used anywhere l declare declarations -- declare

Block Statement l Block statement can be used anywhere l declare declarations -- declare section optional begin statements exception handlers -- exception section optional end; R. Dewar © 2004 46

Back to Packages l Private types and private parts l A type can be

Back to Packages l Private types and private parts l A type can be declared private l Implementation is hidden l But can provide subprograms that operate on instances of the type R. Dewar © 2004 47

A Package for Stacks package Stacks is type Stack is private; procedure Push (It

A Package for Stacks package Stacks is type Stack is private; procedure Push (It : Character; On : in out Stack); procedure Pop (It : Character; From : in out Stack); function Empty (S : Stack) return Boolean; Stack_Empty : exception; Stack_Full : exception; private type Stack is record top : Integer : = 0; contents : String (1. . 80) : = (others => ‘*’); end record; end Stacks; R. Dewar © 2004 48

A client of Stacks l with Stacks; package Mumbo is … … S :

A client of Stacks l with Stacks; package Mumbo is … … S : Stacks. Stack; … Stacks. Push (‘x’, S); … exception when Stacks. Stack_Full => … end Mumbo; R. Dewar © 2004 49

A client of Stacks l with Stacks; use Stacks package Mumbo is … …

A client of Stacks l with Stacks; use Stacks package Mumbo is … … S : Stack; … Push (‘x’, S); … exception when Stack_Full => … end Mumbo; R. Dewar © 2004 50

Implementation of Stacks package body Stacks is procedure Push (It : Character; On :

Implementation of Stacks package body Stacks is procedure Push (It : Character; On : in out Stack) is begin if On. top = 80 then raise Stack_Full; else On. top : = On. top + 1; On. contents (On. top) : = It; end if; end Push; … end Stacks; R. Dewar © 2004 51

Generic Packages generic type T is private; Max : Natural; package Stacks is type

Generic Packages generic type T is private; Max : Natural; 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; R. Dewar © 2004 52

Implementing generic l Generic body looks just like the nongeneric one l Except that

Implementing generic l Generic body looks just like the nongeneric one l Except that we will reference type T instead of type Character. R. Dewar © 2004 53

Client of Generic l with Stacks; package Mumbo is -- Must first instantiate the

Client of Generic l with Stacks; package Mumbo is -- Must first instantiate the package Istak is new Stacks (Integer, 100); S : Istak. Stack; … Istak. Push (219, S); … end Mumbo; R. Dewar © 2004 54

An Introduction to Ada: That’s all, folks! Programming Languages Winter 2004 R. Dewar ©

An Introduction to Ada: That’s all, folks! Programming Languages Winter 2004 R. Dewar © 2004