Pyrrhus Software
Enduring Solutions
Introduction to Ada 95
Joyce L Tokar, PhD
[email protected]
Introduction to Ada
Morning Ada Concepts - 1
Pyrrhus Software
Enduring Solutions
Acknowledgements
• Eugene Binque, Ph. D.
• David A. Cook, Ph. D.
• Leslie (Les) Dupaix
Introduction to Ada
Morning Ada Concepts - 2
Pyrrhus Software
Enduring Solutions
Course Outline
•
•
•
•
•
•
•
•
Introduction to Ada
History and Overview
Large Scale View of Ada
Conventional Features
Packages and Overloading
Object Oriented Features
Real-Time Features
Systems Features
Tools and Environments
Morning Ada Concepts - 3
Pyrrhus Software
Enduring Solutions
Morning Session
• This part of the course will present the
basic structure of the Ada programming
language.
• It will cover data abstraction, information
hiding, localization, and modularity. The
features that enable you to build reliable
software systems from the building
blocks in the language.
Introduction to Ada
Morning Ada Concepts - 4
Pyrrhus Software
Enduring 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.
Introduction to Ada
Morning Ada Concepts - 5
Pyrrhus Software
Enduring Solutions
History and Overview
• High-level programming language initially
developed to address the software crisis as
recognized as early as 1974 by the US
Department of Defense.
• Evolution to continue to incorporate
improvements in software engineering and
programming.
• Large scale and critical programs that require
high-reliability.
Introduction to Ada
Morning Ada Concepts - 6
Pyrrhus Software
Enduring Solutions
Mission of Ada 95
•
•
•
•
Revise Ada based on User Need
Effect a Smooth Transition
Correct Minor Flaws in Ada 83
Improve the Facilities for Real-Time
Programming
• Introduce Enhancements to Enter Other
Programming Domains
Introduction to Ada
Morning Ada Concepts - 7
Pyrrhus Software
Enduring Solutions
Ada Revision Process
•
•
•
•
•
•
•
User Requirements – Oct 88
Requirements – Dec 90
Mapping – Dec 94
ISO Approval – Feb 95
ANSI/FIPS Approval – Feb 95
Technical Corrigenda – Jul 2000
Addendums – 2005+
Introduction to Ada
Morning Ada Concepts - 8
Pyrrhus Software
Enduring Solutions
Structure of Ada 95
CORE
Systems Programming
ANNEXES
Systems Programming
Real-Time Systems
Real-Time Features
Distributed Systems
OOP Features
Information Systems
Interfaces
Numerics
Safety & Security
Introduction to Ada
Morning Ada Concepts - 9
Pyrrhus Software
Enduring Solutions
Goals of Ada
•
•
•
•
•
•
•
•
•
Introduction to Ada
Readability
Strong Typing
Programming in the Large
Exception Handling
Data Abstraction
Object Oriented Programming
Tasking
Generic Units
Interfacing
Morning Ada Concepts - 10
Pyrrhus Software
Enduring Solutions
Software Engineering
• Reuse of software components.
• Established methods of developing
software.
Introduction to Ada
Morning Ada Concepts - 11
Pyrrhus Software
Enduring Solutions
What distinguishes Ada?
Ada is Reliable ….
• Strong typing leads to the early detection of
errors.
• Integrity is maintained across compilation unit
boundaries.
• All identifiers are declared before they are
used.
• Clearly identified links to other program
modules through the use of context clauses.
• Program libraries to encapsulate program
units for reuse.
Introduction to Ada
Morning Ada Concepts - 12
Pyrrhus Software
Enduring Solutions
Strong Typing
• Each object has a clearly defined set of
values.
• Prevents confusion between logically
distinct concepts.
• Thus, many errors are detected by the
compiler.
Introduction to Ada
Morning Ada Concepts - 13
Pyrrhus Software
Enduring Solutions
Ada Library
• All interfaces between modules can be
checked during the compilation phase.
• Often this capability is left to the
debugger in many other languages.
• Early detection by the Ada compiler
increases the development of reliable
code and decreases the cost of
development.
Introduction to Ada
Morning Ada Concepts - 14
Pyrrhus Software
Enduring Solutions
Strong Typing
procedure TESTER is
type APPLES is range 0 .. 100; -- an integer type
type ORANGES is range 0 .. 100; --ditto
A : APPLES := 100;
- - initialized during declaration
B : APPLES;
O : ORANGES;
begin
B := A;
O := A;
- - ERROR, incompatible types
end TESTER;
--> A and O are not compatible.
Ada enforces “name equivalence” not
structural equivalence.
Introduction to Ada
Morning Ada Concepts - 15
Pyrrhus Software
Enduring Solutions
Overall Program Structure
• Library of program components
• Program is composed of library units
• Services are available in packages
stored in a libraries.
Introduction to Ada
Morning Ada Concepts - 16
Pyrrhus Software
Enduring Solutions
The Library Model
Subunit
The subunit is
developed with calls to
library units
Compiler
The compiler
compiles the
subunit
checking all
interfaces
with library
units.
Resolves
ambiguities.
Places the
subunit into
the library.
The library
maintains a record
of all compiled
subunits and their
interfaces.
Introduction to Ada
Morning Ada Concepts - 17
Pyrrhus Software
Enduring Solutions
Overall Program Structure
with Sqrt;
with Simple_IO; -- context clause
procedure Print_Square_Root is
begin
Simple_IO.Put( Sqrt(2.5) ); -- library access
end Print_Square_Root;
•
•
Context clause -- used to introduce packages and
program units into the current compilation.
Library Access -- the compiler will check to make
sure that the procedure call signature (number of
parameters, order & type) is correct.
Introduction to Ada
Morning Ada Concepts - 18
Pyrrhus Software
Enduring Solutions
Basics of Ada
• Once you understand the strong typing
and library features of Ada, the basics of
the language resembles many other
high-level languages.
• Once we have covered the basic
features of the language, we will have
the building blocks to construct many
highly reliable systems.
Introduction to Ada
Morning Ada Concepts - 19
Pyrrhus Software
Enduring Solutions
Overall Program Structure
•
•
•
•
•
•
•
•
•
Syntax and Lexical Forms
Scalar Types
Composite Types
Data Declarations
Expressions
Statements
Control Statements
Subprograms
Input/Output
Introduction to Ada
Morning Ada Concepts - 20
Pyrrhus Software
Enduring Solutions
Syntax and Lexical Forms
Lexical Elements:
the alphabet A - Z
the digits 0 - 9
special characters “ # & ‘ ( ) * + , - / : ; < = > _ |
the space character
identifier ::= identifier_letter {[underline] letter_or_digit}
Age : Integer := 21;
Pi : constant Real := 3.14159_26536;
Nineteen_Hundred : Year := 19E2;
CPI : Real := 2#101.11#; -- equals 5.75 base 10
Still_Thirty : Integer := 16#30#; -- equals 48 base 10
Introduction to Ada
Morning Ada Concepts - 21
Pyrrhus Software
Enduring Solutions
Scalar & Composite Types
• Scalar type objects are single values.
SCALAR TYPES
DISCRETE
INTEGER
REAL
ENUMERATED
FIXED
FLOAT
• Composite objects contain components.
COMPOSITE TYPES
ARRAY
Introduction to Ada
RECORD
TAGGED
PROTECTED
Morning Ada Concepts - 22
Pyrrhus Software
Enduring Solutions
Declarations
procedure Monkey_Test is
type A_String is access String;
type A_String_Array is array (Positive range <>) of A_String;
function "+" (S : String) return A_String is
begin
return new String'(S);
end "+";
Zoo : constant A_String_Array :=
(+"Aardvark", +"Baboon", +"Cougar", +“Monkey",
+"Elephant", +"Ferret", +"Giraffe", +"Horse");
Monkey : A_String := +"Monkey";
Zoo_Monkeys : Boolean := False;
Introduction to Ada
Morning Ada Concepts - 23
Pyrrhus Software
Enduring Solutions
Expressions, Statements,
Control Statements, and I/O
begin -- Monkey_Test
for Animal in Zoo’Range loop
Zoo_Monkeys := Monkey.all = Zoo( Animal ).all;
exit when Zoo_Monkeys;
end loop;
if Zoo_Monkeys then
Put( “There are monkeys in the Zoo” );
end if;
end Monkey_Test;
Introduction to Ada
Morning Ada Concepts - 24
Pyrrhus Software
Enduring Solutions
Program Units
Subprograms
-- Functions and Procedures
-- Main Program
-- Abstract Operations
Tasks
-- Parallel Processing
-- Real-time Programming
-- Interrupt Handling
Packages
-- Encapsulation
-- Information Hiding
-- Abstract Data Types
Generics
-- Templates
Introduction to Ada
Morning Ada Concepts - 25
Pyrrhus Software
Enduring Solutions
Specifications and Bodies
"with” ing the package
Ada subunit
A program
unit or
subunit
Body
Data
Specification
Introduction to Ada
Morning Ada Concepts - 26
Pyrrhus Software
Enduring Solutions
Subprogram Units
Body
Specification
ABSTRACTION
"What" the program unit does
INFORMATION HIDING
"How" the program unit does
what it does
All the user of the program
unit needs to know
The details of implementation
are inaccessible to the user
Introduction to Ada
Morning Ada Concepts - 27
Pyrrhus Software
Enduring Solutions
Ada Subprograms
visible
Specification
hidden
Body
• Procedures
 Perform some action
 Call always appears as a statement.
• Functions
 Returns a value
 Call always appears in an expression.
Introduction to Ada
Morning Ada Concepts - 28
Pyrrhus Software
Enduring Solutions
Parameter Modes
• The direction in which the value associated with the
formal parameter is passed.
• Three modes
 in
 out
 in out
-- Parameter is initialized by the actual parameter;
-- Parameter may only be read
-- Parameter is an uninitialized variable;
-- Parameter may be updated and read
-- parameter is initialized by the actual parameter;
-- it permits both reading and updating of the
-- value of the associated actual parameter.
• Functions may only have in parameters.
• The default parameter mode is in.
Introduction to Ada
Morning Ada Concepts - 29
Pyrrhus Software
Enduring Solutions
Ada Procedures
-- Procedure Specification
procedure SWAP (PRE, POST: in out INTEGER);
-- Procedure Body
procedure SWAP (PRE, POST: in out INTEGER) is
TEMP: INTEGER := PRE;
begin
PRE := POST;
POST := TEMP;
end SWAP;
-- Procedure Calls
SWAP (MY_COUNT, YOUR_COUNT);
SWAP (MY_COUNT, POST => YOUR_COUNT);
SWAP (PRE => MY_COUNT, POST => YOUR_COUNT);
Introduction to Ada
Morning Ada Concepts - 30
Pyrrhus Software
Enduring Solutions
Specification vs. Body
-- Procedure Specification
procedure SWAP (PRE, POST: in out INTEGER);
• Required to allow calling of procedure
SWAP prior to writing the actual body
• The specification allows the compiler to
check the interface for units that call
SWAP
• This is a COMPILABLE unit!
Introduction to Ada
Morning Ada Concepts - 31
Pyrrhus Software
Enduring Solutions
Specification vs. Body
-- Procedure Body
procedure SWAP (PRE, POST: in out INTEGER) is
TEMP: INTEGER := PRE;
begin
PRE := POST;
POST := TEMP;
end SWAP;
• This is required before the compiled unit can actually
run.
• NOTE: if you are not making SWAP a library unit
(i.e. if it is embedded inside another unit) the
separate specification is not required. A body always
implies a specification.
Introduction to Ada
Morning Ada Concepts - 32
Pyrrhus Software
Enduring Solutions
Ada Functions
-- Function Specification
function SQRT (ARG: FLOAT) return FLOAT;
-- Function Body
function SQRT (ARG: FLOAT) return FLOAT is
RESULT: FLOAT;
begin
-- algorithm for computing RESULT goes here
return RESULT;
end SQRT;
-- Function Call
-- (Assumes STANDARD_DEV and VARIANCE are of type FLOAT)
STANDARD_DEV := SQRT (VARIANCE);
Introduction to Ada
Morning Ada Concepts - 33
Ada Packages
Specification
Pyrrhus Software
Enduring Solutions
Body
object
operation
• The PACKAGE is the primary means of “extending” the Ada
language.
• The PACKAGE hides information in the body thereby enforcing
the abstraction represented by the specification.
• Operations (subprograms, functions, etc.) whose specification
appear in the package specification must have their body in the
package body.
• Other units (subprograms, functions, etc. ) as well as other types,
objects, etc. may also appear in the package body. If so, they are
not visible outside of the package body.
Introduction to Ada
Morning Ada Concepts - 34
Ada Packages
Pyrrhus Software
Enduring Solutions
-- Package Specification
package RUBIK is
type CUBE is private;
procedure GET (C : out CUBE);
procedure SOLVE (C : in out CUBE);
procedure DISPLAY (C : in CUBE);
BAD_CUBE : exception;
private
type CUBE is . . . -- also considered “hidden”
end RUBIK;
-- Package Body
package body RUBIK is
-- all bodies of subprograms found in the package spec go here
-- along with any other local declarations that should be
-- kept "hidden“ from the user
procedure GET (C : out CUBE) is . . .
procedure SOLVE (C : in out CUBE) is . . .
procedure DISPLAY (C : in CUBE) is . . .
end RUBIK;
Introduction to Ada
Morning Ada Concepts - 35
Package Usage
Pyrrhus Software
Enduring Solutions
RUBIK
MAIN
CUBE
GET
SOLVE
DISPLAY
with RUBIK;
with Ada.Text_IO;
BAD_CUBE
procedure MAIN is
MY_CUBE : RUBIK.CUBE;
begin
RUBIK.GET(MY_CUBE);
RUBIK.SOLVE(MY_CUBE);
RUBIK.DISPLAY(MY_CUBE);
exception
when RUBIK.BAD_CUBE =>
Ada.Text_IO.PUT_LINE("You've got a bad one");
end MAIN;
Introduction to Ada
Morning Ada Concepts - 36
Direct Visibility
Pyrrhus Software
Enduring Solutions
package MEASURES is
type AREA is private;
type LENGTH is private;
function "+" (LEFT, RIGHT : LENGTH) return LENGTH;
function "*" (LEFT, RIGHT : LENGTH) return AREA;
private
type LENGTH is range 0..100;
type AREA is range 0..10000;
end MEASURES;
-------------------------------------------------------------------------------with MEASURES; use MEASURES; --direct visibility
procedure MEASUREMENT is
SIDE1,SIDE2 : LENGTH;
FIELD : AREA;
begin …...
FIELD := SIDE1 * SIDE2; -- Infix notation of
-- user-defined operation
end MEASUREMENT;
Introduction to Ada
Morning Ada Concepts - 37
Software
Indirect Visibility Pyrrhus
Enduring Solutions
package MEASURES is
type AREA is private;
type LENGTH is private;
function "+" (LEFT, RIGHT : LENGTH) return LENGTH;
function "*" (LEFT, RIGHT : LENGTH) return AREA;
private
type LENGTH is range 0..100;
type AREA is range 0..10000;
end MEASURES;
-------------------------------------------------------------------------------with MEASURES; --NOTE: No “use”clause
procedure MEASUREMENT is
SIDE1,SIDE2 : MEASURES.LENGTH;
FIELD : MEASURES.AREA;
begin
…...
FIELD := MEASURES."+"(SIDE1, SIDE2);
end MEASUREMENT;
Introduction to Ada
Morning Ada Concepts - 38
Pyrrhus Software
Enduring Solutions
Use Type
with MEASURES; -- NOTE: No “use”clause
procedure MEASUREMENT is
use MEASURES.LENGTH; -- direct visibility of the type LENGTH
use MEASURES.AREA; -- direct visibility of the type AREA
SIDE1,SIDE2 : LENGTH;
FIELD : AREA;
begin
…...
FIELD := SIDE1+ SIDE2;
end MEASUREMENT;
Introduction to Ada
Morning Ada Concepts - 39
Pyrrhus Software
Enduring Solutions
“use” considered harmful
use
• Leads to problems during maintenance.
• Makes debugging difficult.
• Pollutes the name space.
Introduction to Ada
Morning Ada Concepts - 40
Pyrrhus Software
Enduring Solutions
“Use” clause considered harmful
package MEASURES is
type AREA is private;
type LENGTH is private;
function Add_Length (LEFT, RIGHT : LENGTH)
return LENGTH;
function Calc_Area (LEFT, RIGHT : LENGTH)
return AREA;
private
type LENGTH is range 0..100;
type AREA is range 0..10000;
end MEASURES;
Introduction to Ada
Morning Ada Concepts - 41
Pyrrhus Software
Enduring Solutions
“Use” considered harmful
with MEASURES; -- NOTE: no “use” clause
procedure MEASUREMENT is
SIDE1, SIDE2 : MEASURES.LENGTH;
FIELD : MEASURES.AREA;
begin
…...
FIELD := MEASURES.Calc_Area (Side1, Side2);
end MEASUREMENT;
Introduction to Ada
Morning Ada Concepts - 42
Pyrrhus Software
Enduring Solutions
Ada Tasks
Specification
entry
entry
Body
• The TASK concept in Ada provides a model of parallelism
which encompasses:
• multicomputers
• multiprocessors
• interleaved execution.
• In Ada, the method of communication between tasks is
known as "rendezvous“.
• Ada "draws up" into the language certain capabilities
previously performed only by the operating system.
Introduction to Ada
Morning Ada Concepts - 43
Pyrrhus Software
Enduring Solutions
Ada Tasks
• Each task is a separately executing unit (with it’s own
stack)
• A task starts running as soon as the parent starts executing
• Once a task starts, it runs independently of the parent
• If desired, a task can communicate with other running units
by passing data. Data is passed via “Entry Points” using
rendezvous (calls)
Introduction to Ada
Morning Ada Concepts - 44
Pyrrhus Software
Enduring Solutions
Task Communication
-- Task Specifications
task TASK_1;
-- no entries
task TASK_2 is
entry PASS_DATA (N : INTEGER);
end TASK_2;
-- Task Bodies
task body TASK_1 is
TASK_2.PASS_DATA(17);
end TASK_1;
-- an entry call
task body TASK_2 is
accept PASS_DATA (N : INTEGER) do
-- statements to be executed during rendezvous
end PASS_DATA;
end TASK_2;
Introduction to Ada
Morning Ada Concepts - 45
Pyrrhus Software
Ada Tasks
Simplest form:
no communication
Tasks always belong to
someone (MAIN)
MAIN can not end until all
dependent tasks end
Execution of T1 and T2
begins here
Introduction to Ada
Enduring Solutions
procedure MAIN is
task T1;
task T2;
task body T1 is
-- local declarations
begin
-- do something
end T1;
task body T2 is
-- local declarations
begin
-- do something
end T2;
begin -- MAIN
null;
end MAIN;
Morning Ada Concepts - 46
Pyrrhus Software
Enduring Solutions
Tasks are Operating System
Independent
OS
TRADITIONAL Model
Of Concurrency
OS
The Ada
Concurrency Model
Introduction to Ada
Morning Ada Concepts - 47
Buffer Manager
task Buffer is
entry Put( X : Item );
entry Get( Z : out Item );
end Buffer;
Introduction to Ada
Pyrrhus Software
Enduring Solutions
task body Buffer is
Full : Boolean := False;
Y : Item;
begin
loop
select
when not Full =>
accept Put( X : Item ) do
Y := X; Full := True;
end;
or
when Full =>
accept Get( Z : out Item ) do
Z := Y; Full := False;
end;
or
terminate;
end select;
end loop;
end Buffer;
Morning Ada Concepts - 48
Pyrrhus Software
Buffer Manager in Use
Buffer
Producer
Put(X)
task body Producer is
X : Item;
begin
loop
-- Produce X
Buffer.Put( X );
end loop;
end Producer;
Introduction to Ada
Enduring Solutions
Consumer
Get(X)
task body Consumer is
Z : Item;
begin
loop
Buffer.Get( Z );
-- Consume Z
end loop;
end Consumer;
Morning Ada Concepts - 49
Pyrrhus Software
Enduring Solutions
Typing
Introduction to Ada
Morning Ada Concepts - 50
Pyrrhus Software
Enduring Solutions
Ada Types
• An Ada type is a template for objects
 a set of values which are meaningful
 a set of operations on the objects (values)
• All objects must be declared and objects of different
types cannot be implicitly mixed in operations
• TYPES are not operated upon directly, objects can
be operated upon. Types are a means of declaring
OBJECTS (instances of the type).
type
object
Introduction to Ada
Morning Ada Concepts - 51
Pyrrhus Software
Enduring Solutions
Classes of Ada Types
Scalar
Composite
Ada
Types
Objects contain components
Access
Objects point to other objects
& subprograms
Private
Objects are abstract
Task
Introduction to Ada
Objects are single values
Objects are parallel processes
Morning Ada Concepts - 52
Pyrrhus Software
Enduring Solutions
Predefined Types
• In Ada, most types SHOULD be defined
by the user.
 Model real-world values
 Matches the “abstraction” being
programmed
 Limits and ranges are detected early
• Nevertheless, there are some
predefined types.
Introduction to Ada
Morning Ada Concepts - 53
Pyrrhus Software
Enduring Solutions
Predefined Types
SCALAR TYPES
DISCRETE
INTEGER
ENUMERATED
REAL
FIXED
Integer
Boolean
Duration
Natural
Character
Decimal
Positive
Wide_Character
FLOAT
Float
Mod
Long_Integer
Short_Integer
Introduction to Ada
Morning Ada Concepts - 54
Pyrrhus Software
Integer Types
Enduring Solutions
An Integer type characterizes a set of whole number
values and a set of operations on whole numbers.
type DEPTH is range -1000 .. 0;
type ROWS is range 1 .. 8;
type LINES is range 0 .. 66;
subtype TERMINAL is LINES range 0 .. 24;
ROW_COUNT : ROWS;
LINE_COUNT : LINES := 1;
CRT
: TERMINAL := 16;
FATHOMS
: constant DEPTH := -100;
Introduction to Ada
Morning Ada Concepts - 55
Pyrrhus Software
Enduring Solutions
Enumeration Types
Enumeration types are defined by enumeration of their values.
type COLOR is (WHITE, RED, YELLOW, GREEN, BLUE);
type LIGHT is (RED, AMBER, GREEN);
type GEAR_POSITION is (UP, DOWN, NEUTRAL);
type SUITS is (CLUBS, DIAMONDS, HEARTS, SPADES);
subtype MAJORS is SUITS range HEARTS..SPADES;
type BOOLEAN is (FALSE, TRUE); -- predefined type
HUE : COLOR;
SHIFT : GEAR_POSITION := GEAR_POSITION'last;
T : constant BOOLEAN := TRUE;
HIGH : MAJORS := CLUBS; -- invalid
Introduction to Ada
Morning Ada Concepts - 56
Pyrrhus Software
Enduring Solutions
Character Type
The predefined type Character is a character type
whose values correspond to the 256 code positions
of Row 00 (also known as Latin-1) of the ISO 10646
Basic Multilingual Plane (BMP).
type ROMAN_DIGIT is ('I', 'V', 'X', 'L', 'C', 'D', 'M');
type VOWELS is ('A', 'E', 'I', 'O', 'U');
subtype FORTRAN_CONVENTION is CHARACTER range 'I' .. 'N';
INDEX : FORTRAN_CONVENTION :='K';
ROMAN_100 : constant ROMAN_DIGIT := 'C';
MY_CHAR : CHARACTER;
Introduction to Ada
Morning Ada Concepts - 57
Pyrrhus Software
Enduring Solutions
Composite Types
• Building block for complex types.
• Combination of any types.
COMPOSITE TYPES
ARRAY
Introduction to Ada
RECORD
TAGGED
PROTECTED
Morning Ada Concepts - 58
Pyrrhus Software
Enduring Solutions
Constrained Arrays
type TABLE is array(INTEGER range 1 .. 5) of FLOAT;
MY_LIST : TABLE := (3.7, 14.2, -6.5, 0.0, 1.0);
1
3.7
2
14.2
3
-6.5
0.0
4
7.3
1.0
5
MY_LIST
MY_LIST (4) := 7.3;
Introduction to Ada
Morning Ada Concepts - 59
Pyrrhus Software
Enduring Solutions
Constrained Arrays
type DAYS is (SUN, MON, TUE, WED, THU, FRI, SAT);
type WEEK_ARRAY is array (DAYS) of BOOLEAN;
MY_WEEK : WEEK_ARRAY := (MON .. FRI => TRUE, others => FALSE);
SUN FALSE
MON TRUE
TUE TRUE
if MY _WEEK (THU) = TRUE then ...
if MY_WEEK (THU) then …
WED TRUE
THU TRUE
FRI TRUE
SAT FALSE
MY_WEEK
Introduction to Ada
Morning Ada Concepts - 60
Pyrrhus Software
Enduring Solutions
Unconstrained Arrays
• Index type and component type bound to array type.
• Index range bound to objects, not type.
• Allows for general purpose subprograms.
• Includes the Ada String type.
type SAMP is array (INTEGER range <>) of FLOAT;
LARGE : SAMP (1 .. 5) := (2.5, 3.4, 1.0, 0.0, 4.4);
SMALL : SAMP (2 .. 4) := (others => 5.0);
1 2.5
2 5.0
2 3.4
3 5.0
3 1.0
4 5.0
4 0.0
5 4.4
SMALL
LARGE
Introduction to Ada
Morning Ada Concepts - 61
Pyrrhus Software
Enduring Solutions
Record Type
type DATE is record
DAY : INTEGER range 1 .. 31;
MONTH : MONTH_TYPE;
YEAR : INTEGER range 1700 .. 2150;
end record;
TODAY : DATE;
DAY
MONTH
DAY
Introduction to Ada
Morning Ada Concepts - 62
Record Types
Pyrrhus Software
Enduring Solutions
Record components may have default initial values
for their components.
type DATE is record
DAY : INTEGER range 1 .. 31 := 15;
MONTH : MONTH_TYPE := January;
YEAR : INTEGER range 1700 .. 2150 := 1968;
end record;
FDJ_BDAY : DATE;
TODAY : DATE := (7, December, 2003); -- an aggregate
FDJ_BDAY.DAY = 15
FDJ_BDY.MONTH = January
FDJ_BDY.YEAR = 1968
if FDJ_BDAY /= (15, December, 1968) then …
Introduction to Ada
Morning Ada Concepts - 63
Pyrrhus Software
Enduring Solutions
Ada Strings
type STRING is array (Positive range <>) of Character; -- predefined type
STR_5 : STRING (1 .. 5);
STR_7 : STRING (1 .. 6) := "SIGAda";
WARNING : constant STRING := "DANGER";
STR_6
S I G A d a
WARNING
D A N G E R
subtype TEN_LONG is STRING(1 .. 10);
FIRST_TEN : TEN_LONG := "Header ";
FIRST_TEN
H e a d e r
Introduction to Ada
Morning Ada Concepts - 64
Pyrrhus Software
Enduring Solutions
Access Types
Also known as “pointers”
type NODE;
type PTR is access NODE;
type NODE is
record
FIELD1 : SOME_TYPE;
FIELD2 : SOME_TYPE;
FIELD3 : PTR;
end record;
TOP : PTR; -- an access object
TOP : PTR := new NODE; -- an allocator
TOP.FIELD3 := new NODE; -- another allocator
Introduction to Ada
Morning Ada Concepts - 65
Pyrrhus Software
Enduring Solutions
Access Types
•
•
•
•
•
•
Introduction to Ada
Pool-specific access types
General access types
Access parameters
Access discriminants
Access to subprograms
Storage pool management
Morning Ada Concepts - 66
Pyrrhus Software
Enduring Solutions
General Access Types
type Int_Ptr is
access all Integer;
IP : Int_Ptr;
type Const_Int_Ptr is
access constant Integer;
CIP : Const_Int_Ptr;
I : aliased Integer;
C : aliased constant Integer := 1815;
J : Integer := 6;
…
IP := I’Access; -- access to a variable
CIP := C’Access; -- access to a constant
IP.all := CIP.all;
CIP.all := I; -- cannot assign to a constant
CIP := I’Access; -- read only access to a variable
IP := J’Access; -- illegal, J is not marked as aliased
Introduction to Ada
Morning Ada Concepts - 67
Pyrrhus Software
Enduring Solutions
Private Types
•
•
•
•
•
Actual type description is "hidden"
The type is primarily known through its operations
Private types are always implemented by packages
Private types protect data from erroneous access
Two types
 Private -- assignment, (in) equality and all explicitly
declared operations
 Limited Private -- assignment and all explicitly declared
operations
Introduction to Ada
Morning Ada Concepts - 68
Private Types
Pyrrhus Software
Enduring Solutions
package PASSWORD_CHECK is
type PASSWORD_TYPE is limited private;
procedure GET_PASSWORD (Value : in out PASSWORD_TYPE);
procedure VERIFY_PASSWORD (Value : in out PASSWORD_TYPE);
private
type PASSWORD_TYPE is STRING(1..20);
end PASSWORD_CHECK;
• Password is “hidden” in that the compiler will enforce
limitations on what you can do with any variable of
type PASSWORD_TYPE.
• If you “with PASSWORD_CHECK” in another unit,
you have access to PASSWORD_TYPE and the two
procedures, but you may NOT perform ANY other
operations on a variable of type PASSWORD_TYPE.
Introduction to Ada
Morning Ada Concepts - 69
Pyrrhus Software
Enduring Solutions
Ada Statements
SEQUENTIAL
:=
null
procedure call
return
declare
CONDITIONAL
if
then
elsif
else
case
ITERATIVE
OTHERS
loop
exit
for
while
raise
goto
Introduction to Ada
TASKING
delay
entry call
abort
accept
select
requeue
then abort
All block statements
are terminated with
an end (end if, … )
Morning Ada Concepts - 70
Pyrrhus Software
If Statements
Enduring Solutions
if TODAY = (29, May, 2004) then
MOMS_YEARS := MOMS_YEARS + 1;
GET (BIRTHDAY_CARD);
end if;
if IS_ODD (NUMBER) then
ODD_TOTAL := ODD_TOTAL + 1;
else
EVEN_TOTAL := EVEN_TOTAL + 1;
end if;
if SCORE >= 90 then GRADE := 'A';
elsif SCORE >= 80 then GRADE := 'B';
elsif SCORE >= 70 then GRADE := 'C';
elsif SCORE >= 60 then GRADE := 'D';
else
GRADE := 'F';
end if;
Introduction to Ada
Morning Ada Concepts - 71
Pyrrhus Software
Case Statements
Enduring Solutions
procedure SWITCH (HEADING : in out DIRECTION) is
begin
case HEADING is
when NORTH => HEADING := SOUTH;
when EAST => HEADING := WEST;
when SOUTH => HEADING := NORTH;
when WEST => HEADING := EAST;
end case;
end SWITCH;
case NUMBER is
when 2
=> DO_SOMETHING;
when 3 | 7 | 8 => DO_SOMETHING_ELSE;
when 9 .. 20 => DO_SOMETHING RADICAL;
when others => PUNT;
end case;
Introduction to Ada
Morning Ada Concepts - 72
Pyrrhus Software
Enduring Solutions
Loop Statements
loop
GET_SAMPLES;
exit when EXHAUSTED;
PROCESS_SAMPLES;
end loop;
for i in 1..5 loop
GET_IT(NUMBER);
MODIFY_IT (NUMBER);
end loop;
while DATA_REMAINS loop
<sequence_of_statements>
end loop;
Introduction to Ada
Morning Ada Concepts - 73
Pyrrhus Software
Enduring Solutions
What makes an Ada loop unique?
• You can only increment or decrement
(no skipping values).
• The Loop Control Variable (LCV) is
implicitly declared inside the loop.
• The LCV disappears when the loop
terminates.
Introduction to Ada
Morning Ada Concepts - 74
Pyrrhus Software
Enduring Solutions
Loop Control Variable
….
COUNTER : Integer := 0;
…
for Counter in 1..100 loop
if My_Array(Counter) = SOME_VALUE then
exit;
end if;
end loop;
Put (Counter); -- Prints out the value of Counter
QUESTION - what is the value of Counter for the Put operation?
Introduction to Ada
Morning Ada Concepts - 75
Pyrrhus Software
Enduring Solutions
Sample Program
-- To exemplify some of the Ada statements, let's look
-- at the implementation of a 'wrap-around’ successor
-- function for type DAYS.
procedure TEST is
type DAYS is (SUN, MON, TUE, WED, THU, FRI, SAT);
TODAY : DAYS;
TOMORROW : DAYS;
-- Object declarations
function WRAP (D : DAYS) return DAYS is . . .
begin
...
TOMORROW := WRAP(TODAY);
...
end TEST;
Introduction to Ada
Morning Ada Concepts - 76
Pyrrhus Software
Enduring Solutions
Sample Program
function WRAP (D : DAYS) return DAYS is
begin
case D is
when SUN => return MON;
when MON => return TUE;
when TUE => return WED;
when WED => return THU;
when THU => return FRI;
when FRI => return SAT;
when SAT => return SUN;
end case;
end WRAP;
Introduction to Ada
Morning Ada Concepts - 77
Pyrrhus Software
Enduring Solutions
Sample Program
function WRAP (D : DAYS ) return DAYS is
begin
return DAYS'SUCC(D);
exception
when CONSTRAINT_ERROR => return DAYS'FIRST;
end WRAP;
Introduction to Ada
Morning Ada Concepts - 78
Pyrrhus Software
Enduring Solutions
Exceptions
Hndling all pssible erros!
There are four errors in this slide!
Introduction to Ada
Morning Ada Concepts - 79
Pyrrhus Software
Enduring Solutions
Exceptions
• Exceptions are a mechanism to allow the programmer to
identify and handle errors within the program without calling
system error routines.
• There are two kinds of exceptions:
 predefined exceptions
• Standard (Constraint, Program, Storage, Tasking )
• IO (Status, Mode, Name, Data, Layout, End, Device,
Use).
 user-defined exceptions
• Allows the designer to define and raise non-standard
exceptions.
Introduction to Ada
Morning Ada Concepts - 80
Pyrrhus Software
Enduring Solutions
Exceptions
• Exception handlers handle the exception.
 You can also name and save an exception
externally.
 An exception can be re-raised and it can be
propagated.
Introduction to Ada
Morning Ada Concepts - 81
Pyrrhus Software
Enduring Solutions
Exception Example
procedure Check_Data is
My_Error : exception;
AGE : Positive;
DATA : string (1..10) := (others => ‘ ‘);
begin
Get_AGE (Age);
Get_DATA (DATA);
if DATA = “David Cook” then
raise My_Error;
end if;
exception
when Constraint_Error => ….
when My_Error => ….
end;
Introduction to Ada
Morning Ada Concepts - 82
Pyrrhus Software
Enduring Solutions
Generics
• Generics define a template or mold for
program units.
Introduction to Ada
Morning Ada Concepts - 83
Pyrrhus Software
Enduring Solutions
Generics
Dictionary Definition:
a. Relating to, or characteristic of, a whole group or
class
b. General
• Defines a template for a general purpose program
units.
• The template must be instantiated prior to use in a
program.
• Strong typing makes generics a necessary language
feature.
Introduction to Ada
Morning Ada Concepts - 84
Pyrrhus Software
Enduring Solutions
Generics
Generics are like high-level macros. We parameterize them at
compile time because we can't pass types or subprograms at
execution time. Parameters to generics can be
Different
Types
types
subprograms
objects
values
Generic Sort
Different
Types
(Ordered)
With a generic, we can pass a type and reuse one general
routine or algorithm or a variety of data types.
Introduction to Ada
Morning Ada Concepts - 85
Pyrrhus Software
Enduring Solutions
Swap Routine
procedure Integer_Swap(Integer_1 : in out Integer;
Integer_2 : in out Integer) is
Temp : Integer := 0;
begin
Temp := Integer_1;
Integer_1 := Integer_2;
Integer_2 := Temp;
end Integer_Swap;
Introduction to Ada
Morning Ada Concepts - 86
Pyrrhus Software
Generic Swap Routine
Enduring Solutions
Generic formal part
spec
body
Introduction to Ada
Generic parameter
generic
type ELEMENT is private;
procedure SWAP(ITEM_1 : in out ELEMENT;
ITEM_2 : in out ELEMENT);
procedure SWAP(ITEM_1 : in out ELEMENT;
ITEM_2 : in out ELEMENT) is
TEMP : ELEMENT;
begin
TEMP := ITEM_1;
ITEM_1 := ITEM_2;
ITEM_2 := TEMP;
end Swap;
Morning Ada Concepts - 87
Pyrrhus Software
Enduring Solutions
Using Generics
with Swap;
procedure Example is
procedure Int_Swap is new Swap(Integer);
procedure Chr_Swap is new Swap(Character);
Num1, Num2 : Integer;
Char1, Char2 : Character;
begin
Num1 := 10;
Num2 := 3;
Int_Swap (Num1, Num2);
Char1 := 'A';
Char2 := 'Z';
Chr_Swap (Char1, Char2);
end Example;
Introduction to Ada
Morning Ada Concepts - 88
Pyrrhus Software
Enduring Solutions
Summary of Morning
•
•
•
•
•
•
•
Introduction to Ada
Subprograms
Packages
Tasks
Types and Objects
Statements
Exception Handlers
Generics
Morning Ada Concepts - 89
Pyrrhus Software
Enduring Solutions
Thank You
Introduction to Ada
Morning Ada Concepts - 90
Descargar

Introduction to Ada - ACM SIGAda Home Page