Upload
samson-harrell
View
218
Download
2
Tags:
Embed Size (px)
Citation preview
Afternoon Ada Concepts - 1Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Introduction to Ada 95
Joyce L Tokar, [email protected]
Afternoon Ada Concepts - 2Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Course Outline • History and Overview• Large Scale View of Ada• Conventional Features• Packages and Overloading• System Programming Features• Object Oriented Features• Real-Time Features• Tools and Environments
Afternoon Ada Concepts - 3Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Afternoon Session• Look into the support for Systems
programming, Real-Time programming, and Object-Oriented programming.
• Look at the tools and environments available for developing Ada applications.
Afternoon Ada Concepts - 4Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Ada 95 Highlights• Upward Consistent
Six new reserved words:• abstract, aliased, protected, requeue, tagged, until
8-bit Character Type Small efficiency improvements
• Building on Ada 83 concepts Private and derived types for data abstraction and OOP. Subprogram and entries for user-defined and protected
operations. Packages for structuring the program library and distributed
applications.
Afternoon Ada Concepts - 5Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Ada 95 Highlights• Systems Programming Support
Child library units Interfaces
• Real-Time Programming Enhancements Protected types for data-oriented synchronization Requeue of an entry caller Asynchronous transfer of control
• Object-Oriented Features Tagged type extension User-defined type classes and dispatching operations User-defined initialization, finalization, and assignment
Afternoon Ada Concepts - 6Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Systems Programming
• Hierarchical Libraries
• Generics
• Interfacing to other languagesAda95
Afternoon Ada Concepts - 7Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Hierarchical Libraries
Afternoon Ada Concepts - 8Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Program Libraries
• The Ada program library brings important benefits by extending the strong typing across the boundaries between separately compiled units.
• The flat nature of the Ada 83 library gave problems of visibility control. It prevented two library packages from sharing a full view of a private type. Resulting packages became large and monolithic maintenance nightmares.
• A more flexible and hierarchical structure was necessary.
Afternoon Ada Concepts - 9Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Systems Programming Enhancements
• Subsystem facilities.• Facilities to “hide” auxiliary units within subsystems.• Subsystem interfaces that involve private types.• Signification reduction in recompilation.• Support for interfacing to other systems.
Afternoon Ada Concepts - 10Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Hierarchical Libraries
• Library unit may have child library units.• Share private parts amongst children.• Allows disciplined type extension of private types.• Allows for incremental development.• Clients with only those units they need directly.• Clients are recompiled only when those units are changed.
• Direct support for subsystem concept.
Afternoon Ada Concepts - 11Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Hierarchical Libraries
package Complex_Numbers is type Complex is private; function "+"(X,Y : Complex) return Complex; ... -- similar functions for "-", "*", and "/" function Cartesian_to_Complex (Real, Imag : Float) return Complex; function Real_Part(X : Complex) return Float; function Imag_Part(X : Complex) return Float;private ...end Complex_Numbers;
Afternoon Ada Concepts - 12Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
“with” clause• with clause -- used to give visibility to a library unit.• This allows you to access components of
Complex_Numbers using dot notation (formally known as selected component notation).
• The with clause gives visibility to anything found in the specification of the withed unit.
with Complex_Numbers;procedure CALCULATE is My_Complex : Complex_Numbers.Complex;begin My_Complex := Complex_Numbers.Cartesian_to_Complex(3.2, -1.0);end CALCULATE;
Afternoon Ada Concepts - 13Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
“use” clause
• use clause -- used to give direct visibility into a library unit.
• Requires the corresponding with clause first.• This allows access to the components within the
Complex_Numbers library unit without dot notation.
with Complex_Numbers; use Complex_Numbers;
procedure CALCULATE is
My_Complex : Complex;
begin
My_Complex := Cartesian_to_Complex(3.2, -1.0);
end CALCULATE;
Afternoon Ada Concepts - 14Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Child Library
package Complex_Numbers.Polar is function Polar2Complex(R, Theta : Float) return Complex; function "abs"(X : Complex) return Float; function ARG(X : Complex) return Float; end Complex_Numbers.Polar;
Afternoon Ada Concepts - 15Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Hierarchical Libraries
with Complex_Numbers.Polar;-- implies with Complex_Numbers; package Client1 is R : Float := 0.0; Angle : Float := 45.0; P1 : Complex_Numbers.Complex := Complex_Numbers.Polar.Polar2Complex(R, Angle); end Client1;
Afternoon Ada Concepts - 16Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Hierarchical Librarieswith Complex_Numbers.Polar;use Complex_Numbers;-- Child name Polar and components of the specification-- of Complex_Numbers are directly visible.package Client1 is R : Float := 0.0; Angle : Float := 45.0; P1 : Complex := Polar.Polar2Complex(R, Angle);end Client1;
Afternoon Ada Concepts - 17Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Hierarchical Librarieswith Complex_Numbers.Polar;use Complex_Numbers;-- Child name Polar and components of the specification of-- Complex_Numbers are directly visible.package Client1 is use Polar; -- Components of the child Polar are directly visible. R : Float := 0.0; Angle : Float := 45.0; P1 : Complex := Polar2Complex(R, Angle); end Client1;
Afternoon Ada Concepts - 18Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Private Children• A private child is typically used to add additional
functionality to the parent.• They prevent the parent from growing too large.• Private children can only be seen by the bodies of
their ancestor.• Typically, they are withed by the body of their parent.• A private child is never visible outside of the tree
rooted at the parent.• In essence, the first private child down a long chain
hides anything below it from outside view..
Afternoon Ada Concepts - 19Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Private Children
private package Complex_Numbers.Hidden_Operations is--Types and procedures in this package can be used--in the body of Complex_Numbers.
end Complex_Numbers.Hidden_Operations;
Afternoon Ada Concepts - 20Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Visibility Rules• Declarations in the parent visible part are visible throughout
specifications and bodies of children.• Declarations in the parent private part are visible in the private
part and body of public children and throughout private children specifications and bodies; but not in public children specification parts.
• Public children can be made visible anywhere with a with clause.
• Private children can be made visible from the specifications or bodies of other private descendants of the parent, or from the parent body.
• Child packages and nested packages may not have the same identifier as a name.
Afternoon Ada Concepts - 21Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Friends don’t let friendsuse use
• Leads to problems during maintenance.• Makes debugging difficult.• Pollutes the name space.
useuse
Afternoon Ada Concepts - 22Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Summary of Hierarchical Libraries
• Child library units support hierarchical structuring of a large system into subsystems
• Recompilation of clients is minimized by modularizing a large subsystem interface into visible child units.
• Recompilation of the implementation of a subsystem is minimized by modularizing into private child units.
• A package can be effectively extended by adding a new visible child, without disturbing existing clients.
Afternoon Ada Concepts - 23Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Children of Generics
• Generic packages can have children.• The child of a generic package must itself be a
generic unit.• The child generic unit can only be instantiated in two
ways: Inside the generic body of its parent; As a child of an instance of its parent.
• A child of an instance must itself be an instance.
Afternoon Ada Concepts - 24Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Children of Genericsgeneric type Floating is digits <>;package Generic_Complex_Numbers is type Complex is private; function "+" (X, Y : Complex) return Complex; …private type Complex is record
Real : Floating; Imag : Floating;
end record;end Generic_Complex_Numbers;
Afternoon Ada Concepts - 25Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Children of Generics
generic
package Generic_Complex_Numbers.Cartesian is function Construct (R, I : Floating) return Complex; function Real_Part (X : Complex) return Floating; function Imaginary_Part (X : Complex) return Floating;end Generic_Complex_Numbers.Cartesian;
Afternoon Ada Concepts - 26Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Children of Genericswith Generic_Complex_Numbers;with Generic_Complex_Numbers.Cartesian;procedure D_to_A is type My_Float is new Float digits 6; package My_Complex_Numbers is new Generic_Complex_Numbers( My_Float ); package My_Cartesian_Numbers is new My_Complex_Numbers.Cartesian; Y : My_Float := 0.0; X : My_Float := 34.3; C : My_Complex_Numbers.Complex := My_Cartesian_Numbers.Construct( X, Y );
Afternoon Ada Concepts - 27Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Generics and Hierarchical Libraries
• A library unit cannot be compiled until other library units mentioned in its with clause are entered into the library.
• A subunit cannot be compiled until its parent body is entered into the library.
• A body cannot be compiled until the specification of its parent is entered into the library.
• A child cannot be compiled until the specification of its parent is entered into the library.
• A package specification and body form a single declarative region.
Afternoon Ada Concepts - 28Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Generics and Hierarchical Libraries
• A library package can only have a body if it needs one to satisfy other language rules.
• Do not attempt to redefine Standard.• Renaming is not text substitution.• A library unit could not be renamed as another library
unit in Ada 83/87.• A subprogram body could not be provided by
renaming in Ada 83/87.
Afternoon Ada Concepts - 29Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Other Language Interfaces • Ability to reference (or call) Ada entities from other
languages and to reference (or call) entities from Ada code. Set of new pragmas: Export, Import, Convention
• Export entities created by the Ada program to other programs.
• Import entities created by other programs into the Ada program.
• Convention specifies the calling conventions or data layouts.
Call-back/call-out via dispatching operations on tagged types. Call-back via subprogram access
• package Interfaces
Afternoon Ada Concepts - 30Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Import Interface
type Matrix is array (1..100, 1..100) of Integer;pragma Convention( ZZ_Fortran, Matrix );-- Matrix is to be laid-out in conformance with the format that is used -- by ZZ_Fortran. Fortran_Matrix : Matrix;pragma Import( ZZ_Fortran, Fortran_Matrix, Link_Name => “Values” );-- the object Fortran_Matrix is created by foreign code, where it is-- called “Values”; no storage will be allocated for its Ada declaration. function Multiply( A,B : Matrix ) return Matrix;pragma Import( ZZ_Fortran, Multiply, “_multi” ); -- the body of Multiply is provided by some routine name _multi with -- ZZ_Fortran calling convention; to be supplied externally.
Afternoon Ada Concepts - 31Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Access Types
• Pool-specific access types• General access types• Access parameters• Access discriminants• Access to subprograms• Storage pool management
Afternoon Ada Concepts - 32Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Access Parametersprocedure Main is type T is ...; type A is access all T; Ref : A; procedure P( Ptr : access T ) is begin ... Ref := A( Ptr ); -- dynamic check on conversion end P; X : aliased T;begin P( X’Access ); ... -- can now manipulate X via Refend Main;
Afternoon Ada Concepts - 33Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Access Parameters
• The actual parameter corresponding to an access parameter can be: An access to an aliased object such as X’Access; Another access parameter with the same accessed type; A value of a named access type again with the same accessed
type; An allocator.
• An access parameter can be: Used to provide access to the accessed object by
dereferencing; Passed as a parameter to another access parameter; Converted to a named access type.
Afternoon Ada Concepts - 34Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Access to Subprograms type Trig_Function is access function( F : Float ) return Float; S,C,T : Trig_Function; -- these variables can point to any function that has -- a float as a parameter and returns a float value. X, Theta : Float; … S := Sin'Access; C := Cos'Access; T := Tan'Access; Theta := Some_Degree; X := T.all(Theta); -- As with many uses with access types the .all is not usually -- required; it would be necessary if there were no parameters.
Afternoon Ada Concepts - 35Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Call Backs
type Button is private;type Action is access procedure(B : in out Button); procedure Set_Action(B : Button; A : Action);pragma Import(ANSI_C, Set_Action, ... );-- some procedure in ANSI_C that expects a reference to-- a subprogram which will be called from within the foreign-- code when some event occurs. procedure My_Action(B : in out Button); . . .Set_Action(Some_Button, My_Action’Access);-- registers the Ada procedure My_Action for call back-- from foreign code.
Afternoon Ada Concepts - 36Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
package Interfaces• Defined in the required annex called Interface to Other
Languages
• Contains declarations of various machine integer types plus shift and rotate functions for modular types.
• Includes a number of child packages: Interfaces.C Interfaces.C.Strings Interfaces.C.Pointers Interfaces.COBOL Interfaces.Fortran
Afternoon Ada Concepts - 37Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Classes of Ada Types
Ada Types
Scalar Objects are single values
Composite Objects contain components
Access Objects point to other objects & subprograms
Private Objects are abstract
Task Objects are parallel processes
Protected Coordinated access to shared data
Tagged Inheritance and runtime polymorphism
Afternoon Ada Concepts - 38Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Improved Real-Time Capabilities
• More efficient data communication and synchronization.
• Building blocks to construct common real-time paradigms.
• More control of task scheduling.
Afternoon Ada Concepts - 39Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Protected Types
• A synchronization mechanism which provides access to shared data without including an additional task.
• A low-level, real-time building block that may be used to construct common real-time paradigms.
• Low-level, light weight, data synchronization mechanism.
• Encapsulation of shared data and access operations.
• Similar to Conditional Critical Region with Signals.
Afternoon Ada Concepts - 40Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Protected Operations
• Protected functions provide read-only access to the protected type data components.
• Protected procedures provide exclusive read-write access to the protected type data components.
• Protected entries provide exclusive read-write access to the protected type data components with guarded access.
Afternoon Ada Concepts - 41Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Simple Protected Type
protected type Shared_Data is function Read return Data_Type; procedure Write(New_Data : in Data_Type);private Data : Data_Type;end Shared_Data;
protected body Shared_Data is function Read return Data_Type is begin return Data; end Read; procedure Write(New_Data : in Data_Type) is begin Data := New_Data; end Write;end Shared_Data;
Spec
Body
Afternoon Ada Concepts - 42Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Using Protected Types
SD1 : Shared_Data;SD2 : Shared_Data;
SDA : array( Index_Range ) of Shared_Data;…task body T1 is task body T2 is… …begin begin … … D1 := SD1.Read; SD1.Write(D2); … …end T1; end T2;
Afternoon Ada Concepts - 43Introduction to Ada
Pyrrhus SoftwareEnduring SolutionsProtected Entries
Two Levels of Protection
• The entry barrier is used to indicate a change in the state of the protected object; every protected entry must specify an entry barrier.
• All barriers are examined at the completion of a protected operation that may have changed the state of the protected object; e.g, at the end of a protected procedure or protected entry call.
• Task's waiting for a protected entry barrier condition to become true are enqueued on the protected entry's queue.
The Entry Barriers
Protected Object
Afternoon Ada Concepts - 44Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Counting Semaphore Specification
protected type Counting_Semaphore ( Initial_Count : Integer := 1 ) is entry Acquire; -- "P" Operation procedure Release; -- "V" Operation function Current_Count return Integer; private Count : Integer := Initial_Count; end Counting_Semaphore;
Afternoon Ada Concepts - 45Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Counting Semaphore Bodyprotected body Counting_Semaphore is entry Acquire when Count > 0 is -- Suspend until Count > 0, then decrement Count begin Count := Count - 1; end Acquire; procedure Release is begin Count := Count + 1; -- Increment Count end Release; function Current_Count return Integer is begin return Count; -- return the current value of Count end Current_Count;end Counting_Semaphore;
Afternoon Ada Concepts - 46Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Counting Semaphore in UseMax_Users : constant := 10; -- Maximum Number of Users of ServiceUser_Semaphore : Counting_Semaphore ( Max_Users ); procedure Use_Service( P : Param ) isbegin User_Semaphore.Acquire; -- wait if there are too many Users begin -- critical region Perform_Service( P ); exception when others => -- Always release the semaphore for the next user. User_Semaphore.Release; raise; end; -- critical region User_Semaphore.Release; -- Release the semaphore for the next user.end Use_Service;
Afternoon Ada Concepts - 47Introduction to Ada
Pyrrhus SoftwareEnduring SolutionsBuffer Manager
protected Buffer is entry Put( X : Item ); entry Get( Z : out Item );private Full : Boolean := False; Y : Item;end Buffer;
protected body Buffer is entry Put( X : Item ) when not Full is begin Y := X; Full := True; end; entry Get( Z : out Item ) when Full is begin Z := Y; Full := False; end;end Buffer;
Afternoon Ada Concepts - 48Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Buffer Manager in Use
task body Producer is X : Item;begin loop -- Produce X Buffer.Put( X ); end loop;end Producer;
task body Consumer is Z : Item;begin loop Buffer.Get( Z ); -- Consume Z end loop;end Consumer;
Producer ConsumerBuffer
Put(X) Get(X)
Afternoon Ada Concepts - 49Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Asynchronous Transfer of Control
• Allows a sequence of statement to be interrupted and then abandoned after some event.
• Used for mode change, time bounded computations, user-initiated interrupts, etc.
• Triggering alternative can be either the completion of an entry call, or the expiration of a delay statement.
select triggering_alternative;then abort abortable_part;end select;
Afternoon Ada Concepts - 50Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
ATC in Use
Event Processingloop select Keyboard_Await_Cancel; Put_Line( “Canceled” ); then abort -- This code is abortable Put( “->” ); Get_Command( Command, Last ); Do_Command( Command( 1..Last ) ); end select;end loop;
Timeout-- Cancel computations when a -- timeout occursselect delay 1.5;then abort Complex_Function(FIR_Range);end select;
Afternoon Ada Concepts - 51Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Requeue Statement
• Allows a caller to be "requeued" in the same or some other queue for later processing.
• Without the with abort option, the requeued entry is protected against cancellation.
requeue Entry_Name [with abort];
Afternoon Ada Concepts - 52Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Delay Statements
delay delay_expression;
…
delay Sleep_Period;
Resume_Work;
…• Relative delay statement will
continue execution after waiting (at least) the designated period of time.
delay until delay_expression;…delay until Alarm_Time;Resume_Work;…• Delay until will resume
execution at the designated time.
• The until does not provide a guaranteed delay interval, but it does prevent inaccuracies due to swapping out between the “delay interval calculation”.
Afternoon Ada Concepts - 53Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Annexes
• Systems Programming Annex
• Real-Time Annex
• Distribution Annex
• Numerics Annex
• Safety and Security Annex
Afternoon Ada Concepts - 54Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Systems Programming Annex
• Specifies a number of low-level features including: in-line machine instructions, interrupt handling, shared variable access task identification. Atomic pragma (indivisible read/writes) Volatile pragma (bypasses cache memory)
• Pre-requisite to the Real-Time Systems Annex
Afternoon Ada Concepts - 55Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Real-Time Systems Annex
• Includes pragmas that allow you to tailor: scheduling of parallel processes priorities of parallel processes queueing protocols for entry calls ceiling-locking protocols
• Must include documentation specifying: time it takes to actually abort a task on both single and multi-
processor systems time it takes to process an asynchronous select
• Includes a Monotonic time package.• Includes low-level asynchronous and synchronous task
control options.
Afternoon Ada Concepts - 56Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Distributed Systems Annex
• Includes features that give you ability to: communicate between partitions running on different
processing and/or storage nodes.
categorize library units as to how they are used (determines if/when it can be distributed).
set up a remote library that is used for remote procedure calls (RPCS), using both static binding and dynamic binding of remote procedures
make an asynchronous procedure call (which returns without waiting for completion).
Afternoon Ada Concepts - 57Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Numerics Annex• Accuracy requirements for floating and fixed point arithmetic,
accuracy requirements for the various predefined packages including...
Ada.Numerics Generic_Complex_Types Generic_Complex_Elementary_Functions Complex_types Long_Complex_Types Complex_Elementary_Functions Long_Complex_Elementary_Functions
• Floating point is defined in terms of model numbers as they relate to the implemented properties. There are no safe numbers. The model is in terms of the exponent of the machine.
Afternoon Ada Concepts - 58Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Safety and Security Annex
• This Annex address requirements for systems that are safety critical or have security constraints. It provides facilities and specifies documentation requirements that relate to several needs: Predicting program execution
Reviewing of object code - pragma Reviewable
Restricting language constructs whose usage might interfere with program reliability.
• pragma Normalize_Scalars – ensures that all otherwise uninitialized objects have an initial value.
Afternoon Ada Concepts - 59Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
pragma Reviewable• Directs the compiler to generate object code that can be
independently validated.
• The following information must be produced: Where compiler-generated run-time checks remain
Identification of any construct that is certain to fail
Where run-time support routines are implicitly invoked
For each scalar, either “Initialized” or “Possibly uninitialized”
An object code listing with machine instructions, offsets, and source code correspondence
Identification of each construct with possible erroneous execution
Order of library elaboration
Afternoon Ada Concepts - 60Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Other Annexes
• Required Annexes: Predefined Language Environment Obsolescent Features
• Other domain specific annexes: Information Systems
Afternoon Ada Concepts - 61Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Predefined Language Annex
• Contains packages that support: Predefined Identifiers Character Handling String Handling Numerical Functions
• Basic math functions• General Trig/Log functions
Random Number Generation• Discrete• Continuous
Afternoon Ada Concepts - 62Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Input/Output
• Ada supports many different types of predefined IO.
• Each type has its’ own package with supporting functions and procedures: • Ada.Sequential_IO• Ada.Direct_IO• Ada.Wide_Text_IO • Ada.Streams.Stream_IO• Ada.Text_IO
Afternoon Ada Concepts - 63Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Information Systems Annex
• This Annex provides a set of of facilities relevant to Information Systems programming. These fall into several categories: The package Decimal which declares a set of constants
defining the implementation’s capacity for decimal types, and a generic package for decimal division.
The child package Text_IO.Pictures, which supports formatted and localized output of decimal data, based on picture string.
Afternoon Ada Concepts - 64Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Obsolescent Features Annex• This section contains descriptions of features of the
language that worked under Ada 83, but are no longer needed and not recommended under Ada 95.
• Most good programmers will not find any of the “obsolescent features” a problem. However, there are a few changes to Ada 95 that would require a lot of “nit-picking” changes. There are a few predefined renaming clauses to prevent you from having to edit all of your old programs. However, your new programs should use the correct methods.
For example: with Ada.Text_IO; package Text_IO renames Ada.Text_IO;
Afternoon Ada Concepts - 65Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
What is OOP?
• There are a variety of definitions available generally based on the language being used to implement the OO model. In general, one can say that OOP is:
• Programming around the concept of objects by defining: A type Operations upon the type (methods) With the flexibility to dynamically Extend a type with new components and operations. Identify a type at run time and manipulate values of several
specific types – polymorphism Choose an operation at run time.
Afternoon Ada Concepts - 66Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Object Oriented Methods
• OO is closely allied to reusability. It’s main advantage is that systems can be separated into logical components, allowing better modeling of the problem world. OO creates better abstractions.
• In addition, OO systems can be extended, rather than modified, to add functionality. This prevents disturbing existing software, eliminating the risk of
introducing errors.
Afternoon Ada Concepts - 67Introduction to Ada
Pyrrhus SoftwareEnduring Solutions Support for the Phases of
Object Oriented Development• OORA
Packaging Abstraction & Encapsulation Parallel Processing
• OOD Packaging & Child Packages Strong Typing Enumeration Types Parallel Processing
• OOP Inheritance Polymorphism (Dispatching) Tasking
OORA
OOD
OOP
Afternoon Ada Concepts - 68Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
High Level View of OOP in Ada 95
• Type Extension – the ability to define one type in terms of the other especially as an extensions of another – tagged types and child library units.
• Inheritance – the ability for such an extended type to inherit the primitive operations of its parent and also to replace and add to such operations -- tagged types.
• Polymorphism – the ability to distinguish the specific type of an object at runtime from among several types and in particular to select an operations according to the specific type – class wide types & type extension.
• Late binding – the ability to select an operation at run time – dispatching based on run time choice of type of parameters and result type.
Afternoon Ada Concepts - 69Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Tagged Typetype Rectangle is tagged record Length : Float := 0.0; Width : Float := 0.0; end record;-- Operations for inheritance are now defined -- Example: Rectangles have a defined perimeter, and-- children derived from Rectangle will have Perimeter.function Perimeter (R : in Rectangle ) return Float isbegin return 2.0 * (R.Length +R.Width);end Perimeter;
Afternoon Ada Concepts - 70Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Tagged Type -- Inheritance
• Cuboid inherits Perimeter from Rectangle (technically, Perimeter is a primitive operation). The function will have to be updated for the new type (Perimeter is defined differently for cubes!).
• To do this, you need to override the operation. One way to do this is to write a new Perimeter. A better way it to base the new Perimeter on the parent class operation.
type Cuboid is new Rectangle with record Height : Float := 0.0; end record;
function Perimeter (C : in Cuboid ) return Float isbegin return Perimeter (Rectangle(C)) * 2.0 + ( 4.0 * C.Height);end Perimeter;
Afternoon Ada Concepts - 71Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Abstract Types & Subprograms
• Purpose of an abstract type is to provide a common foundation upon which useful types can be built by derivation.
• An abstract subprogram is a place holder for an operation to be provided (it does not have a body).
• An abstract subprogram MUST be overridden for EACH subclass.
-- Baseline package used to serve as root of inheritance treepackage Vehicle_Package is type Vehicle is abstract tagged null record; procedure Start (Item : in out Vehicle) is abstract;end Vehicle_Package;
Afternoon Ada Concepts - 72Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Abstract Types & Subprograms
We can’t yet declare an object of Train. Why? Because we haven't filled in the abstract parts declared in it’s parent. We have completed the abstract record, but still need to define procedure Start for the Train.
typetype Train Train is new is new Vehicle Vehicle withwith recordrecord passengers : Integer;passengers : Integer; end end Train;Train;
My_Train : Train; My_Train : Train; -- ILLEGAL-- ILLEGAL
type Train is new Vehicle with record passengers : Integer; end Train;
procedure Start (Item : in out Train) is ....My_Train : Train;
Afternoon Ada Concepts - 73Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Abstract Types
You cannot declare a variable of type Planes (it is abstract), so you must derive from it. However, when you derive a new type from Planes, you must also override the function Runway_Needed_To_Land.
type Planes is abstract new Vehicle with record Wingspan : Some_Type; end Planes;
function Runway_Needed_To_Land (Item : Planes) return Feet is abstract;
Afternoon Ada Concepts - 74Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Inheritance Chains
• All records that derive from a tagged record are implicitly tagged.
• Each inherited record inherits all fields and operations from its parent, creating an inheritance chain.
• If you use an operation on a inherited type that is not explicitly written for that type, then the chain is searched towards the root. The first instance of the operation will apply.
• You can even add abstract records at a child level, allowing you to selectively create the exact fields and inheritance desired.
Afternoon Ada Concepts - 75Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Class-Wide ProgrammingT’Class
• With each tagged type there is an associated type ’Class. • The values of this ’Class type include all derived types. • Any derived type may be converted to the type ’Class.
Vehicle
Trains
Planes
Automobiles
Jet Propeller Helicopters
Vehicle’Class
Planes’Class
Afternoon Ada Concepts - 76Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Polymorphism• The introduction of Class-Wide types provide for dynamic
polymorphism.
• Each tagged type T has an associated type denoted by T’Class. T’Class is comprised of the union of all the types in the tree of derived types rooted at T.
• Each value of a class wide type has a tag which identifies its particular type from other types in the tree of types at run time.
• The type T’Class is treated as an indefinite type (like an unconstrained array type). Therefore all objects declared to be of type T’Class must be initialized with a specific type.
• A formal parameter can be of a class wide type and the actual parameter can then be on any specific type in the class.
Afternoon Ada Concepts - 77Introduction to Ada
Pyrrhus SoftwareEnduring SolutionsClass-wide Programming
Dynamic Dispatching
• The procedure Move_All is a class-wide operation, since any variable in the Vehicle hierarchy can be passed to it.
• Start, however, is defined for each type within the Vehicle hierarchy. Depending on the type of Item, a different Start will be called. During runtime, the specific type of Item is known, but it is not known at compile time. The runtime system must dispatch to the correct procedure call.
-- class-wide value as parameter
procedure Move_All ( Item : in out Vehicle’Class) is
...
begin
Start (Item); -- dispatch according to tag
...
end Move_All;
Afternoon Ada Concepts - 78Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Static Binding-- class-wide value as parameterprocedure Move_All ( Item : in out Vehicle’Class) is...begin ... Start (Item); -- dispatch according to tag -- dynamic dispatch Start (Jet(Item)); -- static call to the Start for Jet. This call will
-- fail at run time if Item is not a member of-- the Jet hierarchy.
...end Move_All;
Afternoon Ada Concepts - 79Introduction to Ada
Pyrrhus SoftwareEnduring SolutionsClass-Wide Programming
Using Pointers
-- Vehicles held as a heterogeneous list using an access type.type Vehicle_Ptr is access all Vehicle’Class;
-- Control routine can manipulate the vehicles directly from the list.procedure Move_All is Next : Vehicle_Ptr;begin ... Next := Some_Vehicle; -- Get next vehicle ... Start (Next.all); -- Dispatch to appropriate Handle … -- Note the de-referencing of pointerend Move_All;
Afternoon Ada Concepts - 80Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Controlled Types
A type derived from Controlled can have an user-defined Adjust, Finalize, and Initialize routines. Every time an object of this type is assigned, released (via exiting scope or freeing up a pointer) or created, the appropriate routines will be called.
package Ada.Finalization is
type Controlled is abstract tagged private;
procedure Initialize (Object: in out Controlled); procedure Adjust (Object: in out Controlled); procedure Finalize (Object: in out Controlled);
Afternoon Ada Concepts - 81Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
QUESTIONS
Ada95
Afternoon Ada Concepts - 82Introduction to Ada
Pyrrhus SoftwareEnduring Solutions
Thank You!
Joyce L Tokar, PhDPyrrhus Software
PO Box 1352Phoenix, AZ 85001-1352
USA1-480-951-1019
1-480-607-3762 (FAX)[email protected]