81
Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C S T S C

Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Embed Size (px)

Citation preview

Page 1: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 1ASEET

Introduction to

Ada95ANSI/ISO/IEC-8652:1995

S T S CS T S C

Page 2: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 2ASEET

SpeakersSpeakersEugene BingueEugene Bingue

Nova Southeastern UniversityNova Southeastern University

[email protected]@ix.netcom.com

Leslie (Les) DupaixLeslie (Les) Dupaix

USAF STSCUSAF STSC

[email protected]@hill.af.mil

Page 3: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 3ASEET

Why Ada 95?Why Ada 95?

Overview of AdaOverview of Ada

AnnexesAnnexes

Introduction to Ada 95Introduction to Ada 95

Page 4: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 4ASEET

A revision of ANSI/MIL-STD-1815A-1983 to reflect A revision of ANSI/MIL-STD-1815A-1983 to reflect current essential requirements with minimum current essential requirements with minimum negative impact and maximum positive impact to the negative impact and maximum positive impact to the Ada community.Ada community.

The Standard dropped the Mil-STD designation The Standard dropped the Mil-STD designation identification and now is ANSI/ISO/IEC-8652:1995.identification and now is ANSI/ISO/IEC-8652:1995.

Software Engineering for the 21st CenturySoftware Engineering for the 21st Century

Why Ada 95?Why Ada 95?

Page 5: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 5ASEET

The Main User NeedsThe Main User Needs

Program Libraries Program Libraries

Object Oriented ProgrammingObject Oriented Programming

Parallel & Real-Time Processing Parallel & Real-Time Processing

InterfacingInterfacing

Page 6: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 6ASEET

Ada Reserved WordsAda Reserved Words

xorxorrequeuerequeue taggedtagged untiluntil

abortabortabsabsacceptacceptaccessaccessallallandandarrayarrayatatbeginbeginbodybodycasecaseconstantconstant

declaredeclaredelaydelaydeltadeltadigitsdigitsdodoelseelseelsifelsifendendentryentryexceptionexceptionexitexitforfor

functionfunctiongenericgenericgotogotoififininisislimitedlimitedlooploopmodmodnewnewnotnotnullnull

ofofororothersothersoutoutpackagepackagepragmapragmaprivateprivateprocedureprocedureraiseraiserangerangerecordrecordremrem

renamesrenamesreturnreturnreversereverseselectselectseparateseparatesubtypesubtypetasktaskterminateterminatethenthentypetypeuseusewhenwhenwithwithwhilewhilealiasedaliased protectedprotectedabstractabstract

Page 7: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 7ASEET

Used as the names of various items (cannot use Used as the names of various items (cannot use reserved words).reserved words).

Arbitrary length.Arbitrary length.

First character - letter A - Z. First character - letter A - Z. (ISO 10646-1)(ISO 10646-1)

Other characters - letter A-Z, numeral, Other characters - letter A-Z, numeral, _ as a _ as a non-terminal characternon-terminal character, (but not several _ in a , (but not several _ in a row).row).

Not case sensitive. Not case sensitive.

Comments are started by “--”, and continue to Comments are started by “--”, and continue to end of lineend of line

IdentifiersIdentifiers

Page 8: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 8ASEET

Examples of IdentifiersExamples of Identifiers

Legal Identifiers:Legal Identifiers:

ReportsReports Last_NameLast_Name WindowWindow

DTZDTZ Target_LocationTarget_Location PiPi

ListList Max_Refuel_RangeMax_Refuel_Range

Illegal Identifiers:Illegal Identifiers:

_BOMBERS_BOMBERS 1X1X P-iP-i

Target/LocationTarget/Location CHECKS_CHECKS_

Last NameLast Name First__NameFirst__Name

Page 9: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 9ASEET

Ada Statements (Verbs)Ada Statements (Verbs)

SEQUENTIALSEQUENTIAL CONDITIONALCONDITIONAL

ITERATIVEITERATIVE

:=:=

nullnull

procedure callprocedure call

returnreturn

declaredeclare

ifif

thenthen

elsifelsif

elseelse

casecase

looploop

exitexit

forfor

whilewhile

raiseraise

gotogoto

OTHEROTHER

delaydelay

entry callentry call

abortabort

acceptaccept

selectselect

requeuerequeue

protectedprotected

All block constructs All block constructs

terminate with an terminate with an endend

(end if, end loop, …)(end if, end loop, …)

TASKINGTASKING

Page 10: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 10ASEET

Hierarchical LibrariesHierarchical Libraries“Packages”“Packages”

Page 11: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 11ASEET

Main Main ProgramProgram

"with” ing the "with” ing the packagepackage

Ada PackageAda Package

SpecificationSpecification

BodyBody

Specification and BodiesSpecification and Bodies

Page 12: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 12ASEET

Program LibrariesProgram Libraries

The Ada program library brings important benefits by The Ada program library brings important benefits by extending the strong typing across the boundaries extending the strong typing across the boundaries between separately compiled units. between separately compiled units.

The flat nature of the Ada 83 library gave problems The flat nature of the Ada 83 library gave problems of visibility control. It prevented two library of visibility control. It prevented two library packages from sharing a full view of a private type. packages from sharing a full view of a private type. Resulting packages became large and monolithic Resulting packages became large and monolithic maintenance nightmares. maintenance nightmares.

A more flexible and hierarchical structure was A more flexible and hierarchical structure was necessary.necessary.

Page 13: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 13ASEET

package Complex_Numbers ispackage Complex_Numbers is

type Complex is private;type Complex is private;

function “+” (Left, Right : Complex) return Complex;function “+” (Left, Right : Complex) return Complex;

... -- similarly “-”, “*” and “/”... -- similarly “-”, “*” and “/”

function Cartesian_To_Complex (Real, Imag : Float) return function Cartesian_To_Complex (Real, Imag : Float) return Complex;Complex;

function Real_Part (X : Complex) return Float;function Real_Part (X : Complex) return Float;

function Imag_Part (X : Complex) return Float;function Imag_Part (X : Complex) return Float;

privateprivate

........

end Complex_Numbers;end Complex_Numbers;

Hierarchical LibrariesHierarchical Libraries

If you want to add additional features to the package (say, Polar If you want to add additional features to the package (say, Polar notation), you want to do so in a manner that minimizes side effects. notation), you want to do so in a manner that minimizes side effects.

Users who already Users who already withwith the package should not have to recompile, nor the package should not have to recompile, nor should they find additions to their “name space”.should they find additions to their “name space”.

Page 14: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 14ASEET

Hierarchical LibrariesHierarchical Libraries

package Complex_Numbers.Polar ispackage Complex_Numbers.Polar is procedure Polar_To_Complex (R, Theta : Float) return procedure Polar_To_Complex (R, Theta : Float) return Complex;Complex; function “abs” (Right : Complex ) return Float;function “abs” (Right : Complex ) return Float; function Arg ( X : Complex) return Float;function Arg ( X : Complex) return Float;end Complex_Numbers.Polar;end Complex_Numbers.Polar;

ChildChild

Solution? Create a package Solution? Create a package subordinatesubordinate to Complex_Numbers. It to Complex_Numbers. It can use the resources of Complex_Numbers, but is a separate can use the resources of Complex_Numbers, but is a separate package in its own right. This is referred to as a package in its own right. This is referred to as a childchild package. package.

Page 15: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 15ASEET

Rules for the Rules for the withwith clause clause

• with clausewith clause - used to give visibility to a library unit - used to give visibility to a library unit

• This allows you to access components of This allows you to access components of Complex_Numbers using Complex_Numbers using dotdot notation (formally notation (formally known as known as selected component notationselected component notation).).

• TheThe withwith clause gives visibility to anything found in clause gives visibility to anything found in the specification of the the specification of the withwithed united unit

with Complex_Numbers; with Complex_Numbers;

procedure CALCULATE isprocedure CALCULATE isMy_Complex : Complex_Numbers.Complex;My_Complex : Complex_Numbers.Complex;

beginbeginMy_Complex := Complex_Numbers. Cartesian_To_Complex(5.0, 2.0);My_Complex := Complex_Numbers. Cartesian_To_Complex(5.0, 2.0);

end; end;

Page 16: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 16ASEET

Rules for the Rules for the useuse clauses clauses

• use clauseuse clause - used to give direct visibility to a - used to give direct visibility to a library unitlibrary unit

• Requires a Requires a withwith clause first clause first

• This allows you to access components of This allows you to access components of Complex_Numbers without using Complex_Numbers without using dotdot notation notation

with Complex_Numbers; use Complex_Numbers;with Complex_Numbers; use Complex_Numbers;

procedure CALCULATE isprocedure CALCULATE isMy_Complex : Complex;My_Complex : Complex;

beginbeginMy_Complex := Cartesian_To_Complex(5.0, 2.0);My_Complex := Cartesian_To_Complex(5.0, 2.0);

end;end;

Page 17: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 17ASEET

UseUse

• Leads to problems during maintenanceLeads to problems during maintenance

• Makes debugging difficultMakes debugging difficult

• Pollutes the Pollutes the name spacename space

Don’t Use the Don’t Use the UseUse

Page 18: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 18ASEET

In the SpecificationIn the Specification

with Complex_Numbers;with Complex_Numbers;package More_Math is.......package More_Math is.......

This implies that users of More_Math will also need This implies that users of More_Math will also need Complex_NumbersComplex_Numbers

In the BodyIn the Body

package More_Math is...package More_Math is...........

with Complex_Numbers;with Complex_Numbers;package body More_Math ispackage body More_Math is

..........

This implies that the user of More_Math needs no additional This implies that the user of More_Math needs no additional resources, but that the implementation of More_Math (which resources, but that the implementation of More_Math (which is hidden from the user) uses Complex_Numbers internallyis hidden from the user) uses Complex_Numbers internally

Where Context Clauses Where Context Clauses GoGo

Page 19: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 19ASEET

Hierarchical LibrariesHierarchical Libraries

If you If you withwith the child you have automatic visibility of the the child you have automatic visibility of the parent (but not direct visibility). In essence, a parent (but not direct visibility). In essence, a withwith clause for a child automatically includes a clause for a child automatically includes a withwith for all for all ancestors. ancestors.

If you If you withwith the parent, you the parent, you DO NOTDO NOT have any visibility of have any visibility of

any children, unless the children are any children, unless the children are withwithed separately.ed separately.

The child has visibility of the parent. The child has visibility of the parent.

A child may A child may withwith previously compiled siblings previously compiled siblings

The child body has complete visibility to the parent bodyThe child body has complete visibility to the parent body

The parent body may The parent body may withwith children children

The parent spec may not The parent spec may not withwith any children any children

Page 20: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 20ASEET

Hierarchical Libraries Hierarchical Libraries - private children- private children

A private child is typically used to add additional A private child is typically used to add additional functionality to the parent.functionality to the parent.

They prevent the parent from growing too large.They prevent the parent from growing too large.

Private children can only be seen by the Private children can only be seen by the bodiesbodies of of their ancestor.their ancestor.

Typically, they are Typically, they are withwithed by the body of their parent.ed by the body of their parent.

A private child is never visible outside of the A private child is never visible outside of the treetree rooted at the parent.rooted at the parent.

In essence, the first In essence, the first private childprivate child down a long down a long chainchain hides anything below it from outside view.hides anything below it from outside view.

Page 21: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 21ASEET

Private ChildrenPrivate Childrenpackage Complex_Numbers ispackage Complex_Numbers is

type Complex is private;type Complex is private;

function “+” (Left, Right : Complex) return Complex;function “+” (Left, Right : Complex) return Complex;

... -- similarly “-”, “*” and “/”... -- similarly “-”, “*” and “/”

function Cartesian_To_Complex (Real, Imag : Float) return function Cartesian_To_Complex (Real, Imag : Float) return Complex;Complex;

function Real_Part (X : Complex) return Float;function Real_Part (X : Complex) return Float;

function Imag_Part (X : Complex) return Float;function Imag_Part (X : Complex) return Float;

privateprivate

........

end Complex_Numbers;end Complex_Numbers;

private package Complex_Numbers.Hidden_Operations isprivate package Complex_Numbers.Hidden_Operations is--Types and procedures in this package can be used--Types and procedures in this package can be used--in the body of Complex_Numbers.--in the body of Complex_Numbers.

end Complex_Numbers.Hidden_Operations;end Complex_Numbers.Hidden_Operations;

ChildChild

Page 22: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 22ASEET

Problems with ChildrenProblems with Children They whine, stay on the phone too much, … wait, They whine, stay on the phone too much, … wait,

wrong analogy!wrong analogy!

A child has automatic visibility of the complete A child has automatic visibility of the complete specification of all of its “ancestors.specification of all of its “ancestors.

This means that a child has full access to the This means that a child has full access to the private parts of the parent, grandparent, etc.private parts of the parent, grandparent, etc.

If I desire access to the private parts of package If I desire access to the private parts of package Cant_Touch_Me, all I have to do is name my Cant_Touch_Me, all I have to do is name my package Cant_Touch_Me.Got_Ya, and visibility is package Cant_Touch_Me.Got_Ya, and visibility is mine!!mine!!

This is a configuration management issue. Simple This is a configuration management issue. Simple tools can track which packages are children of tools can track which packages are children of other packages.other packages.

Page 23: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 23ASEET

UseUse

Friends don’t Let Friends Friends don’t Let Friends use use UseUse

•Leads to problems during maintenanceLeads to problems during maintenance

•Makes debugging difficultMakes debugging difficult

•Pollutes the Pollutes the name spacename space

Page 24: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 24ASEET

When Might it Help?When Might it Help?

To achieve direct visibility of a To achieve direct visibility of a typetype, not a , not a library unit.library unit.

with Complex_Numbers;with Complex_Numbers;

procedure Test isprocedure Test is

use type Complex_Numbers.Complex;use type Complex_Numbers.Complex;

A,B,C : Complex_Numbers.Complex;A,B,C : Complex_Numbers.Complex;

--NOTE: Fully specified name required--NOTE: Fully specified name required

beginbegin

… …

C := A * B; -- infix operation allowed!! C := A * B; -- infix operation allowed!!

The The newnew use clause allows you to create direct visibility at use clause allows you to create direct visibility at a type rather than a package level. This allows infix a type rather than a package level. This allows infix operations on variables where the type is not directly operations on variables where the type is not directly visible.visible.

Page 25: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 25ASEET

SCALARSCALAR

COMPOSITECOMPOSITE

PRIVATEPRIVATE

ACCESSACCESS

TASKTASK

Objects are single valuesObjects are single values

Objects contain other Objects contain other componentscomponents

Objects are Objects are abstractabstract

Objects Objects pointpoint to other to other objects & objects & subprogramssubprograms

Objects are parallel Objects are parallel processesprocesses

Coordinated access to Coordinated access to shared datashared data

Inheritance & Run-time Inheritance & Run-time polymorphismpolymorphism

Classes of Ada TypesClasses of Ada Types

ProtectedProtected

TaggedTagged

AdaAdaTypesTypes

Page 26: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 26ASEET

Predefined TypesPredefined TypesBooleanBooleanIntegerInteger

Natural (Subtype)Natural (Subtype)Positive (Subtype)Positive (Subtype)Mod (Modulus) --NewMod (Modulus) --New

FloatFloatCharacterCharacterWide_CharacterWide_Character --New --NewStringString

Wide_StringWide_String --New --NewFixedFixed Decimal_Fixed_Point --NewDecimal_Fixed_Point --New

type Byte is Mod 255;type Byte is Mod 255;-- an unsigned byte-- an unsigned byte

-- ISO 8859-1 character set-- ISO 8859-1 character set-- ISO10646 BMP character set-- ISO10646 BMP character setBname : String := "Bill “;Bname : String := "Bill “;

--String auto-set to 5--String auto-set to 5Foo : Wide_String := “Foo : Wide_String := ““;“;

type Money is delta 0.01 digits 15; type Money is delta 0.01 digits 15;

Page 27: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 27ASEET

Access TypesAccess TypesAccess types point to data structures, subprograms, or other Access types point to data structures, subprograms, or other access typesaccess types

type Name_Type is string (1..10);type Name_Type is string (1..10);

Type Name_Ptr_Type is access Name_Type;Type Name_Ptr_Type is access Name_Type;

type Int_Ptr is access Integer;type Int_Ptr is access Integer;

type Vehicle_Ptr is access all Vehicle’class;type Vehicle_Ptr is access all Vehicle’class;

type Procedure_Ptr is access procedure; --points to anytype Procedure_Ptr is access procedure; --points to any

--parameterless procedure--parameterless procedure

IP : Int_Ptr;IP : Int_Ptr;

I : aliased Integer; --I : aliased Integer; --aliasedaliased allows I to be pointed to allows I to be pointed to

IP := I’Access;IP := I’Access;

IP.all := 42;IP.all := 42; --I must be de-referenced as --I must be de-referenced as allall

IP := new Integer’(I); IP := new Integer’(I); --makes new values, copies I into it--makes new values, copies I into it

Page 28: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 28ASEET

Problem with PointersProblem with Pointers

It is often convenient to declare a pointer to a data It is often convenient to declare a pointer to a data object and use this pointer as a parameter.object and use this pointer as a parameter.

The problem: even if you make this parameter a The problem: even if you make this parameter a read onlyread only parameter via the parameter via the inin mode, the mode, the function/procedure can change what the pointer function/procedure can change what the pointer points to (rather than the pointer itself).points to (rather than the pointer itself).

To prevent this, there is a mechanism that makes To prevent this, there is a mechanism that makes a pointer and what it points to a pointer and what it points to read onlyread only. .

Page 29: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 29ASEET

Constant Access TypesConstant Access Types

Replace the word Replace the word allall in the type definition by the word in the type definition by the word constantconstant..

type Int_Ptr is access constant Integer;type Int_Ptr is access constant Integer;

Now, variables of type Int_Ptr can point to Integers, but what Now, variables of type Int_Ptr can point to Integers, but what they point to may not be modified.they point to may not be modified.

IP : Int_Ptr;IP : Int_Ptr;I : aliased Integer;I : aliased Integer; ----aliasedaliased allows I to be pointed to allows I to be pointed to

IP := I’Access;IP := I’Access;

IP := new Integer’ (I);IP := new Integer’ (I); --legal, not modifying what IP points to--legal, not modifying what IP points toIP := new Integer’ (5);IP := new Integer’ (5); --new value, original still not modified--new value, original still not modified

IP.all := 5; IP.all := 5; --illegal, compiler error. IP is --illegal, compiler error. IP is read onlyread only

This allows you to declare a pointer type, pass it as a parameter, This allows you to declare a pointer type, pass it as a parameter, and prevent the procedure/function from modifying what the and prevent the procedure/function from modifying what the pointer points to. pointer points to.

Page 30: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 30ASEET

Dynamic SelectionDynamic Selection

type Trig_Function is access function (F : Float) return Float;type Trig_Function is access function (F : Float) return Float;

T : Trig_Function;T : Trig_Function;

X, Theta : Float;X, Theta : Float;

T := Sin’Access; T := Sin’Access;

X := T(Theta);X := T(Theta); -- implicit de-referencing. -- implicit de-referencing. SHOULD NOT BE USED!SHOULD NOT BE USED! -- This looks like normal function call. -- This looks like normal function call.

X := T.all (Theta); -- explicit de-referencing. X := T.all (Theta); -- explicit de-referencing. THIS IS PREFERREDTHIS IS PREFERRED..

An access type can refer to a subprogram; an access-to-An access type can refer to a subprogram; an access-to-subprogram value can be created by the subprogram value can be created by the ‘Access‘Access attribute. attribute. A subprogram can be called using this pointer. This allows A subprogram can be called using this pointer. This allows you to include a pointer to a routine inside of a record, or as you to include a pointer to a routine inside of a record, or as a parameter. This is known as a a parameter. This is known as a callbackcallback..

T can T can point topoint to functions (such as Sin, Cos functions (such as Sin, Cos and Tan) that have a matching parameter and Tan) that have a matching parameter list. Functions must have matching return list. Functions must have matching return types.types.

Page 31: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 31ASEET

CallbackCallbackssprocedure Call_Word_Processor is......

procedure Ring_Bell is ..........

type Action_Call is access procedure;

type Button_Type is record

X_Pos : Integer;Y_Pos : Integer;Action_When_Left_Button_Pushed : Action_Call;Action_When_Right_Button_Pushed : Action_Call;

end;

Button_1 : Button_Type := ( 100, 50, Call_Word_Processor’access, Ring_Bell’access );

Page 32: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 32ASEET

Object-Oriented MethodsObject-Oriented Methods

OO is closely allied to reusability. It’s main OO is closely allied to reusability. It’s main advantage is that systems can be separated advantage is that systems can be separated into logical components, allowing better into logical components, allowing better modeling of the problem world. OO creates modeling of the problem world. OO creates betterbetter abstractions abstractions. .

In addition, OO systems can be extended, In addition, OO systems can be extended, rather than modified, to add functionality. rather than modified, to add functionality. This prevents disturbing existing software, This prevents disturbing existing software, eliminating the risk of introducing errors. eliminating the risk of introducing errors.

Page 33: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 33ASEET

Ada Support for Phases Ada Support for Phases of the OO Lifecycle of the OO Lifecycle

OORAOORA– PackagingPackaging– Abstraction & EncapsulationAbstraction & Encapsulation– Parallel ProcessingParallel Processing

OODOOD– Packaging & Child PackagesPackaging & Child Packages– Strong TypingStrong Typing– Enumeration TypesEnumeration Types– Parallel ProcessingParallel Processing

OOPOOP– InheritanceInheritance– Polymorphism (Dispatching)Polymorphism (Dispatching)– TaskingTasking

OORAOORA

OODOOD

OOPOOP

Page 34: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 34ASEET

Tagged Type Tagged Type type Rectangle is taggedtype Rectangle is tagged

recordrecord

Length : Float := 0.0;Length : Float := 0.0;

Width : Float := 0.0;Width : Float := 0.0;

end record;end record;

-- Operations for inheritance now defined -- Operations for inheritance now defined

-- Example: Rectangles have a defined perimeter, and-- Example: Rectangles have a defined perimeter, and

-- children derived from Rectangle will have Perimeter-- children derived from Rectangle will have Perimeter

function Perimeter (R : in Rectangle ) return Float isfunction Perimeter (R : in Rectangle ) return Float is

beginbegin

return 2.0 * (R.Length +R.Width);return 2.0 * (R.Length +R.Width);

end Perimeter;end Perimeter;

Page 35: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 35ASEET

Tagged Types - Tagged Types - InheritanceInheritance

CuboidCuboid inheritsinherits Perimeter from Rectangle (technically, Perimeter from Rectangle (technically, Perimeter is aPerimeter is a primitiveprimitive operation). The function will have to operation). The function will have to be updated for the new type (Perimeter is defined differently be updated for the new type (Perimeter is defined differently for cubes!).for cubes!).

To do this, you need to To do this, you need to overrideoverride the operation. One way to do the operation. One way to do this is to write a new Perimeter. A better way it to base the this is to write a new Perimeter. A better way it to base the new Perimeter on the parent class operation.new Perimeter on the parent class operation.

type Cuboid is new Rectangle withtype Cuboid is new Rectangle with recordrecord Height : Float := 0.0;Height : Float := 0.0; end record; end record;

function Perimeter (C : in Cuboid ) return Float isfunction Perimeter (C : in Cuboid ) return Float isbeginbegin return Perimeter (Rectangle(C)) * 2.0 + ( 4.0 * C.Height);return Perimeter (Rectangle(C)) * 2.0 + ( 4.0 * C.Height);end Perimeter;end Perimeter;

Page 36: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 36ASEET

Abstract Types & Abstract Types & SubprogramsSubprograms

• Purpose of an abstract type is to provide a common foundation Purpose of an abstract type is to provide a common foundation upon which useful types can be built by derivation.upon which useful types can be built by derivation.

• An abstract subprogram is a place holder for an operation to An abstract subprogram is a place holder for an operation to be provided (it does not have a body). be provided (it does not have a body).

• An abstract subprogram An abstract subprogram MUSTMUST be overridden for be overridden for EACHEACH

subclasssubclass

-- Baseline package used to serve as -- Baseline package used to serve as rootroot of inheritance tree of inheritance tree

package Vehicle_Package ispackage Vehicle_Package is

type Vehicle is abstract tagged null record;type Vehicle is abstract tagged null record;

procedure Start (Item : in out Vehicle) is abstract;procedure Start (Item : in out Vehicle) is abstract;

end Vehicle_Package;end Vehicle_Package;

Page 37: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 37ASEET

Abstract Types and Abstract Types and SubprogramsSubprograms

type Train is new Vehicle withtype Train is new Vehicle withrecordrecord

passengers : Integer;passengers : Integer;end Train;end Train;

My_Train : Train; -- ILLEGALMy_Train : Train; -- ILLEGAL

We can’t yet declare an object of We can’t yet declare an object of TrainTrain. Why? Because we haven't . Why? Because we haven't filled in the filled in the abstract partsabstract parts declared in it’s parent. We have completed declared in it’s parent. We have completed the the abstract recordabstract record, but still need to define procedure , but still need to define procedure Start Start for the for the TrainTrain..

type Train is new Vehicle withtype Train is new Vehicle withrecordrecord

passengers : Integer;passengers : Integer;end Train;end Train;

procedure Start (Item : in out Train) is ....procedure Start (Item : in out Train) is ....My_Train : Train; My_Train : Train;

Page 38: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 38ASEET

Building Inheritance Building Inheritance ChainsChains

All record that derive from a tagged record are All record that derive from a tagged record are implicitly tagged.implicitly tagged.

Each inherited record inherits all fields and operations Each inherited record inherits all fields and operations from its parent, creating an inheritance from its parent, creating an inheritance chainchain..

If you use an operation on a inherited type that is not If you use an operation on a inherited type that is not explicitly written for that type, then the explicitly written for that type, then the chainchain is is searched towards the root. The first instance of the searched towards the root. The first instance of the operation will apply. operation will apply.

You can even add abstract records at a child level, You can even add abstract records at a child level, allowing you to selectively create the exact fields and allowing you to selectively create the exact fields and inheritance desired.inheritance desired.

Page 39: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 39ASEET

Abstract typesAbstract typestype Planes is abstract new Vehicle withtype Planes is abstract new Vehicle with

recordrecordWingspan : Some_Type;Wingspan : Some_Type;

end Planes;end Planes;

function Runway_Needed_To_Landfunction Runway_Needed_To_Land (Item : Planes) return Feet is abstract;(Item : Planes) return Feet is abstract;

You cannot declare a variable of type Planes (it is abstract), so You cannot declare a variable of type Planes (it is abstract), so you must derive from it. However, when you derive a new you must derive from it. However, when you derive a new type from Planes, you must also override the function type from Planes, you must also override the function Runway_Needed_To_Land.Runway_Needed_To_Land.

Page 40: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 40ASEET

PolymorphismPolymorphism

From the Greek From the Greek polypoly, many, and , many, and morphemorphe, form. , form. Polymorphism is another property of Object Oriented Polymorphism is another property of Object Oriented languages. languages.

Class-wide types are said to be polymorphic because a Class-wide types are said to be polymorphic because a class-wide variable can hold objects belonging to any class-wide variable can hold objects belonging to any type within the class. type within the class.

Page 41: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 41ASEET

Class Wide Class Wide ProgrammingProgrammingtype T’Classtype T’ClassVehicle

Trains

Planes

Automobiles

Planes’Class

Vehicle’Class

Jet Propeller Helicopters

• With each tagged type there is an associated type With each tagged type there is an associated type ’Class. ’Class.

• The values of this ’Class type include all derived The values of this ’Class type include all derived types. types.

• Any derived type may be converted to the type Any derived type may be converted to the type ’Class.’Class.

Page 42: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 42ASEET

Class Wide Programming Class Wide Programming (Dispatching)(Dispatching)

---- class-wide value as parameterclass-wide value as parameterProcedure Move_All ( Item : in out Vehicle’Class) isProcedure Move_All ( Item : in out Vehicle’Class) is......beginbegin ...... Start (Item); -- dispatch according to tagStart (Item); -- dispatch according to tag ......end Move_All;end Move_All;

The procedure Move_All is a The procedure Move_All is a class-wideclass-wide operation, since any variable in operation, since any variable in the Vehicle hierarchy can be passed to it. the Vehicle hierarchy can be passed to it.

Start, however, is defined for each type within the Vehicle hierarchy. Start, however, is defined for each type within the Vehicle hierarchy. Depending on the type of Item, a different Start will be called. During 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 runtime, the specific type of Item is known, but it is not known at compile time. The compile time. The runtime systemruntime system must must dispatchdispatch to the correct to the correct procedure call.procedure call.

Page 43: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 43ASEET

Static BindingStatic Binding

-- class-wide value as parameter-- class-wide value as parameter

Procedure Move_All ( Item : in out Vehicle’Class) isProcedure Move_All ( Item : in out Vehicle’Class) is......beginbegin ...... Start (Item); Start (Item); -- dispatch according to tag (Dynamic Dispatching)-- dispatch according to tag (Dynamic Dispatching)

Start (Jet(Item)); Start (Jet(Item)); ---- static call to the Start for Jet.static call to the Start for Jet.

-- this call will fail at run time if Item is not-- this call will fail at run time if Item is not -- a member of the Jet hierarchy-- a member of the Jet hierarchy

......end Move_All;end Move_All;

Page 44: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 44ASEET

Class Wide Programming Class Wide Programming (Dispatching using (Dispatching using

pointers)pointers)

--control routine can manipulate the vehicles directly from the --control routine can manipulate the vehicles directly from the list.list.

procedure Move_All isprocedure Move_All is

Next : Vehicle_Ptr;Next : Vehicle_Ptr;

beginbegin

......

Next := Some_Vehicle; -- Get next vehicleNext := Some_Vehicle; -- Get next vehicle

......

Start (Next.all); Start (Next.all); -- Dispatch to appropriate Handle -- Dispatch to appropriate Handle

...... -- Note the de-referencing of pointer -- Note the de-referencing of pointer

end Move_All;end Move_All;

-- Vehicles held as a heterogeneous list using an access -- Vehicles held as a heterogeneous list using an access type.type.

type Vehicle_Ptr is access all Vehicle’Class;type Vehicle_Ptr is access all Vehicle’Class;

Page 45: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 45ASEET

Controlled TypesControlled Types

A type derived from Controlled can have an user-defined A type derived from Controlled can have an user-defined AdjustAdjust, , FinalizeFinalize,, and and InitializeInitialize routines. Every time an object routines. Every time an object of this type is assigned, released (via exiting scope or freeing of this type is assigned, released (via exiting scope or freeing up a pointer) or created, the appropriate routine will be called.up a pointer) or created, the appropriate routine will be called.

package Ada.Finalization ispackage Ada.Finalization is

type Controlled is abstract tagged private;type Controlled is abstract tagged private;

procedure Initialize (Object: in out Controlled); procedure Initialize (Object: in out Controlled); procedure Adjust (Object: in out Controlled); procedure Adjust (Object: in out Controlled); procedure Finalize (Object: in out Controlled);procedure Finalize (Object: in out Controlled);

Page 46: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 46ASEET

Controlled Type Example

with Ada.Finalization;

package Bathroom_Stalls is

type Stall is new Ada.Finalization.Controlled with private;

private

type Stall is new Ada.Finalization.Controlled with record

ID : integer; end record;

procedure Initialize (Object : in out stall);

procedure Adjust (Object : in out stall);

procedure Finalize (Object : in out stall);

end Bathroom_Stalls;

Page 47: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 47ASEET

with Ada.Text_IO;use Ada.Text_IO;package body Bathroom_Stalls is

Stall_No : Natural := 1;Stalls_In_Use : Natural := 0;

procedure Initialize (Object : in out Stall) is begin object.id := Stall_No; put ("In Initialize, object # " & integer'image(object.id) ); Stall_No := Stall_No + 1; Stalls_In_Use := Stalls_In_Use + 1; Put_Line(". There are "& integer'image(Stalls_In_Use) & " People in stalls."); end Initialize;

procedure Adjust (Object : in out Stall) renames Initialize;

procedure Finalize (Object : in out Stall) is begin put("In Finalize, object # " & integer'image(object.id) ); Stalls_In_Use := Stalls_In_Use - 1; Put_Line(". There are "&integer'image(Stalls_In_Use) & " People in stalls."); end Finalize;

end Bathroom_Stalls;

Page 48: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 48ASEET

Controlled Type Examplewith bathroom_stalls;procedure stalls is

A,B: bathroom_stalls.stall; --initialize called twice

begin declare D: bathroom_stalls.stall; --initialize begin A := D; --finalize, then adjust (initialize) end;A := B; --finalize, then adjust (initialize)end;

In Initialize, object # 1. There are 1 People in stalls.In Initialize, object # 2. There are 2 People in stalls.In Initialize, object # 3. There are 3 People in stalls.In Finalize, object # 1. There are 2 People in stalls.In Initialize, object # 4. There are 3 People in stalls.In Finalize, object # 3. There are 2 People in stalls.In Finalize, object # 4. There are 1 People in stalls.In Initialize, object # 5. There are 2 People in stalls.In Finalize, object # 2. There are 1 People in stalls.In Finalize, object # 5. There are 0 People in stalls.

Page 49: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 49ASEET

PARAMETER MODEPARAMETER MODE

The direction (from the standpoint of the The direction (from the standpoint of the subprogram) in which the value associated subprogram) in which the value associated with the formal parameter is passedwith the formal parameter is passed

Three modesThree modes– inin - Parameter may only be read- Parameter may only be read– outout - Parameter may be updated and then read- Parameter may be updated and then read

– in out - Parameter may be both read and updatedin out - Parameter may be both read and updated

Functions may only have Functions may only have inin parameters parameters

The default parameter mode is The default parameter mode is inin

must be a variable

Page 50: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 50ASEET

Parallel ProcessingParallel Processing(Tasking)(Tasking)

The Ada parallel processing model is a useful The Ada parallel processing model is a useful model for the abstract description of many model for the abstract description of many parallel processing problems. In addition, a parallel processing problems. In addition, a more static monitor-like approach is available more static monitor-like approach is available for shared data-access applications. for shared data-access applications.

Ada provides support for single and multiple Ada provides support for single and multiple processor parallel processing, and also processor parallel processing, and also includes support for time-critical real-time and includes support for time-critical real-time and distributed applications.distributed applications.

Page 51: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 51ASEET

Protected TypesProtected Types

Protected types provide a low-level, Protected types provide a low-level, lightweight synchronization mechanism lightweight synchronization mechanism whose key features are:whose key features are:

Protected types are used to control Protected types are used to control access to data shared among multiple access to data shared among multiple processes. processes.

Operations of the protected type Operations of the protected type synchronize access to the data.synchronize access to the data.

Protected types have three kinds of Protected types have three kinds of operations: protected functions, operations: protected functions, protected procedures, and entries.protected procedures, and entries.

Page 52: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 52ASEET

Protected Units & Protected Units & Protected ObjectsProtected Objects

Protected procedures provide mutually exclusive read-write access to the data of a protected object

Protected functions provide concurrent read-only access to the data.

Protected entries also provide exclusive read-write access to the data.

Protected entries have a specified barrier (a Boolean expression). This barrier must be true prior to the entry call allowing access to the data.

Page 53: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 53ASEET

Protected TypesProtected Types package Mailbox_Pkg ispackage Mailbox_Pkg is

type Parcels_Count is range 0 .. Mbox_Size;type Parcels_Count is range 0 .. Mbox_Size;type Parcels_Index is range 1 .. Mbox_Size;type Parcels_Index is range 1 .. Mbox_Size;type Parcels_Array is array ( Parcel_Index ) of Parcelstype Parcels_Array is array ( Parcel_Index ) of Parcelsprotected type Mailbox isprotected type Mailbox is

-- put a data element into the buffer-- put a data element into the bufferentry Send (Item : Parcels);entry Send (Item : Parcels);

-- retrieve a data element from the buffer-- retrieve a data element from the bufferentry Receive (Item : out Parcels);entry Receive (Item : out Parcels);procedure Clear;procedure Clear;function Number_In_Box return Integer;function Number_In_Box return Integer;

privateprivateCountCount : Parcels_count := 0;: Parcels_count := 0;Out_IndexOut_Index : Parcels_Index := 1;: Parcels_Index := 1;In_IndexIn_Index : Parcels_Index := 1;: Parcels_Index := 1;DataData : Parcels_Array ;: Parcels_Array ;

end Mailbox;end Mailbox;end Mailbox_Pkg;end Mailbox_Pkg;

Page 54: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 54ASEET

package body Mailbox_Pkg ispackage body Mailbox_Pkg is

protected body Mailbox isprotected body Mailbox is

entry Send ( Item : Parcels) when Count < Mbox_Size is entry Send ( Item : Parcels) when Count < Mbox_Size is -- block until room-- block until room

beginbeginData ( In_Index ) := Item;Data ( In_Index ) := Item;In_Index := In_Index mod Mbox_size + 1;In_Index := In_Index mod Mbox_size + 1;Count := Count + 1;Count := Count + 1;

end Send;end Send;

entry Receive ( Item : out Parcels ) when Count > 0 is entry Receive ( Item : out Parcels ) when Count > 0 is -- block until non--- block until non-

emptyemptybeginbegin

Item := Data( Out_Index );Item := Data( Out_Index );Out_Index := Out_Index mod Mbox_Size + 1;Out_Index := Out_Index mod Mbox_Size + 1;Count := Count -1;Count := Count -1;

end Receive;end Receive;

Protected Types ExampleProtected Types Example

Page 55: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 55ASEET

Protected Types Protected Types Example (cont.)Example (cont.)

procedure Clear is procedure Clear is --only one user in Clear at a time --only one user in Clear at a timebeginbegin

Count := 0;Count := 0;Out_Index := 1;Out_Index := 1;In_Index := 1; In_Index := 1;

end Clear;end Clear;

function Number_In_Box return Integer is function Number_In_Box return Integer is -- many users can check # -- many users can check #

in Box in Box beginbegin

return Count; return Count; end Number_In_Box;end Number_In_Box;

end Mailbox;end Mailbox;

end Mailbox_Pkg;end Mailbox_Pkg;

Page 56: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 56ASEET

selectselect triggering_alternative; triggering_alternative;then abortthen abort abortable_part; abortable_part;end select;end select;

Asynchronous Transfer of Asynchronous Transfer of ControlControl

The abortable part is executed if the triggering The abortable part is executed if the triggering alternative is not ready. alternative is not ready.

If the triggering alternative becomes ready If the triggering alternative becomes ready prior to the completion of the abortable part, prior to the completion of the abortable part, then the abortable part is aborted. then the abortable part is aborted.

If the abortable part completes, then the If the abortable part completes, then the triggering alternative is cancelled.triggering alternative is cancelled.

Page 57: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 57ASEET

Asynchronous Transfer of Asynchronous Transfer of ControlControl

((Waiting for an Event)Waiting for an Event)

looploopselectselect

Terminal.Wait_For_Interrupt;Terminal.Wait_For_Interrupt;Ada.Text_IO.Put_Line(“Interrupted”);Ada.Text_IO.Put_Line(“Interrupted”);

then abortthen abortAda.Text_IO.Put_Line(“Enter Command --> “);Ada.Text_IO.Put_Line(“Enter Command --> “);Ada.Text_IO.Get_Line(Command, Last);Ada.Text_IO.Get_Line(Command, Last);Parse_and_Process (Command (1..Last) )Parse_and_Process (Command (1..Last) )

end loop;end loop;end Poll_Device;end Poll_Device;

Page 58: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 58ASEET

selectselect

delay 5.0;delay 5.0;

Ada.Text_IO.Put_Line(“Calculation does not converge”);Ada.Text_IO.Put_Line(“Calculation does not converge”);

Some_Default_Action;Some_Default_Action;

then abortthen abort

Horribly_Complicated_Recursive_Function(X,Y);Horribly_Complicated_Recursive_Function(X,Y);

end select;end select;

-- After 5 seconds (plus a little), I will reach here-- After 5 seconds (plus a little), I will reach here

Asynchronous Transfer of Asynchronous Transfer of ControlControl

((Creating a Creating a Timeout)Timeout)

Page 59: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 59ASEET

Requeue StatementRequeue Statement

The The requeuerequeue allows a call to an entry to allows a call to an entry to be placed back in the queue for later be placed back in the queue for later processing.processing.

Without the Without the with abortwith abort option, the option, the requeued entry is protected against requeued entry is protected against cancellation.cancellation.

requeue Entry_Name [with abort];requeue Entry_Name [with abort];

Page 60: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 60ASEET

delay Next_Time - Calendar.Now;delay Next_Time - Calendar.Now;

suspended for at least suspended for at least the duration specifiedthe duration specified

specifies an absolute time specifies an absolute time rather than a time intervalrather than a time interval

The The untiluntil does notdoes not provide a guaranteed delay interval, but it does provide a guaranteed delay interval, but it does prevent inaccuracies due to swapping out between the “delay prevent inaccuracies due to swapping out between the “delay interval calculation” and the delay statementinterval calculation” and the delay statement

delay until Next_time;delay until Next_time;

Delay and Until Delay and Until StatementsStatements

Page 61: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 61ASEET

EXCEPTIONSEXCEPTIONS

Hadnling all posible Erors!Hadnling all posible Erors!

Note : There are four errors in this slide. Note : There are four errors in this slide.

Exceptions and exception handling in Ada 95 Exceptions and exception handling in Ada 95 are still exceptional!!are still exceptional!!

Page 62: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 62ASEET

ExceptionsExceptions Exceptions are a mechanism to allow the programmer to identify Exceptions are a mechanism to allow the programmer to identify

and handle errors within the program without calling system error and handle errors within the program without calling system error routines.routines.

There are two kinds of exceptions:There are two kinds of exceptions:

– predefined exceptionspredefined exceptions Standard (Standard (Constraint, Program, Storage, TaskingConstraint, Program, Storage, Tasking ) )

IO (IO (Status, Mode, Name, Data, Layout, End, Device, Use)Status, Mode, Name, Data, Layout, End, Device, Use)

– user-defined exceptionsuser-defined exceptions Allows the designer to define and Allows the designer to define and raiseraise non-standard exceptions non-standard exceptions

Exception handlers Exception handlers handle the exception.handle the exception.

– You can also You can also namename and and save save an exception externally.an exception externally.

– An exception can be An exception can be re-raisedre-raised and it can be and it can be propagated.propagated.

Page 63: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 63ASEET

Generics Define a Template OrGenerics Define a Template Or

Mold for Programs UnitsMold for Programs Units

GENERICSGENERICS

Page 64: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 64ASEET

GenericsGenerics Generics allow you to create a template for Generics allow you to create a template for

packages, functions, and procedures. packages, functions, and procedures. Generic templates can be customized via Generic templates can be customized via runtime runtime

elaborationelaboration.. During elaboration, generic parameters are used to During elaboration, generic parameters are used to

create ancreate an instantiation instantiation of the generic template. of the generic template. Generic parameters includeGeneric parameters include

– typestypes– variables and constantsvariables and constants– functions and proceduresfunctions and procedures– another generic instantiationanother generic instantiation– packagespackages

Page 65: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 65ASEET

Unchecked Conversion Unchecked Conversion and Unchecked Accessand Unchecked Access

Unchecked_ConversionUnchecked_Conversion– Converts any type to any other type. Converts any type to any other type. – Strictly a Strictly a bit by bit bit by bit conversion. conversion. – Constraint and Range checking left up to the program.Constraint and Range checking left up to the program.– This attribute, if misused, can lead to corrupted data structures.This attribute, if misused, can lead to corrupted data structures.

X’Valid X’Valid – Checks to see if the object has a Checks to see if the object has a safesafe value. value.

X’Unchecked_AccessX’Unchecked_Access – Overrides type checking for access values.Overrides type checking for access values.– Program is responsible for removing local objects from global Program is responsible for removing local objects from global

data structures prior to exiting the objects’ scope. data structures prior to exiting the objects’ scope. – This attribute, if misused, can lead to corrupted data structures.This attribute, if misused, can lead to corrupted data structures.

Page 66: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 66ASEET

AnnexesAnnexesThree Annexes are required:Three Annexes are required:

• Annex A, ``Predefined Language Annex A, ``Predefined Language Environment''Environment''• Annex B, ``Interface to Other Languages''Annex B, ``Interface to Other Languages''• Annex J, ``Obsolescent Features''Annex J, ``Obsolescent Features''

The following Specialized Needs Annexes define The following Specialized Needs Annexes define optional additions to the language. A compiler optional additions to the language. A compiler including them, however, must be in full compliance. including them, however, must be in full compliance.

• Annex C, ``Systems Programming''Annex C, ``Systems Programming''• Annex D, ``Real-Time Systems''Annex D, ``Real-Time Systems''• Annex E, ``Distributed Systems''Annex E, ``Distributed Systems''• Annex F, ``Information Systems''Annex F, ``Information Systems''• Annex G, ``Numerics''Annex G, ``Numerics''• Annex H, ``Safety and Security''Annex H, ``Safety and Security''

Page 67: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 67ASEET

Annex A. Predefined Annex A. Predefined Language EnvironmentLanguage Environment

Annex AAnnex A contains packages that support contains packages that support– Predefined IdentifiersPredefined Identifiers– Character HandlingCharacter Handling– String HandlingString Handling– Numerical FunctionsNumerical Functions

Basic math functionsBasic math functions General Trig/Log functionsGeneral Trig/Log functions

– Random Number GenerationRandom Number Generation DiscreteDiscrete ContinuousContinuous

Page 68: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 68ASEET

INPUT/OUTPUTINPUT/OUTPUT

• Ada supports many different types of predefined Ada supports many different types of predefined IO.IO.

• Each type has its’ own package with supporting Each type has its’ own package with supporting functions and procedures: functions and procedures:

– Ada.Sequential_IOAda.Sequential_IO– Ada.Direct_IOAda.Direct_IO– Ada.Wide_Text_IO Ada.Wide_Text_IO – Ada.Streams.Stream_IOAda.Streams.Stream_IO– Ada.Text_IOAda.Text_IO --this is where --this is where Text_IOText_IO is now is now

Page 69: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 69ASEET

Other “Bells and Other “Bells and Whistles”Whistles”

One character look-ahead in files (without One character look-ahead in files (without moving file pointer)moving file pointer)

Get immediate from keyboard (no carriage Get immediate from keyboard (no carriage return required)return required)

Procedure to Procedure to flushflush file buffer without file buffer without closing then re-opening fileclosing then re-opening file

Stream IO (mixed text and binary)Stream IO (mixed text and binary)

Ability to read command line from within Ability to read command line from within programprogram

Page 70: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 70ASEET

pragma Import pragma Import

pragma Exportpragma Export

pragma Conventionpragma Convention

used to import a used to import a foreign language into foreign language into

AdaAdaused to export an Ada

entity to a foreign language

use the conventions of another language

Annex BAnnex BInterfacing to Other Interfacing to Other

LanguagesLanguages

Page 71: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 71ASEET

Standard Interfaces -Standard Interfaces -Required PackagesRequired Packages

package Interface.C package Interface.C – Has two required child packagesHas two required child packages

Interface.C.StringsInterface.C.Strings Interface.C.PointersInterface.C.Pointers

package Interface.Cobol package Interface.Cobol

package Interface.Fortranpackage Interface.Fortran

Page 72: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 72ASEET

Annex C. Systems Annex C. Systems ProgrammingProgramming

Covers a number of low-level Covers a number of low-level features such as features such as – in-line machine instructions, in-line machine instructions, – interrupt handling, interrupt handling, – shared variable accessshared variable access– task identification. task identification. – AtomicAtomic pragma (indivisible read/writes) pragma (indivisible read/writes)– VolatileVolatile pragma (bypasses cache memory) pragma (bypasses cache memory)

This annex is a requirement for Annex D, This annex is a requirement for Annex D, Real-Time Systems Annex.Real-Time Systems Annex.

Page 73: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 73ASEET

Annex D. Real-time Annex D. Real-time SystemsSystems

Includes pragmas that allow you to tailorIncludes pragmas that allow you to tailor– scheduling of parallel processesscheduling of parallel processes– priorities of parallel processespriorities of parallel processes– queueing protocols for entry callsqueueing protocols for entry calls– ceiling-locking protocolsceiling-locking protocols

Must include documentation specifyingMust include documentation specifying– time it takes to actually abort a task on both single time it takes to actually abort a task on both single

and multi-processor systemsand multi-processor systems– time it takes to process an asynchronous selecttime it takes to process an asynchronous select

Includes a Monotonic time packageIncludes a Monotonic time package Includes low-level asynchronous and Includes low-level asynchronous and

synchronous task control optionssynchronous task control options

Page 74: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 74ASEET

Annex E. Distributed Annex E. Distributed SystemsSystems

Includes features that give you ability toIncludes features that give you ability to– communicate between communicate between partitionspartitions running on running on

different different processingprocessing and/or and/or storagestorage nodes. nodes.

– categorize library units as to how they are used categorize library units as to how they are used (determines if/when it can be distributed). (determines if/when it can be distributed).

– set up a remote library that is used for remote set up a remote library that is used for remote procedure calls (RPCS), using both procedure calls (RPCS), using both staticstatic binding binding and and dynamicdynamic binding of remote procedures binding of remote procedures

– make an make an asynchronousasynchronous procedure call (which procedure call (which returns without waiting for completion).returns without waiting for completion).

Page 75: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 75ASEET

Annex F. Information Annex F. Information SystemsSystems

This Annex provides a set of of facilities This Annex provides a set of of facilities relevant to Information Systems relevant to Information Systems programming. These fall into several programming. These fall into several categories:categories:– The package Decimal which declares a set of constants The package Decimal which declares a set of constants

defining the implementation’s capacity for decimal types, and defining the implementation’s capacity for decimal types, and a generic package for decimal division.a generic package for decimal division.

– The child package Text_IO.Pictures, which supports formatted The child package Text_IO.Pictures, which supports formatted and localized output of decimal data, based on and localized output of decimal data, based on picture string.picture string.

Page 76: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 76ASEET

Annex G. NumericsAnnex G. Numerics The Numerics Annex specifies:The Numerics Annex specifies:

– features for complex arithmetic, including complex I/Ofeatures for complex arithmetic, including complex I/O– a a strict strict mode in which the predefined arithmetic mode in which the predefined arithmetic

operations of floating point and fixed point types have to operations of floating point and fixed point types have to provide guaranteed accuracy or conform to other numeric provide guaranteed accuracy or conform to other numeric performance requirementsperformance requirements

– a a relaxed relaxed mode in which no accuracy or other numeric mode in which no accuracy or other numeric performance requirements need be satisfied (as for performance requirements need be satisfied (as for implementations not conforming to the Numerics Annex)implementations not conforming to the Numerics Annex)

Page 77: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 77ASEET

Annex H. Safety and Annex H. Safety and SecuritySecurity

This Annex address requirements for systems This Annex address requirements for systems that are safety critical or have security that are safety critical or have security constraints. It provides facilities and constraints. It provides facilities and specifies documentation requirements that specifies documentation requirements that relate to several needs:relate to several needs:– Predicting program executionPredicting program execution

– Reviewing of object codeReviewing of object code

– Restricting language constructs whose usage might Restricting language constructs whose usage might interfere with program reliabilityinterfere with program reliability

Page 78: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 78ASEET

Pragma Reviewable;Pragma Reviewable;

Directs the compiler to generate object code Directs the compiler to generate object code that can be independently validated.that can be independently validated.

The following information must be producedThe following information must be produced– Where compiler-generated run-time checks remainWhere compiler-generated run-time checks remain

– Identification of any construct that is certain to failIdentification of any construct that is certain to fail

– Where run-time support routines are implicitly invokedWhere run-time support routines are implicitly invoked

– For each scalar, either “Initialized” or “Possibly uninitialized”For each scalar, either “Initialized” or “Possibly uninitialized”

– An object code listing with machine instructions, offsets, and An object code listing with machine instructions, offsets, and source code correspondencesource code correspondence

– Identification of each construct with possible erroneous Identification of each construct with possible erroneous executionexecution

– Order of library elaborationOrder of library elaboration

Page 79: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 79ASEET

Annex J. Obsolescent Annex J. Obsolescent FeaturesFeatures

• This section contains descriptions of features of the This section contains descriptions of features of the language that worked under Ada 83, but are no language that worked under Ada 83, but are no longer needed and not recommended under Ada 95.longer needed and not recommended under Ada 95.

• Most good programmers will not find any of the Most good programmers will not find any of the “obsolescent features” a problem. However, there “obsolescent features” a problem. However, there are a few changes to Ada 95 that would require a lot are a few changes to Ada 95 that would require a lot of “nit-picking” changes. There are a few predefined of “nit-picking” changes. There are a few predefined renaming clauses to prevent you from having to edit renaming clauses to prevent you from having to edit all of your old programs. However, your new all of your old programs. However, your new programs should use the correct methods.programs should use the correct methods.

with Ada.Text_IO;with Ada.Text_IO;package Text_IO renames Ada.Text_IO;package Text_IO renames Ada.Text_IO;ExampleExample

Page 80: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 80ASEET

Questions?Questions?

Ada95

Page 81: Afternoon Ada 95 Intro - 1 ASEET Introduction to Ada95 ANSI/ISO/IEC-8652:1995 S T S C

Afternoon Ada 95 Intro - 81ASEET

The End!The End!