-A109D 641 T8MANSHOP2 AUG~jlI PROGRAN O0C AmLNTt VA … · -a109d 641 t8manshop2 aug~jli p87(u) ada...
Transcript of -A109D 641 T8MANSHOP2 AUG~jlI PROGRAN O0C AmLNTt VA … · -a109d 641 t8manshop2 aug~jli p87(u) ada...
-A109D 641 T8MANSHOP2 AUG~jlI p87(U) ADA JOINT PROGRAN 1/4
AD119 41 O0C AmLNTt VA 2AU GB
UNCLASSIFIED F/C 12/5 ML
I1.0llB ~~ Il 11 2.
,III25
MICROCOPY RESOLUTION TEST CHART
UNCLASSIFIED FILE COP'E I When Data Enree; FILE COP,IENTAT ION PAGE READ _s__ucTO_ S
BEFORE COMPLETEING FORM%
A D-A 189 641 2. GOVT ACCESSION NO. 3. RECIPIENT'S CATALOG NUMBER
.a TYPE Of RE.PORT jOQ WgF7 ED
Advanced Ada Workshop, August, 19876. PERFORMING ORG. REPORT NUMBER
7. AUTHOR(s) 8. CONTRACT OR GRANT NUMBER(s)Ada Software Engineering Education and Training Team (ASEET)
9. PERFORMING ORGANIZATION AND ADDRESS 10. PROGRAM ELEMENT. PROJECT. TASK
Ada Software Education and Training Team AREA & WORK UNIT NUMBERS
Ada Joint Program Office, 3E114, ThePentagon, Washington, D.C.20301-3081
11. CONTROLLING OFFICE NAME AND ADDRESS 12. REPORT DATEAda Joint Program Office 3 December. 19863E 114, The Pentaaon 13. NUMBER OF dAUESWashington, DC 20101-3081 380
14. MONITORING AGENCY NAME & aODRESS(Ifdifferer, -m ControllingOffice) 15. SECURITY CLASS (otrn,s,eport)
Ada Joint Program Office UNCLASSIFIED
5a. CASSiFICATION DCwNGRADINGSEDULE
N/A
16. DISTRIBUTION STATEMENT (ofrhisReport)
Approved for public release; distribution unlimited.
17. DISTRIBUTION STATEMENT (of the abstractenteredin Block20. If different from Report)
UNCLASSIFIED DTC18. SUPPLEMENTARY NOTES
19. KEYWORDS (Continue on reverse side if necessary and identify by block number)
Ada Programming language, Ada Training, Education, Training, ComputerPrograms, Ada Joint Program Office, AJPO,
20. ABSTRACT (Continue on reverse side if necessary and identify by block number)
\ This document contains prints of slides presented at the Advanced daWorkshop, Monday, 17 August to Friday, 21 August, 1987. 1,
DD Ium, 1473 EOITION OF I NOV 65 IS OBSOLETE
I JAN 73 S/N 0102-LF-014-6601 UNCLASSIFIEDSECURITY CLASSIPITCAION OF THIS PAGE (Whe(nOarafrnre,d)
0 ;1. .p-
Cf ro (LCd0 4
t4 co
(U ti
0 Q
*F-'0qQc
44 r
Lai
i
a, "a~-mc
dc.
Aft.
APPLIED Ada SOFTWARE ENGINEERING
• Basic Problem
-- Projection to the 1990's
--- A Macro Solution
* A Practical Solution
-- Software Engineering
-- Ada
• Software Engineering
-- Goals
-- Principles
* Why Ada ?
-- Features of Ada
-- Software Engineering
Applications
BASIC PROBLEM
Projection to the 1990's
M Kultiprocessors - Networks andParallel Architectures
* Distributed Databases
H fardware Capabilities
* Software Demands
H fardware Costs
Cm)m
LQ C.)
L~LW
DISTRIBUTED DATABASES
*Central Control Over Data
* inisize Effort in Storing Data
" The Ada Package Store-
HARDWARE CAPABILITIES
* ainframe in a Micro
-- Intel 80286, 80386, 80486, ???
-- Motorola 68000, 68010, 68020, 68030, ???
Screen Resolution
-- Desktop Publishing, CAD/CAM
Storage Devices
-- 100+ MB Hard Disks
-- Access Times - 18 mas to 40 ms
* Opens New Fields of Applications
SOFTWARE DEMANDS
New Users with Consumer Relationships
* Non-Technical Arenas
-- Need Guarantees
-- Demand Reliability
Development is the Key
-- Design is Paramount
--- Simplistic Operations; i.e. TV
-- Costs of Errors
-- Other Considerations
Lfl
@0
0
LLI
CO)
In
LLI"
CD c2CA
A MACRO SOLUTION
G Greater Use of Automation
• Higher Levels of Abstraction
R Reuseability
-- Isolate Commonality
-- Create Workable Abstractions
-- Reuseable Parts Library
* Rapid Prototyping
-- Gain Insight
-- Evaluate Design Expectations
-- Compare Design Alternatives
A solution offered by Edward Lieblein
A PRACTICAL SOLUTION
Software Engineering Myths
Anyone Can Be a Software Engineer
* Automated Tools - Software Engineering
Structured Programming = Software Engineering
Structured Analysis - Software Engineering
Code Re-use - Software Engineering
It Will Make Programming Obsolete
* Wl Will Make It Effortless
* Fantastic Productivity Gains
Ada - Software Engineering
= == =- ==n _ -i m i~iAN& anaaem
SOFTWARE ENGINEERING
A PRACTICAL SOLUTION
* What Is It ?
* Why Is It Needed ?
* The State of the Art
• The State of the Practice
Why Nov ?
F4za
00
4-j 4 -J0
U ci
C)I
x C 0UJ ~ D D Zr
U 4-0-C0
0 00
E 0-
(1) 0
-0c0
Z 0 12
00
C-J
U) 0
rIJF F c o E N- 0 0 0 _- -S ._J0 o -_J I i- (I
* * *
.0
.0
0
0 00.
c o
W a-0 --J 0
0
E EC0.a
0 --
z .0Q-Q) o o.4J- U)=
.._
.-U)mm m mnm
zz
C
0 0) E 0 _
Z Z)
o 0o
z Li~J Ci2
aJ 0 -z H-Zr7.L *
0_
00L.L
C))
LU
0 5 H-
U) LL.
Cz 0
D Q) -0 L1
L)U0 * - H
0FH- -0 o D
o 00
_0 0-0 :D
:D C* o:LI) 0
o
0)
Z 0)
44-1
0 0Co U)0 ci(10 -I-
4 -1 --
CLC
oc
4-j~coi
L0 0 ~00 *n
p U
L. -
00
.- , .
U_ )-%*4 (l.
*ox
- JN)
Lf 01
C',
0 a~
__0' 0.
c" E L
:i 4,--.jc f #j#~-~-0
L) 0
-l)j
0E0
0)
00
E4 3
Z 0©o -
00
C 00-Jr-
- '9- - -~- - - ~------ -
E0 -4-1'
0 c 0
U)) a)4- ) C/L0
E0 0o-x 0 04a) Lc)-E
Cl
00
0
0
U) _0
E 0
a) CU) 0-U))
00 0o E~ cEZ a) 0
E w' a) ' 4
o >,L~ 0 0- 00n n )
4--o
CO a_ 0) 01
Z 0 E~
o WU)
0I ) 0XO -c 0 wc- 6E ) E o
0 -c C0)
0 0 c< Q) <o LL
0
00
j Z
0 . u w - cyNs4
0>CL wg 0,CZ 0
WU C/) -1cZWj * *W 0< z Jm
0 LL CL C/
zo o0 C) ui L C,
W //
0) CC.
&--VCL (I
A PRACTICAL SOLUTION
Ada
Ada and Software Engineering
* They Aren't the Same Thing
* Ada Has Unique Features That
Facilitates Software Engineering
You CAN Write Bad Code in Ada
Ada is NOT the Total Answer
USAISEC
0m) 'II 0
V) 0I
CIE Eo
~CD 0/ C0) z 0
Eo 0 w F-_W
- Co > o zZQ
o E 0 0Ow (m 0 =
0 z
I-U)
4-
E
o --
'44- -0
0o 0
4- 0
E0 _ E-4-1 E -oC
o 0 _00
> 0
4- 0
4-j-4-
C) 0) (0- E )UQ) 0 0 0 (0- LLu
SOFTWARE ENGINEERING
* Goals of Software Engineering
* Principles of Software Engineering
LI
LIAJ
ID
co
0
z
zc
0 0 0 -E
4 J
0 N
o o 0 0
(O < 0 u
cn C)Co J - 9 (CfD* * *
(9
C)U-4'
Q-)
a)
0- Q)
Q))
CC
4- x0
L2 E2-4-1
cn ~ -0~ -
0 0--
00
4U1 -4'a
00
14-- aa) a)
00
0 00
Aft
:3U)C)00
4-i U 0
0
V2 00 V
Z 0 cN-- C) _D'N
0y 0 L ) 0 C
NtI 0 0'IuC) - U)
0 0
_
-j
c4Uj 0 0-
n n0
Am,
E-'E
C 4" 1
4-o >, >C,
(00
UCl
0
00 o4- 0 0,
0 co
0 C_ 0" 0
-0 Co0 - C)_ Uc 0
CO - > .DC0 0 Q 0- Z z
FEATURES OF Ada
Supports Large System Development
Supports Structured Programming
* Supports Top-Dovn Development
Supports Strong Data Typing
* Supports Data Abstraction
Supports Information Riding and
Data Encapsulation
Am& ,•.. . |
-co w - -~ - -
z E
Z0~4--Z0
04--j
z•4-- E4jL0 -D
mjn
0- -4-jiC/D 0co
4-j 0- L.
U) 0 '-4-
0 c U)00
00
-4-, 0 0
4-j
U 0 0-4-4, '-- U
C 0 - 0
-~ 0
0 C:00 0 Q
40 4- 4- 00
aof0
. ) ..... ..
04I
0
L. (D
0) W)
o C
-4
0 00D 0
-0 E. J0 L
LO -n a-0
-4-J
0 - 0
-4--, c
u Q))
-4-4-0
4-1.--0 W
0 CC )4_
< 00
0
C0 0 Q0 E)
(1)1
-4-4--0
V))
<4-J4-j
U) U
< CEL0
0 L-%4
4-'4-
0 0C) Li
0 - 0
U) E
0
0 !)
L- 00) 0
0o <DL
0 H-
cn
~0
-QQC
0
-b-I~ -K .--
0
(I))
0 C:
oo 0
SaQ) E Cm04.- L. -4--
C C CL 0o a, a0L
C)
0 . 0
CDC
L)U
W) Q)_
00 09 Q
E ~
zcm 0I
0 U > .. iQ -0 cc no-0 0~ L.
U)3
(n -i.-, U)
E 0a
m E u2
CJD U) ) 0-on cnU <U)
_3 0
-4-,
0-
ii E
0 0 0
0-E
U) _I
Q).L
0 G U)V ___l
N-)-->,irni -
< U)
0 0O
'-4-- O -.-
25 o (1)-
-o U) D -
co
0 c-
o ._C _
-U _00 -o©U)Q 00 0- ,,
000 _~c
< E -0o* % .-..
-~~~~ ....-.- - _ _ _ _o
z Lz L
00
LUL
z D
LLU
0 0 NO0
U4-00
0_
0 0Wz>
00Ju
U))
0n C:0
00<
0 0
-4-4--0
Q 00C)_
o) 00 00~ U U
Q) --- d4--
E 0 E 0
C ") 0 ) v u -C- 0C V : -0-
2p a-00
< E C
MAJOR FEATURES OF Ada
* Packages * Tasks
* Strong Typing * Exceptions
* Typing Structures * Generics
* Data Abstraction
PACKAGES
* Definition
* Components of a Package
-- Specification
-- Body
*Goals and Principles of Software
Engineering Supported
C
CI
<04
]r"
-- 0
o 0
+ _4-,0o _ +,i
._. -y _ L__ ___
< 0
0Aft
5 . - 0 ,._H.,.'
K) -t: -F- -' '
-K --- 4
.. . ... . . ... .0 Ir ) 0.. .... ..
--- U
0 - ___--
-~ F4~J
0 I
iiItt.~J.~' I,
U0 0
~0C/D r -~ r~-~f ~ L.. i
cr)~20o 0
0 -0L. ~f)0 0
U
(-)o .~0 V
0 ~-- 0 -'-'
Co0 -~-~ 0 '4-
Oo rn0 ~- >~0
- Io~ w ~II
* * * 7Jlit
Ld
p ~LLJ<Z
CL LLLJ*-U
CLD
roo-jo<
... Q ) 0 0
OIJ 0 cn,0o0 0
0 W
Z' C/)Q0 o) a 0
0-0LLLJ (/
A A
IIr
0 :0 J.0:
0 0 0
CY 00~00
0 0(D
a3 - 00000000
0 L0o L_ 0 0 00
E
4-)o co t 0-
- Q c U ) 0
Q)00 :>o) - 4~-J _) - t -c
- 0 u0j ' 0: j
0i C) c )Q)~ E c L 0
-IE1I 0 Q r-, )>0nr. Q) Q) )
C)Eu : :
N U)
4-jJ 0 -0
.+--c-~ 0
o-- -< ::DL O
STRONG TYPING
R aw Materials for Software Engineering
*Effects of Strong Typing
*Goals and Principles of SoftwareEngineering Supported
C CL
L- 0)C
0) 0Cf)00
Z E_0 0
C lC-- z
U) LU
0* zEn xC) 0 z
Q)U
cfU)
00
CJ))EU
Q)l4-ao
0 U0
Q) 4
E 0)
CDDC3 CloCC00
-4 -
))
CC
zo-J
C00
44J
cn U)
Q)
0N-
CL
0 c0
D 4J
4o 0
~0
00C) 0
4-1-U)~ 0 0)
__Q C) %- D
Z 0 0 0.2 ) -4- E4-0
o 0
0-L n
- -E -0
Ox
0
o -Y) +
0 - o *- (1 ,aoL- z L
C E 0 a 0 C: CLO
-I- LLJ IUZ
U)~ E Cal J H- L
0- _j0 -- 0 I
0a) GOL cH- L z
a, -1o- 1<0u ~0
TYPING STRUCTURES
* Discrete Data Types
-- Enumeration
-- Integer
Real Data Types
-- Fixed point ( Absolute Error )
-- Floating Point ( Relative Error )
Composite Types
-- Arrays ( Homogeneous )
-- Records ( Heterogeneous )
Dynamic Types
-- Access Types
Abstract Data Types
-- Private
-- Limited Private
Q-
Q)l
00
> I
0 4- -
~0 U)
~0-
E )U L 0U
:D- Q00 C
c -4--) 0 C)U
LIE0-c E<I ~I 1 E
C,-) 0 *>*
00 000 1
> 00
0) 104% . ' I I
Q0 L.
0 ~ : <cLJJ WW
0 LL]LU
L ) -c0 )Lu a
1(f) a)U 0(
Vl)
< L- 0
0 0- 0 <D-CL
WU zI2D
-4-) UJ L-4-j mm i
Q ) LJ LI W V
0D)0
0-4-- Q-LQm _0
C: 0)0 -)C
L.Lj C) CLiD W1 1c0-4j I DLJ
0 4-j
N0 E0 .0
0 a) -;-0 0 0
4-Q 0 N -4-j E
0 0 0 0d
4-j0. 0.)
-0~
X *
a) LUC0) -a
U)i W Of
lID
.. .. ....
00_ 0
.. ~,0
cn Io- 0CD CD1
.- CCD
0 CD
40 _ E0
ocEL 0 -4-'L
*-D L z ol uJ
L. Ld z0 0 () DI LL
Of.M w 0 0LU w -
III L()U
LL -r "R.
(0 -
h~F -CC-Q4
F- a c
o) o 0
CI) 0_ O- S.
0 :D
-V)cz) C)
-0 0 c
Z)0 0
oV)
w m m
bJ= J
0L j z
>->
0< -
0~ ~ ~ 00 :DC
Ql) L-
(..)< 0J 9-I- N0 V) C) Glo 0 0L
0 aJ0 C\ () .0 II 0Ld Mc- rv- cu y Or . L).. -
SV) XLLJJJQ I L.J )->- - zo-LL D<.F~. zOZH-
>. 0< <
a CL a- D- EZLO <<05
45 -61-1 ' 41-.U)
DATA ABSTRACTION
* Definition
* Goals and Principles of SoftwareEngineering Supported
* Baskin-Robbins Ice Cream Example
0
0 4-jI
*F 0
0--
00
0 0:
00>
E E 4-a
E(I) Q0 () 0
00C,) E)0
N- >0 > 0 0u Q))
-JJ WU n
C C
E -_0
EE
-j- _ -
a_
Aft,
Ld
DLLU LLU
0 Z ZC) L
: D 0- :D
00L.L>
m () z Q)
cjj00 _0
0. c 0C))
-Y
00
-C
LUI:2
(1)2;
U J D-0IN :
zL z
LLJD LU
OLO00
4- C)>- 1 U)L 4-
nyV 0-
* dh
LujLuJ mm
-z
LI)Iw X LLJD
UJ ) m 0 0*- 0::
uLu
Lu m00LL IDz D L
ma ) D -L, DUc) 0 Uc ot
Db~ >~*<oc
-a-
(I
=)LLJ
LLJ2L
D4- 0
Lii
V) y-V Li
M) Z
0 ~ - 0>-0
o CLCC0. 0
- ----- ------ -- --
a))-C
w~~ 0zbD
LLii
cr-n 0 0
III a 0-zL L
(-) -mDA*~ .. 0 LJXa)~0 L >
w: LIJ Z V)v n -. c 0 S
~0
0 c
LLL.
~mLLJ W:DLLJcM
m zDD zo Z
> L r
CL LLC
-LL LLJ
V) CxI. V*r Li.Jw
ED V Li L.m z L
-0 0-00D(D Z (L
a CL- 0C cC
>. >,
.4; m
-I-,I
0L6io
4)LL
Lii mOL, .. 0 I:
0 0
.VI J
0 X
U LL CLZw W n 0
TASKS
*Def inition
*Goals and Principles of Software
Engineering Supported
Example
0
-Q) 00-44-j
-0 0
-cn0 4-j -
0
CI)) 0Q)-4-1
C)UE4> Q
EU) U) 00~- -4-7Uc >N 00
CL CLH-cC
00
00 z0 C40
U) 0) L
0L
z- Z o~ 0
flD Lz 2 LU _
LL0 _0~ 0~
Z )V-00 LI C
0 C DLZO 0
LUo~2> 0 C :
) L.00G *v
0L_ (D
0* z
A-w
00
00
0 00 -:;
0I E : (9C- LL -L
Y- 03= (z >,) 0oz :)- -
01 z :3 :D:: -0 -- ,< 0. sr0i Lj- . LC) 0 C, -- 0- ~<ZO
Q ~ c 0
EXCEPTIONS
* Definition
* Goals and Principles of Software
Engineering Supported
Types of Exceptions in Ada
-- Pre-defined Exceptions
-- User-defined Exceptions
* Example
00c00
U) 0
_0 C
0 Q0%+
0 Q) 0
-0 Q)Q
U))
U)_
E 0E
U) Q0 0
0 00 U)
4-1 Q) Q)
%4-->Co 00 --
Lii 00 Q) 4* * * *
0:U0
0 U0
0 U 0
0~ 0Q
00)Cf) c -z 0 0-Co
~CI
0 0
C0 0- 01 4N-4--
C).N -aD-' 0 1'
0 Q) C) U CL 00) 000 C- E
'4- 00QCD L 0
O c (n
0-O 0 C CD - G n ~(n Q 0
C) V) 0 -
-C-
E o
cn~c cn
~) 0 0 0
0
E~-C
Am.-
AD-AL89 641 AUIyhi
~C U 8RAAWOXS 98A 7(l 9U) ADA JOINT PROGRAM 2/4
IJHCLASSIFIED F/G 12/5 ML
I- ~ 2.2
t-
-11 I 2 -0
II11 - III
i.25 1., 1.6
MICROCOP Y PSOLUIiON 1IS, CHAO
iR
CL
4) 4)
0
C o3:
r' CILc 0 0
c) *LJ3J Z: D0L
C) al~ m0E-CLCC1
0 (D
*0*L 7- L 0
w Euj
C)
0~0c L
W
GENERICS
* Definition
* Goals and Principles of Software
Engineering Supported
* Example of Generic Unit Use
In li III I I AND.ii
I-
00
83 L
a4-J
CC
C-7J EI_y -- -4 - - - - - -) 0 .
U a-E L
-I-,_ _ ~ I
I,!C <--''
C-)-
C!)>
0) -0 -
Z Q)
N- Q)
QN U
ry v)
0Am0
LUIWI
o LUwcn 0 :0-z LU0L
Cf2 LU0
Cf) 0
<) CC 0ho'
0 L0 CL: U -
F- LUz I- L
0 I-
V C
-j M
LUd0H
Z
- :3-4-
LLLUo L
U)I ) L
a) CL a
>% LUJ LLJHHi
0 ~~ ~ 0L< <U 1
L. L 0ULU
-Auk 3 ) - _ H f
Ld
LLc0 <
CL <HO
U))
a- Ld<H
< Z.-: z
W) Ll Lj C.C3 LZJ C)
00) ~j C- *%10-) C) D C
C. 00LL
-0 . .- V- L< <
-~~~~ ~ - ------ ---------- - - - I . *1~
SUMMARY
* Basic Problem
-- Projection to the 1990's
-- A Macro Solution
A A Practical Solution
-- Software Engineering
-- Ada
* Software Engineering
-- Goals
-- Principles
• Why Ada ?
-- Features of Ada
-- Software Engineering
Applications
z
C4 z ZZ LLJ M
<~ 0
C) ~DQOL < ZWV
Lz 2Oo jry F OUJ LHD x * *L * * *
Q<
Uo <0d M
U) MQL :7jZ V<k
Wn:D ZI X0 ZV) CLOOE
*) *- 0 *- * *2zEL
0 0z
U) V)H-- E_4U
U) 04 z Z lm 0 0 z
C) __JO Q Z<Q V
E- t < 0 LL < C)L
Cl))ZZ 0
< MLz ZZW
C12 ~ D.OjN MOZZO< Ofu-zOf:D O 0 - -I LL < L)DLQ< * LL * *
0<
LUJ
HLL <~Z o <Q< b**
zz
0 o zo OWZP= P= Ld b
QL < *
Ada Generics
Part of the
Advanced Ada Workshop
Sponsored by theAda Software Engineering Education & Training Team
(ASEET)
John BaileySoftware Metrics, Inc.
703-533-8300Jbailey at Ada20
18 August 198?
Outline
1. RationaleAre generics really necessary in Ada?What can they do?
2. Syntax and SemanticsGeneric parametersInstantiationCompared with other Ada units
3. ExamplesSee how simple they can be.See how useful they can be.See how complicated they can be.
4. LimitationsSome generalization is not easy.Some generalization Is not possible.
5. Advanced UsageRetrofitting genericsGeneralization Judgement calls
. . ... .......... ... .. .. . - -- -- ,.., ,. . lkb ,m m m nl I
1. Rationale
Are generics really necessary?
Ada language goals:Encapsulation of processing desiredEncapsulation of resources (objects) desiredUser-defined types desiredStrong, static type checking desiredUnnecessary language features not desiredReusability desired
Other languages answer some of these goals, but not all.
FortranEncapsulation of processing supportedEncapsulation of resources (mostly)No user-defined typesNo static type checkingI/O routines part of language definitionSome reusability support
PascalEncapsulation of processing supportedNo encapsulation of resourcesUser-defined typesStrong, static type checking (with loopholes)I/O routines part of language definitionNo reusability support
SmalltalkEncapsulation of processing supportedEncapsulation of resources supportedUser-defined types supportedNo static type checkingOnly primitive I/O language-definedExcellent reusability support
Generics Are Solution
Some of the above goals appear to be in conflict:
Reusability vs. Strong static type checking -- ?
type UserType is new Integer;procedure Increment (X : in out UserType) Isbegin
X:= X + 1;end Increment;
Cannot reuse Increment anywhere else.
* Strong checking vs. Minimal language -- ?
type User_Type is new Integer;X: UserType;I : Integer;Put (X); - for strong checking, thesePut (I); - must be distinct "Put's"
Pascal solves this with "magic" I/O procedures- extended language
Write (X);Write (I);Write (X, I);Write ('The answer is ', X,' or', I);
Smalltalk provides primitive I/O with each new typeMight not be wanted.Does not provide static checkingThis allows great flexibility but can lead to
runtime errors that could have beenavoided by compilation-time checking
The Case for Generics
Ada generics allow excellent compromise
Minimal additional complexity
Encapsulation of processingGeneric subprograms
Encapsulation of resources (objects)Generic packages
User-defined types desiredStrong, static type checking desired
Unnecessary language features avoidedI/O not part of language (rather, partof the standard environment)
Reusability supportedReasonable flexibilityCapability to separate essential detail
of an algorithm or object fromproblem-specific detail
(Hint: that last point Is the essence of generic programming)
ink.. •••m ~ iH•ii H H•
I - ... . -. I
What can Generics Do?
Consider the rationale for programming anything:
A programmed solution:Generalizes over several occurrencesAppropriate if similar processing,
but with varying values
Typical programs contain:
* Conceptual "chunks" related to the generalproblem class:AlgorithmsObjects or classes of objects
* Details about the specific problemSpecific typesSpecific routines, such as error recoverySpecific data flow designs
- At run time, a specific case is handledValues specific to a given run are usedSame program is "reused" with next set
of values
Likewise, generic programming uses:
* Conceptual chunks, object classes
* Problem-specifics
" Run-time specifics
Traditional Programming - Diagram
Algorithms, Objects, Resources
- Intertwined with - -
Problem-specific declarations
package Useful-Object is
type Specific_Type is (Something_or_other);
procedure DoSomething (To: Specific_Type);
function StatusOf (AnObjectOf : Specific-Type)return PredefinedTypeerhaps;
end UsefulObject;
Generic Programming - Diagram
application-domain application-domainalgorithms object classes
problem-specific declarations
problem-specific processing
Instantlations of the application-domainchunks (above the dashed line)
generic
type Formal_Type is private;
package General-Object is
procedure DoSomething (To: FormalType);
function Status-Of (AnObjectOf : Formal-Type)return PredefinedTypePerhaps;
end GeneralObject;
type Specific-Type is (Somethingor other);
package Useful-Object Is newGeneral-Object (SpecificType);
Another Quick Example
Frequently, the following occurs in Ada programs:
package GlobalTypes istype Useful Is (This, That, TheOther);
end Global Types;
with GlobalTypes;package Service is
procedure Operation(On : Global_Types.Useful);
end Service;
with GlobalTypes;with Service;procedure User is
MyObject : GlobalTypes.Useful;begin
Service.Operation (MyObject);end User;
Cannot separately use Service without also usingGlobal-Types due to visibility requirements.
Alternative, Equivalent Program
package Global_Types istype Useful is (Whatever);
end GlobalTypes;
- no context clausegeneric
type Formal is private;package GeneralService is
procedure Operation (On : Formal);end GeneralService;
with Service;with Global_Types;procedure User Is
MyObject : GlobalTypes.Useful;package Service Is new
GeneralService (GlobalTypes. Useful);begin
Service.Operation (MyObject);end User;
Now, GeneralService can be reused withoutGlobal_Types.
Just as a program becomes a specific case for agiven run, a generic program is InstantiatedInto a specific case for a given program.
. . .. n (k~~~~m ,mmw mmmm m •m
Another Reason Generics are Unavoidable
With only predefined types, reusability is simplified:
function Math Operation (X : Real) return Real;
If users only have type Real for floating point,the above function Is always usable
However:
Ada allows user-defined types, such as:
type LowPrecision is digits 3;type HighPrecision Is digits 7;
And, Ada requires strong static type checking, soIf Math-Operation were needed for both ofthe above types, two functions would be needed:
function MathOperation (X : LowPrecision)return LowPrecision;
function MathOperation (X : High_Precision)return HighPrecision;
Generics solve this problem:
generictype Real Is digits o;
function MathOperation (X : Real) return Real;
Analogy with Programming
Typical programming:
A programmed solution can be written once and "used'several times. The following motivate thecreation of a programmed solution:
Reusability:Similar processing will be required repeatedly.
Reliability:Testing and verification can be performedto help ensure all runs will be correct.
Readability:By allowing variables to stand for specificvalues during run time, the programcan be understood in the abstract.
Maintainability:Making a change in the program will applyto all usages.
- -| II I - . ".
Generic Programming:
All the same arguments can be applied to genericprogramming.
Reusability:Similar program components neededrepeatedly, but different enough topreclude run time parameterization.
Reliability:A properly tested generic need not beretested each time it Is used.
Readability:By supressing problem-specific detailthe higher-level concept can be understood.
Maintainability:By helping to avoid repetition, the (hopefullysingle) location where a change Is requiredIs easier to determine.
Simplified View
Just as types are templates for describing objects,
Generics are merely templates for other program units.
Generic packages
Generic subprogramsGeneric proceduresGeneric functions
There are no generic tasks- a task Is already an object of a type.- a generic package can contain a task
A generic (template) is instantiated by adeclaration just as an object Is an "instance"of a type (template).
This Instantlation Is accomplished by the compiler,and not (necessarily) at run time.
The effect of Ada generics can be obtained througheditor-like substitution (but this is not thesmartest Implementation of them)
Sometimes likened to assembly language Macros.
........ . 1 L -*~A . ., m m ,l m
Simple Examples
If you can write an Ada package, procedure, or function(you can, can't you?)then you can write an Ada generic:
procedure Easy isbegin
Textlo.PutLine ("pie");end Easy;
-- a call to Easy:Easy;
Generic version:
genericprocedure Easyiisbegin
Textlo.PutLine ("pie");end Easy;
-- first an Instantlation:procedure EasyInstance Is new Easy;
- then a call:EasyInstance:
Note the need to Instantiate first, then treat as a
regular procedure.
The above generic is a trivial case with no parameters.
It's possible (but not too likely) that such a simplegeneric might be useful.
....... .... ... . .. dill,,, m, m n mnnm Ask.
The preceeding example must have been in the scopeof package Textlo.
Or, it could have been a library unit with its owncontext clause:
with Textlo;genericprocedure Easy isbegin
Text lo.Put Line ("pie");end Easy;
Generics are one of the possible library units.
Recalling the Ada grammar:
Library_Unit ::=
subprogramdeclaration
packagedeclaration
genericdeclaration
generic_instantlation
subprogram-body
Note that a generic instantlation can also be a libraryunit.
Given the foregoing, the following two lines alsoform a library unit:
with Easy;procedure Easy_instance is new Easy;
And a user could be:
with EasyInstance;procedure User Isbegin
Easy-Instance;end User;
Resulting in "pie" being printed.
These trivial cases should Illustrate the hiddensimplicity In the declaration and use ofAda generics.
More Useful Example
Normally, one or more parameters would be usedto allow a variety of Instances to be declared.
genericPrompt : String := "A>";
procedure IssuePrompt;
with Text Io;procedure IssuePrompt isbegin
Textlo.Put (Prompt);end IssuePrompt;
Note, the context clause could have preceeded thespec but It isn't needed until the body.
Note that the separate spec and body is Required
with generic subprograms, unlike regular subprograms.
The following Is Not allowed:
with Textlo;generic
Prompt : String := "A>";procedure IssuePrompt isbegin
Textlo.Put (Prompt);end IssuePrompt;
Instantiations
The above could be instantiated with the following:
with IssuePrompt;with Textlo;function UserReply return String Is
procedure Prompt is newIssuePrompt ("What is your wish? ");
Buffer : String (1..80);Length: Natural;
beginPrompt;Textlo.GetLine (Buffer, Length);return Buffer (1 ..Length);
end User-Reply;
with IssuePrompt;with Textlo;function UserReply (To_Question: String := "")
return String Isprocedure Prompt is new
IssuePrompt (To_Question);Buffer : String (1..80);Length: Natural;
beginPrompt;Textlo.GetLine (Buffer, Length);return Buffer (1..Length);
end User-Reply;
Continued...
Respl : constant String := User-Reply; -what's wrong?
Resp2 : constant String := User-Reply ("Why? ");
Resp3 : constant String := User-Reply;
What Is your wish?
Why?
A>
Another Example
Generic formal type parameter (any floating point type)followed by an object parameter of that type:
generictype Real is digits o;Max : Real := Real'Last;
procedure Useless;
procedure Useless IsLocal : Real := Max / 2.0;
beginif RearLast > Max then
Local := Real'Last / 2.0;end if;
end Useless;
with Useless;procedure UselessUser Is
type Coarse Is digits 3;procedure Zip Is new Useless
(Real => Coarse,Max => 10.0);
procedure Zap Is new Useless (Coarse);procedure Zot Is new Useless (Float, -1.0);
beginZip;
end UselessUser;
Object Parameters - Detail
As with subprogram parameters, generic formalparameters can have modes:
Mode in is the default.
genericObjl : Integer;ObJ2 : in Integer;
procedure Testing;
procedure Testing Isbegin
Objil := Obj2; - no!end Testing;
In Parameters
Mode In parameters act as constants.
Mode in parameters are passed values (as with Inparameters of subprograms).
with Testing;procedure Test is
X, Y : Integer := 29;procedure Fee Is new Testing (3 + X, 7);procedure Fie Is new Testing (X, Y);
beginFee;
end Test;
Mode in parameters are given values as in assignment(unlike subprogram in parameters - see later).
with Testing;procedure Test is
X : Integer; -- unitializedprocedure Bomb is new Testing (X, X);
beginBomb; - erroneous
end Test;
Default Evaluation
Defaults are evaluated at time of Instantlation(Not at time of elaboration of generic)
package DeclarationShell is
function Num return Integer;
genericVal : Integer := Num;
procedure Demo;
end DeclarationShell;
package body DeclarationShell is
Local : Integer := 0;
function Num return Integer isbegin
Local := Local + 1;return Local;
end Num;
procedure Demo is separate;
end DeclarationShell;
with Textlo;separate (DeclarationShell)procedure Demo Isbegin
Textlo.PutLine (Integer'lmage (Val));end Demo;
I f a i i il l I II II I I I
So,...
with DeclarationShell;procedure Show is
procedure Demo Isnew DeclarationShel.Demo;
procedure Demol isnew DeclarationShell.Demo;
beginDemo;Demol;
end Show;
output:
12
Not:
1
1
Mode in out
Mode In out parameters must be passed variables, notvalues (same as In out subprogram parameters)
Formal objects of mode in out are aliases for theiractual counterparts.
Can be confusing - and Is usually not recommended.
The evaluation of the variable represented by a namesupplied as the actual parameter to an in outgeneric formal object parameter occurs once
Therefore, If some expression In the name evaluationchanges after the Instantlation, no change Is madeto the object represented by the formal name.
Aft.m mmimllli
Test your knowledge!
declare
Y : array (1..5) of Character := "kitty";
Index : Integer := 1;
genericX : In out Character;
procedure Gen;
procedure Gen isbegin
Index := 5;X := 'W';Put (String (Y));
end;
procedure P is new Gen (Y (Index));
beginP;
end;
What would happen If the object passed dependedon the value of a discriminant?
f.L., ,=.=
Is this Reasonable?
declaretype Furniture is (Bed, Couch, Table);type Style (F : Furniture := Bed) Is record
case F iswhen Bed =>
FourPoster: Boolean;when Couch =>
Convertible : Boolean;when Table =>
Legs : Integer;end case;
end record;S : Style;generic
X : in out Boolean;procedure Gen;
procedure Gen Isbegin
S := (Table, 4);- what Is the value of X ??
end;
procedure P Is new Gen (S.FourPoster);
beginP;
end;
Would the above be allowed?
Other points
Mode out Is not available.What would that mean, anyway?
Formal objects are not static, so they can't be usedin the generic in case alternatives, type ranges,floating point precisions, etc.
declaregeneric
X : Integer;procedure Gen (Val : Integer);
procedure Gen (Val : Integer) Isbegin
case Val iswhen X =>
when others =>
end case;end Gen;
procedure P is new Gen (X => 5);begin
P (Val => 8);end;
You guessed It, this Is Illegal, too!
Parametric Confusion
When the subprograms have parameters, the syntaxcan be confusing.
Generic formals preceed specification but parameterlist follows Instantlation.
Subsequent parameters to Instance also follow,but name is instance name now not generic name.
So, the text never quite matches up, as withsubprograms!
declaregeneric
GenFormal : Integer;procedure G (ProcFormal : Boolean);
procedure G (ProcFormal : Boolean) isbegin
Put (Gen_Formal);Put (ProcFormal);
end G;
procedure P Is new G (Gen-Formal => 3);begin
P (ProcFormal => False);end;
Enough on objects... Type Parameters!
The real power of generics is revealed throughthe use of type (and subprogram - later) parameters
Type Parameters
type T is digits <>; -- any floating point type
type T is delta <>; - any fixed point type
type T is range <>; -- any Integer type
type T is (<>); -- any discrete type, which-- includes integer types
Note allowable operations on above, such as 'First,'Last, 'Succ, 'Pred, "*" $+ , etc. , areavailable only as appropriate (minimumassumptions)
generictype Counter is (0);
function GenF (X : Counter) return Counter;
function GenF (X : Counter) return Counter isbegin
return X + 1; - oopsend GenF;
As
Private Formal Parameters
type T Is private;
Good news: any type except a limitedtype will match this formal.
Bad news: you can only declare objects,assign values to objects, and testfor equality (just those operationsyou would expect to be able toperform on a private type).
type T is limited private;
Good news: any type including a limitedtype will match this formal.
Bad news: you can only declare objectsand nothing else (just whatyou would expect to be able todo with a limited private type).
Remember, object parameters are given values byassignment, so can't have limited private objectparameters (rats!).
genericFile : Textlo.File_Type;
procedure Oops;
Static Uses Not Allowed
declare
genericX :Integer;
package Static_Uses_Illegal Is
type Length Is range 1.. X;
type Precision Is digits X;
N : constant := X;
end StaticUsesIllegal;
package S is new StaticUses_Illegal (3);
beginnull;
end;
Surprise
declaresubtype Small is Integer range 1.10;X : Integer := 27;generic
S : in Small;procedure Gen;procedure Gen isbegin
Put ("All OK");
end Gen;procedure P Is new Gen (X);
beginP;
end;
-- will raise ConstraintError at time of Instantiation
declaresubtype Small Is Integer range 1.10;X : Integer := 27;generic
S : in out Small;procedure Gen;procedure Gen Isbegin
Put ("All OK");end Gen;procedure P is new Gen (X);
beginP;
end;
-- will execute OK - in spite of apparent error
2
Different Integer Types
Ada allows user defined Integer types:
type Dimension Is range 0.. 100;
This is really a derived type, and therefore a distincttype from type Standard.Integer.
Therefore, a utility that worked with Integers wouldnot work with type Dimension:
function IsPrime (P : Integer) return Boolean;
D : Dimension := 27;
If Is_Prime ( D ) then ... -- would not compile
One solution:
If Is-Prime ( Integer ( D ))then... -- OK
Generic solution:
generictype IntLike Is range <>;
function IsPrime ( P : Int_Like) return Boolean;
function PrimeDimension is newIsPrime ( IntLike => Dimension);
if PrimeDimension ( P => D) then ... --OK
3
Other Numeric Generic Parameters
Similarly, a generic could manipulate floating orfixed point numeric objects of user-defined types.
function Sqrt (X : Float) return Float;
Would only work with values of type Float:
type Precise is digits 9;Measurement : Precise := 2.33442_545;
beginAns : Sqrt (Measurement); -- would not compileAns := Sqrt (Float (Measurement)); -- OK, but ugh
Better to make Sqrt generic:
generictype Precision is digits <>;
function GenSqrt (X : Precision) return Precision;
function Sqrt is new GenSqrt (Precise);
M := Sqrt (Measurement);
Note that you Don't say:
function Sqrt is new GenSqrt (9);
4
Fixed Point Does Not Give an Alternative
Recall that there is no general purpose fixed pointtype so all fixed point types (except Duration) areuser-defined.
function Sqrt (X : NoGlobal_FixedType)
So, fixed point routines must be generic if notin the scope of the fixed point declarations theywill operate on:
generictype Fixed Is delta <>;
function GenFixedSqrt (F : Fixed) return Fixed;
And, instantiations would look as you would expect:
type Fix Is delta 0.01;function FixSqrt Is new GenFixedSqrt (Fix);
Note, again, that the syntax of the Instantlation
Is not:
function FixSqrt Is new GenFixedSqrt (0.01);
5
Enumeration Types Can Also Be Passed
If a generic needs to know about an enumerationtype, there is a generic formal parameter forany discrete type.
Note that integer types are also considered discretetypes, so an Instantlation can pass either anenumeration type or an integer type.
generictype Things Is (<);
function Number_Of_Things return Integer;
function NumberOfThings return Integer isbegin
returnThings'Pos (Things'Last) -Things'Pos (Things'First) + 1;
end NumberOfThings;
function Two is newNumber_Of_Things (Boolean);
function LookOut is newNumberOfThings (Integer);
function BarelyMakeIt is newNumber_Of_Things (Positive);
uuuun l n lnlglnl~ J mml nU6
Review of Simple Parameters
To pass Use the form
Integer type Int is range <>;
Floating type Fit is digits <>;
Fixed type Fix is delta <>;
Discrete type Enum is (<>);
(integers are also discrete)
7
Access Type Parameters
generictype IntPtr Is access Integer;
package Probably_NotTooUseful is ...
When one parameter depends on another:
package Access_Example Is
type Candy is (MM, Mars, Hershey);type Pointer is access Candy;
generictype Blind is limited private;type Ptr Is access Blind;
package Lists is
type List is limited private;-- must be limited Why?
procedure Make (L : in out List);-- etc.
privatetype List Is
recordData: Blind; -- because of thisLink : Ptr;
end record;end Lists;
package CandyChain is new Lists(Blind => Candy,
Ptr => Pointer
end AccessExample;
8
Structured Types
How do you pass an array to a generic?
generictype Arr Is private;ObJ : Arr;
procedure Try;
S : String (1 .. 5) := "kitty";
procedure Nice-Try Is new Try (String, S);
procedure Try isbegin
Obj( 1 ) := 'w';end Try;
Sorry - no dice
To be treated as an an array, the structure of an objectmust be "known" to the generic:
41L .... .
How To Teach Your Generic About Arrays
generictype IntArray is array
(integer range <>) of Integer;procedure SortArray (Arr : in out Int_Array);
procedure SortArray (Arr : in out IntArray) isTemp : Integer;
beginfor I In Arr'First + 1.. Arr'Last loop
for J in Arr'First . I - 1 loopif Arr (I) < Arr (J) then
Temp := Arr (J);Arr (J) := Arr (I);Arr (I) := Temp;
end if;end loop;
end loop;end SortArray;
type List Is array (Integer range <>) of Integer;
procedure S Is new SortArray (List);
L : List (1.5) := (3, 2, 4, 7, -3);
beginS (L);
Here, the component type had to be Integer, and theindex range had to be an unconstrained range ofInteger.
10
More Flexibility Possible
Above, the Index type was Integer and thecomponent type was type Integer.
Here, the Index type is a range of any integer typeand the component type is also any integer type.
generictype Index is range <>;type Component is range <>;type IntArray is array (Index) of Component;
procedure SortArray (Arr : In out IntArray);procedure Sort_Array (Arr : In out Int_Array) is
Temp : Component;begin
for I in Arr'First + 1 . Arr'Last loopfor J In Arr'First.. I - 1 loop
if Arr (I) < Arr (J) thenTemp := Arr (J);Arr (J) := Arr (I);Arr (I) := Tdmp;
end if;end loop;
end loop;end SortArray;type Short is range 1.. 5;type Dimension is new Integer range 0.. 100;type List Is array (Short) of Dimension;procedure S Is new SortArray
(Short, Dimension, List);L: List := (2, 5, 4, 6, -3);
beginS(L)
12
. ... .......... . . inm m AIR, m
Even More Flexibility
An array must be indexed by a discrete type, but notnecessarily an integer type - an enumerated typeIs also OK.
Also, the component type can be anything (but ifassignment is needed in the generic, then it cannotbe limited).
generictype Index is (<>);type Component is private;type IntArray is array (Index) of Component;
procedure Sort-Array (Arr : in out Int_Array);
procedure SortArray (Arr : in out IntArray) isTemp : Component;
beginfor I in Index'Succ (Arr'First) . . Arr'Last loop
for J in Arr'First. . Index'Pred (I) loopif Arr (I) c Arr (J) then
Temp := Arr (J);Arr (J) := Arr (I);Arr (I) := Temp;
end if;end loop;
end loop;end SortArray;type List is array (Boolean) of Float;procedure S is new Sort_Array
(Boolean, Float, List);L : List (4.5, 2.6945);
beginS(L);
14
Constrained vs. Unconstrainted Arrays
Note that the first example used an unconstrained typefor the formal array parameter and was instantiatedwith an unconstrained actual array type.
The next two examples showed a constrained arraytype parameter and actual type.
There is NO array parameter to generics that allowseither an unconstrained or constrained array typeto be passed to it.
Typically, if you would like to allow either, make thegeneric handle unconstrained arrays, and make the userdeclare constrained array types based on namedunconstrained types, which are the ones used for theinstantiation.
type Short Is range 1 . . 5;type List is array (Short) of Things;
The above is really shorthand for
type Anon is new Integer; -- or other parent typesubtype Short is Anon range 1 . . 5;
type AnonList is array (Anon range <>) of Things;subtype List is AnonList (Short);
So, just don't take shortcuts In declaring the user
array types.
15
No Generic Record Types
Would be nice, but the syntax and rules would haveto be quite complex.
For example,
generictype First Component is private;type Second_Component is private;type Rec is record
Namel : FirstComponent;Name2 : SecondComponent;
end record;procedure Nice-Try;
How would you handle different sized record structures?
How would you handle initialized components?
What would you do with such general records oncethey were passed to the generic?
Food for thought...
16
Exceptions Raised by the Instance
Exceptions can be raised and propagated by an instanceduring processing.
These must be handled by the user of the instance:
genericprocedure Action;
procedure Action isError : exception;
begin
end Action;
procedure Act1 is new Action;procedure Act2 is new Action;procedure Act3 is new Action;
begin
Act1;Act2;Act3;
exceptionwhen Actl.Error =>when Act2.Error =>when Act3.Error =>
17
No Exception Parameters To a Generic
Can't pass an exception to a generic to be raised:
generic
WhenTrouble : exception; -- nope
procedure Sort•...
exceptionwhen others =>
raise WhenTrouble;end Sort;
My_Exception : exception;
procedure S is new Sort (MyException);
beginS;
exceptionwhen My_Exceptlon => -- this Isn't possible
whatever...end;
18
But, There Is Something Just As Useful
Passing a subprogram to a generic is possible:
generic
with procedure CallMeSometime;procedure GeneralStuff;
procedure GeneralStuff Isbegin
CallMeSometime;
end GeneralStuff;
procedure WaitForCall isbegin
Put ("I've been called!");end WaitForCall;
procedure Myinstance is newGeneralStuff (WaitForCall);
begin
Myjnstance;-- WaitForCall could now be called-- by the Instance
19
Subprogram Parameters
Replaces the dynamic passing of subprogramssuch as In standard Pascal.
Enables more complete type checking, i.e., typesof parameters to passed subprogram can bechecked against calls to It.
Pascal problem:
program P;type
Color = (Red, Green, Blue);var
Bucket : Color;
procedure Print (C : Color);begin
case C ofRed : write ('Red');Green : write ('Green');Blue : write ('Blue');
end;end;
procedure Proc (P : procedure):begin
P (Bucket); (* OK *)'P (5); (* runtime error *)
end;
beginProc (Print);
Ada Solution
declare
type Color is (Red, Green, Blue);Bucket : Color:= Green;
procedure Print (C : Color) Isbegin
Textlo.Put (Color'Image (C));end Print;
genericwith procedure P (Val : Color);
procedure GenProc;
procedure GenProc isbegin
P (Bucket); -- OKP (5); -- compile time error
end GenProc;
procedure Proc is new GenProc (Print);
beginProc;
end;
I • n il I I n m ia ,, m 2
......- -- - - I --- ___ -
Sending the Parameter Types, Too
One of the most common uses of subprogram parameters
to generics is to provide the generic with operations on
user-supplied types.
Some operations are Implied by the generic formal
parameter:
type T is private;
allows values of this type to be assigned
to variables and compared for equality
type T is (<>);
matches any discrete type
allows use of 'First, 'Last, 'Succ, 'Pred, 'Image,
'Value, 'Pos, 'Val, "<", ">", as well as above.
type T is range <>;
matches any integer type
since integer types are also discrete types,
allows all of the above plus the integer operations
such as + # e1, etc.
type Ar Is array (Index) of Component;
allows Indexing, slicing, assigning, equating
(which are special for arrays), 'Length, 'First,
'Last, etc.
3
When Additional Operations are Needed
For example, with array, private, and limited privatetypes, the generic cannot perform text output of valueswithout help from the user:
type Handle Is access Integer;Ptr : Handle := new Integer'(57);
function Handle_Image (L : Handle) return String isbegin
return Integer'Image (L.all);end Handle-Image;
generictype Any is limited private;with function StringOf (X : Any) return String;
procedure GenProc (Obj : Any);
procedure GenProc (Obj : Any) isbegin
Put ("This is GenProc processing... ");Put (StringOf ( Obj));
end GenProc;
procedure Example Is new GenProc(Handle, Handle-Image);
procedure Interesting is new GenProc(Integer, Integer'Image);
beginExample (Ptr);Interesting (75);
end;
4
Default Subprogram "Values"
As with generic object and value parameters (and unlikegeneric type parameters - why?) generic subprogramparameters can be supplied by defaults.
For example, consider the following:
with Text_lo;package Shell is
generictype Any is limited private;with procedure Print (Val : Any)
package AnyLists is
type AnyList is ...
procedure Put (L : AnyList);-- the body would call the generic-- parameter Print procedure
end Any_Llsts;
package CharLists Is new Any_Lists(Character, Text_lo.Put);
end Shell;
.,...4=
With judicious naming of the generic subprogramparameter, a default might be possible:
with Textlo;package Shell Is
generictype Any is limited private;with procedure Put (Val : Any) is <>;
package AnyLists is
type Any_List is...
procedure Put (L : Any_List);-- the body would call the generic-- parameter Put procedure
end Any_Lists;
package CharLists is new AnyListst (Character);
-- what's missing?
end Shell;
Remember - the resolution of the default takes place atthe point of Instantiation (not at the genericdeclaration). Otherwise, it would be trivial.
6
Speaking of Point of Declaration vs. Instantiation...
Also remember that global references from within ageneric refer to those at the point of declaration notthose at the point of instantiation. But, defaultreferences refer to matching names from the point ofinstantiation. Confused?
with Text lo;use Text_lo;package Shell is
Global : Integer := 17;
genericwith procedure Put (Val : Integer) is <>;
procedure Demo;
end Shell;
package body Shell is
procedure Demo isbegin
Put (Global);end Demo;
end Shell;
i Ii ml m Im •7
with Shell;package Inner is
Global : Integer := 39;
procedure Put (I : Integer);
procedure User is new Demo;end Inner;
with Textlo;package body Inner is
procedure Put (I : Integer) Isbegin
Text lo.Put("Surprise!" & Integer'lmage (I));
end Put;end Inner;
Inner.User;
What gets printed?
So, generic instantiation is not simple text substitution.
L8
Exercise
Modify the Sorting example from before so that the usercan optionally change whether the sort is ascending ordescending.
NAs before:
generictype IntArray is array
(Integer range <>) of Integer;procedure SortArray (Arr : in out IntArray);
procedure SortArray (Arr : in out IntArray) isTemp: Integer;
beginfor I in Arr'First + 1 . . Arr'Last loop
for J in Arr'First. . I - 1 loopif Arr (I) < Arr (J) then
Temp := Arr (J);Arr (J) := Arr (I);Arr (I) := Temp;
end If;end loop;
end loop;end SortArray;
Make minimal changes to satisfy requirement.
I l i i • 9
Solution
generictype IntArray Is array
(Integer range <>) of Integer;with function "-c" (Left, Right : Integer)
return Boolean is <>;procedure SortArray (Arr : in out Int_Array);
procedure SortArray (Arr : in out Int_Array) isTemp : Integer;
beginfor I in Arr'First + 1.. Arr'Last loop
for J in Arr'First.. I - 1 loopif Arr (I) < Arr (J) then
Temp := Arr (J);Arr (J) := Arr (I);Arr (I) := Temp;
end if;end loop;
end loop;end SortArray;
Instances could be declared:
type List Is array (Integer range <>) of Integer;
procedure Ascending1 is new Sort-Array(List, "<");
procedure Ascending2 is new Sort-Array (List);
procedure Descending is new Sort-Array(List, >")
10
Nesting of Generics
It can be useful to export a generic utility from ageneric package. Don't clutch:
generictype Element is private;with function "<" (Left, Right : Element)
return Boolean is <>;package Sorted_BinaryTrees Is
type Tree is private;
procedure Insert(X : Element; Into "in out Tree);
genericwith procedure Operate (X : Element);
procedure SearchAndOperate (T : Tree);
end SortedBinaryTrees;
(The body is, of course, "trivially obvious to even themost casual reader"...
Exercise: Give an example instantlation of the abovegenerics. (Not the body.)
A Simple Solution
package IntTrees isnew Sorted_Binary_Trees (Integer);
procedure Put_lnt (X : Integer) is
beginTextlo.Put ( Integer'lmage (X));
end PutInt;
procedure PrintInOrder is newIntTrees.SearchAndOperate (Putjlnt);
2
Other Type Parameters
As with arrays, unconstrained types are allowed forprivate and limited types using the customary syntax:
generictype Furniture (Upholstered : Boolean)
Is private;package P is
Table : Furniture (False);Couch : Furniture (True);
end P;
Note that a default for the discriminant is Not allowed.
This means that an unconstrained object cannotbe declared (unlike typical discriminated records)
Incidentally, a type mark must be used in a genericpart, and not a subtype:
genericsubtype Short Is Integer range -6,;
procedure NotAChance;
. . .. ... .-- -- w in _ l~mm ) n mar m , lm m m3
More on Unconstrained Types
Peculiar situations can arise when matching a private orlimited type with an actual type which is unconstrained.
If the actual type is unconstrained:
an unconstrained arrayan unconstrained record without a default
discriminant
then you can't declare an object of that type inside thegeneric (which includes allocators without initial values)
unless the object is a constant, meaning the initial valuemust have been supplied by the Instantiation.
4
generictype T is private;
package Experiment IsVal : T;type Ptr Is access T;P : Ptr := new T;
end Experiment;
type Boo is array (Boolean range <>) of Integer;package P Is new Experiment (Boo); -- will fail
type Rec (B : Boolean) is recordnull;
end record;package Q is new Experiment (Rec); -- will fail
generictype T is private;Init : T;
package Experiment IsVal : T := Init; -- still a problemtype Ptr Is access T;P : Ptr := new T'(In It); -- this helps
end Experiment;
type Boo Is array (Boolean range <>) of Integer;I : Boo (False.. True) := (6, 12);package P is new Experiment (Boo, I);' -- will fail
type Rec (B : Boolean) is recordnull;
end record;R : Rec (False) := Rec'(B => False);package 0 Is new Experiment (Rec, R); -- will fail
5
generictype T is private;[nit : T;
package Experiment isVal : constant T := Init; -- OKtype Ptr Is access T;P : Ptr := new T'(Init);
end Experiment;
type Boo is array (Boolean range <>) of Integer;I : Boo (False.. True) := (6, 12);package P is new Experiment (Boo, I); -- OK
type Rec (B : Boolean) is recordnull;
end record;R : Rec (False) := Rec'(B => False);package 0 is new Experiment (Rec, R); -- OK
6
Retrofitting Generics
Look familiar?
package Counter istype Count is limited private;procedure Increment (C : in out Count);procedure Reset (C : out Count);
private...end Counter;
package Trees istype Tree is limited private;procedure Get (T : out Tree);function Is_Leaf (T : Tree) return Boolean;procedure Split (T : in out Tree;
Left, Right : out Tree);procedure Return (T : in out Tree);
private...end Trees;
with Trees;package Piles is
type Pile is limited private;function Empty (P : Pile) return Boolean;procedure Put (T : in out Trees.Tree;
On : in out Pile);procedure Initialize (P : in out Pile);procedure Get (T : out Trees.Tree;
From : in out Pile);private...end Piles;
with Trees, Piles, Counter;procedure CountLeaves is...
7
Generalization
generictype Object is limited private;
package GeneralPiles istype Pile is limited private;function Empty (P : Pile) return Boolean;procedure Put (T : in out Object;
On : in out Pile);procedure Initialize (P : in out Pile);procedure Get (T "out Object;
From : in out Pile);private...end Piles;-- package Is the same except for substitution-- of Object for Trees.Tree
with Trees, General_Piles, Counter;procedure CountLeaves is...
package TreePiles isnew GeneralPiles (Trees.Tree);
-- can be the same otherwise
Note that this generalization was made easy due to thelack of assumptions that the original components madeabout each other's types.
Clue: private and limited private types assist in futuregeneralizations of your program components.
-- m: i l i II I l I8
What if the types aren't private?
Generalizations are still possible, but require morecomplicated generic parts.
package ExportArray istype Global_Array Is array (1. .10) of Integer;
with Export Array;package Needs_ToSeeGIobalArray is
procedure Sort(Ar : In out ExportArray.GlobalArray);
To generalize the above:
generictype GA is array (1..10) of Integer;
package NeedsToSeeGlobalArray isprocedure Sort (Ar : in out GA);
Or better would be:
generictype Index_Range is range <>;type GA is array (Index-Range) of Integer;
package NeedsToSee...
But would need to ensure that the body of the packagedid not depend on literals unique to the original arraytype (i.e., that the range went from 1 to 10).
.. ........... . .... . = mmmm mm mm ( mml mmmm m mml 9
Simple Generic
Given a single state-machine Implementation of stacks,the customary way to Introduce many stacks Is to turnit Into an abstract data type:
Simple stack package:
package Stack Isprocedure Push (I : Integer);procedure Pop (I : out Integer);function Empty return Boolean;function Full return Boolean;
end Stack;
Conventional way to convert to many stacks:
package Stacks istype Stack Is private;procedure Push (I : Integer; On : in out Stack);procedure Pop
(I : out Integer; From : In out Stack);function Empty (S : Stack) return Boolean;function Full (S : Stack) return Boolean;
private...end Stacks;
User code:
S : Stacks.Stack;I : Integer;
beginPush (25, S);Pop (I, S);
- , nmmmmm~mmm w nnlu nnum lnnm A sklllln I ' ' n m m
N H
-- I - - - - -- - - -
Many Stacks, "Generically"
Review the original single stack:
package Stack Isprocedure Push (I : Integer);procedure Pop (I : out Integer);function Empty return Boolean;function Full return Boolean;
end Stack;
Illustration of generic method (not necessarilyrecommended, just for example):
genericpackage Stack is
procedure Push (I : Integer);procedure Pop (I : out Integer);function Empty return Boolean;function Full return Boolean;
end Stack;
No change to the body in this conversion! (Unlike thebody of the private type example.)
User code:
package S1 Is new Stack;package S2 Is new Stack;I : Integer;
beginS1.Push (25);S1.Pop (I);
-,,..,4=2
Generic Implementations
What happens when a generic Is elaborated?
What happens when an instantlation Is elaborated?
It depends...
Suppose an Initialization block appears at the end of ageneric package body:
with Textlo;package body Stack Is
beginTextlo.Put ("Stack Instance elaborated");
end Stack;
Then, each of the following will cause the above Putstatement to execute:
package S1 is new Stack;package S2 Is new Stack;
In the case of packages (not generics) there would onlybe one logical package and only one elaborationinitialization would occur.
This emphasizes the fact that there are as many logicalpackages (or subprograms) as there are instantlationsof a generic package (or subprogram).
3
Logical or Physical?
Debate over whether an Implementation should actuallycreate physical copies of a generic for each Instance orsomehow "code share" among all the Instances.
Code sharing Is more the way a procedure or functionbehaves (re-entrant).
Physical expansion (cody copying) is more the way amacro expansion behaves.
There are advantages and disadvantages of each:
Physical Expansion, Pro:
Object code executes faster because all the workis done at compile time and no context switching isneeded among the Instances of the same generic code.
Implementation Is simpler.
Physical Expansion, Con:
Space requirements for object code can become areal problem if there a lot of Instances.
Recompllation of a generic spec Is always requiredeven If Just the body changes. (Why?)
.,,==,=.n== ==m == nuB m =a ~ lm nn m 1 !! I I
- -.-.l _ l , p • -- r -
Code Sharing, Pro:
Significant savings in object code size.
Generic bodies can be changed without recompilingthe specs (and therefore the instantlatlons).
Code Sharing, Con:
Execution can be slower due to run timeinstantiations.
Implementation Is more difficult.
So, which is it? There Is a "best" answer:
For a development compiler, on a host machine, wheremaintenance, modification, and recompilation is likelyand turnaround time Is more Important that saving afew milliseconds at run time, you want a code sharingcompiler.
For a target compiler, In a time-critical application,where execution efficiency Is more Important thatrecompllation efficiency, you want a code copyingcompiler.
It's 11:00 ... Do you know what your compier isdoing?
(Do you know what the different vendors offer?)
5
More Retrofitting - Make the following general:
*. package Project issubtype Line is String (1.80);subtype Word is String (1..80);type BreakChars is (' ', '-', '.', ,');
end Project;
with Project; use Project;procedure Next-Word (From : in out Line; Into : out Word) isbegin
Into := (others => ');for C in 1 .. 80 loop
- find first non-BreakChars letter in Fromend loop;for W in C.. 80 loop
- copy contiguous non-BreakChars to Intoend loop;for R in W+1 .. 80 loop
- left justify remaining letters in From- and set rest to a Blank
end loop;end NextWord;
with NextWord;with Project; use Project;with Text_lo;procedure Main is
lnput_Line : Line;Length : Natural;A_Word : Word;
begin ... - initializations, file openingswhile not Textlo.End Of File (InFile) loop
Input-Line := (others => ");GetLine (InFile, InputLine, Length);loop
NextWord (From => lnputLine, Into => A-Word);exit when AWord = (others =>PutLine (AWord);
end loop;end loop;
end Main;
6
package Project issubtype Line is String (1..80);subtype Word is String (1..80);type BreakChars is (' ,'-, ", ,),
end Project;
generictype Line is array (Positive range <>) of Character;type Word is array (Positive range <>) of Character;BreakChars : String;
package NextWordPackage isprocedure NextWord
(From .in out Line; Into : out Word);end NextWordPackage;
package body NextWordPackage isprocedure NextWord
(From : in out Line; Into : out Word) isbegin
Into := (others => BreakChars (BreakChars'First));
with NextWord;with Project; use Project;with Textlo;procedure Main is
Input_.Line: Line;Length : Natural;A-Word : Word;package Words is new
begin - initializations, file openingswhile not Textlo.EndOfFile (InFile) loop
Input_- Line := (others => ");Get-Line (In-File, Input-Line, Leng'h);loop
Next Word (From => Input_Line, Into => A-Word);exit when AWord = (others => 'PutLine (AWord);
end loop;end loop;
end Main;
7
Unwrapping Ada® Packages
LCDR Melinda MoranComputer Science Department
U. S. Naval AcademyAnnapolis, MD 21401
(301) 267-2797AV 281-2797LINDY@USNA
Adas is a registered trademark of the U S Governmet Ada Joint Program Office
' -mmimiimnnl ib~mmii'll
Ada Program Structure
O 4 Basic Program Units:
E(Packages
O Subprograms
0 Tasks
= Generic Units
Packages, a Powerful Tool forSoftware Engineering:
OAbstraction0 both data and process abstraction supported0 layers of abstraction supportedO faciltate managing complezity by allowing
division of problem into layers of abstractionwith 7 +/ - 2 components each
nformation Hidingo irrelevant information hiddenO only information relevent to each level of
abstracLon is visible and accessible at thaty levelModularity
o1 facilitate creation of libraries ofsoftware modules which can be reusedto implement many systems
o facilitate easily modified systems wherepackages can easily be added and subtracted
Bi"Localizationo facilitate creation of very cohesive packages
whIch car, be less tightly coupled
0 Uniformity0 Completeness2"Con irmab ii Ity
O communication only through visibleinterface minimizes debugging problemsby minimizing "ripple* effects
0 clear definition of interfaces simplifiestesting problems
PACKAGES
Definition: collection of computationalresources, which may encapsulate datatypes, data objects, subprograms, tasksand even other packages.
Purpose: to express and enforce user'slogical abstractions within the language.
Applications/Common Usages:
o Encapsulate related data types, constants orobjects.
o Encapsulate related program units.0 Embody an Abstract Data Type.0 Embody an Abstract-state Machine.0 Encapsulate tasks.*
ilnfo taken from Software Engineering with Ada by Grady Boochwith exception of "] --
Structure of a Package
0 Composed of 2 parts
0 Specificationo define the package interface with c2bfl
modules-- tre types Kid =-Aces if offerso define the portion of the package vlslb*e
to other moduleso must be compild bfoe prog=r units
which ume ito may cantain a -privat portion
0 Bodyo contAs lrIlmmrtation detas of1Ohw 8
the d c-age hfi Its contrac wtth thecliont modules
0 aciMttes "Iorm@Uofl hdt~ - hieirrlevo Wnorrmaton ft=m cient
o protects data Wv~nxtres and opea athonsIt encsuate s fr=n Indver twit ormaidoous tam periMn7 by chent module
o1 my I* aspetely copie at a atetft U Weetiwi
o0 may bereplaced with diferntkvp41 Ment~n wWttflr!CoMplt'r ippW to OtIW ndulss as kft
spa~~~~ Mictlp~ ~ wda1 my Mo b~ ~In t gm setaiwa ny
cotains types or object4 dclartiono may cotain a secumo of t auo
statefmts and an excption handler
pwtmuar~~z.~ awlIn meamepinaa*.vzez cam : aI ~)
CIO
vitA T Zap - 2=1 mu-aft bier IRML-in LAI
EM I OW~~l 4USCR I- Mb int W I(27):
b"La
MT clmz I
m(3g
WC azp Le
gatMT(Ec)
M (,es IrWKMas~
wiendw Sefainwktal . Imsi stw obeg"
mT(mM I
AD-AI.89 641 AfjjERffW XHPUITi97) ADA JOINT PROGYAN 3/4
UNCL*SSZIED F/C L2/3 HI.
1.0
I O _1 _ __2 -
MICROCOPY RLSOLU1ION ItY1 CHAR'
-- Unit Name: Basic 10-- Author: LCDR MORAN-- Date: 4 AUG 1987-- Function: Provides user ability to do input and output of- character, string, integer, and floating point
-- data types.
package Baslce9 is
procedure New Line;-- advances cursor to next line on the screen
procedure Get(Item : out character)l-- reads a single character from the keyboard
procedure GetLine(Item : out character);-- reads a single character and carriage return from the keyboard
procedure Put(Item : in character);-- outputs a single character to the screen
procedure PutLine(Item : in character);-- outputs a single character to the screen and advances the cursor-- to the next line on the screen
procedure GetcItem : out string);-- reads a string of characters from the keyboard
procedure GetLine(Item I out string);-- reads a string of characters and a carriage return from the keyboard
procedure Put(Item : in string);
-- outputs a string of characters to the screen
procedure Put Line(Item : in string);-- outputs a string of characters to the screen and advances the cursor-- to the next line on the screen
procedure Get(Item : out integer):-- reads an integer from, the keyboard
procedure Get Line(Item : out integer);-- reade an integer and a carriage return from the keyboard
procedure Put(Item : In integer);
-- outputs an integer to the screen
procedure Put.Line(Item : in Integer);-- outputs an integer to the screen and advances the cursor to the-- next line on the screen
procedure Get(Item t out float);
-- reads a floating point value from the keyboard
procedure GetLine(Item t out float);-- reads a floating point value and a carriage return from the keyboard
procedure Put(Item : in float);-- outputs a floating point value to the screen
procedure Put Line(Item : in float);-- outputs a floating point value to the screen and advances the cursor
to the next line on the screen
end Basic_10;
@3~0 -30.4 .
-9 .3 a,-0
*z a3 13 0 a 3 U .C; .3 CL C0 C 2*2 5 4 C LS
I - C 03 -1 -L - .01 0 ., 0- .3 a. -1
21 G a a c~ a a 0- a a 0 2L. ! * a . 1. c . c L. .3 .- Z3 _ , _. _ , - . S -. a: - zm m3 13 a .V * s 1 0c 3 -0 In V "a is 1 n - I 0a
Cl a3 II - C 0 4* C -a r .3 C .3 S r 3 C .3c
0 0* - 0 a. I . 0 I 0 0 000
C2 -L C- SL 0L SL 0*- 2L 0 - 4*.0.4 c2 - 0 -. a. - a. .. 4 0 . C2 3.4 a. . A. .3.
I I I I IIS SI SI
41 3 4 33 S . .3 5 0 S 03 S 0 0 0
0 0 1 0 0
0.a 0.0 . . 0 0. 0.C- C
-00
.3 I313 a 1 0-Do- ao c !a
C; a;O *C 0 ooc .
-10 1 a CS. e .C Ic a L
1 !0 cV -; 2 - a. 2. 1. 3 - z 2 o - C .
Wn -u 0 U a 0Ca S. S0 1 L . L
.C 4 .3 CL 0 .0. S.C C3 L0CSCu . *4.
102 CL. @
package COMPLEX Istype COMPLEX-NUMBER is record
REAL-PART FLOAT,IMAGINARY-PART: FLOAT,
end record;function "- (A,B in COMPLEX-NUMBER) return COMPLEX-NUMBER;function"-" (A,B In COMPLEX-NUMBER) return COMPLEX-NUMBER;
end COMPLEX;
package body COMPLEX isfunction "-" (A,B. In COMPLEX-NUMBER) return COMPLEXNUMBER is
RESULT COMPLEXNUMBER;begin
RESULT.REALPART:= A.REAL..PART - B.REALPART,RESULT. IMAGINAPYPAPT := A.IMAGINARYPAPT + B.IMAGINAPYPART;return RESULT,
end;
function "-" (A,B- In COMPLEX-NUMBER) return COMPLEX-NUMBER IsRESULT COMPLEXNUMBEP;
beginRESULT.REALPART := A.REALPART - B.REALPART;RESULT.IMAGINARYPART:= A.IMAGINARYPART - B.IMAGINAPYPART,return RESULT;
end;end COMPLEX;
package FRACTIONS Istype FRACTION Is record
NUMERATOR :NATURAL;DENOMINATOR :NATURAL;
end record;function " (A,B In FRACTION) return FRACTION;function (A,B In FRACTION) return FRACTION;
end FRACTIONS,
package body FRACTIONS Isfunction *" (A,B: in FRACTION) return FRACTION is
RESULT. FRACTION;begin
RESULT.NUMERATOR:=. (A.NUMERATOR * B.DENOMINATOR)(B.NUMERATOR *A.DENOMINATOR);
RESULT.DENOMINATOR : A.DENOMINATOR + B.DENOMINATOR;return RESULT,
end;
function "-* (A,B In FRACTION) return FRACTION IsRESULT: FRACTION;
beginRESULT.NUMERATOR:= (A.NUMERATOR * B.DENOMINATOR) -
(B.NUMERATOR * A.DENOMINATOR);RESULT.DENOIINATOR;: A.DENOMINATOR B.DENOMINATOR;return RESULT;
end;end FRACTIONS;
*wsiiimi rnulg mmdl
with COMPLEX, FRACTIONS;use COMPLEX, FRACTIONS;procedure ARITHMETIC Is
X: FRACTION:= (3,4);Y: FRACTION := (5,6);FRACTION-RESULT: FRACTION:= (1, 1);
A: COMPLEXNUMBER := (5,7);B. COMPLEXNUMBER := (8,9);COMPLE)X.RESULT: COMPLEXNUMBER:= (0,0);
beginFRACTION.RESULT:= X + Y;COMPLEXRESULT:= A + B;
FRACTIONRESULT : X - Y;COMPLEXRESULT:= A - B;
end;
Packages with No Body
package CALENDAR istype DAY is (MONDAY, TUESDAY, WEDNESDAY. THURSDAY, FRIDAY.
SATURDAY. SUNDAY),type MONTH is (JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE.
JULY. AUGUST. SEPTEMBER. OCTOBER. NOVEMBER,DECEMBER):
type YEA'. is range 0 .. INTEGER'LAST;end CAL;-. jAR:
package METRICEARTHCONSTANTS isEQUATORIAL-RADIUS : constant :- 6378.145: -- kmGRAVITATION-CONSTANT: constant:- 3.986012e5; -- km'*3/secs2SPEED-UNIT : constant :- 7.90536828; -- km/secTIME.UNIT : constant :- 806.8118744: -- sec
end METRICEARTHCONSTANTS;
IMETR ICEA RTHCONST ANTS package taken from. Software Engineeringwith Ada by Grady Boochi
page F-30wuith TYPES;use TYPES;package GIGI_GRAPHICS.PKG is
procedure SETSCREENSCALE(left,righttop,bottom: in integer);procedure CLEARSCREEN;procedure SETSCREENCOLOR(color :in colortype);procedure SETREVERSEVIDEO;procedure SETNORlIALVIDEO;procedure FREEZESCREEN(ticks :in integer);procedure MOVECURSORABS(xcoord,ycoord : in integer);procedure SETCLRSORAT(xcoord,ycoord :in integer);procedure MOVECURSORREL(xincr,yincr :in integer);procedure QtlERYCURSORPOSC~ccoord,ycoord :out integer);procedure SAVELASTIMOVELOC;procedure RESTORELASTMOVELOC;procedure PUTDOT;procedure DRAWLZNETO(xcoord,ycoord :in integer);procedure DRAtPOLYLINE(coordarray :in coordarraytype;
num _of..coord~pairs :in integer);
procedure DRAWCIRCLE(xcoord~yc*oord~radius in integer);procedure SETSHADINCEZEFL114E(y_value: in integer);procedure SETSHAD13CCHAR(shadin&_char :in character);procedure SETSHADINGON;procedure SETSHADINGOFF;procedure SAVELASTDRAWLOC;procedure RESTORELASTDRAWLOC;procedure SETWRITINGCOLOR~color :in colortype);procedure SETWRIT INCG':ODE (mode : in modety pe)procedure SETTEXTSIZE(size in integer);procedure SETTEXTPATHi(angle in integer);procedure SETTEXTHEIGIIT(height :in integer);procedure SETITALICSMIGLE(angle in integer);procedure SETflLINlKOFF;procedure SETBLINKON;procedure SAVETEXTATTRIBUTES;procedure RESTORETEXTATTRIBUTES;procedure OUTPtIT(integer _val : in integer);procedure OUTPUT(text _ val: in string);procedure OUTPUT(char val :in characcer);
end GIGI _GRAPUICS_PKC;
page F-31with TEXTHANDLER;use TEXTHANDLER;package body GIGI_GRAPHICSPKG is
-- current screen scale boundsCLEFT integer :- 0; -- current left x-axis value
CRIGHT integer :- 767; -- current right x-axis valueCTOP : integer :- 0; -- current top y-axis valueCBOTTO1M : integer :- 479; -- current bottom y-axis value
-current cursor position
CP_X : integer : 0; -- current position, x-valueCPY: integer : 0; -- current position, y-value
task SEMAPHORE is
entry SEIZE;
entry RELEASE;end SEMAPHORE;
task body SEMAPHORE is
INUSE : boolean :- false;begin
loopselect
when not IN USE ->
accept SEIZE doINUSE :- true;
end SEIZE;
orwhen INUSE ->
accept RELEASE doIN USE :- false;
end RELEASE;
end select;end loop ;
end SEMAPHORE;
-- - - --- -- -- -- -- -- -- -- --- -- -- -mm-- - -- -- -- -- --
page F-32
function INBOUNDS(xcoord,ycoord in integer) return boolean isxvalid, yvalid : boolean;
begin-- check if xcoord between left and right screen scale boundsif ((xcoord >- cleft) and (xcoord <- cright)) or
((xcoord <- cleft) and (xcoord >- cright)) thenxvalid := true;
elsexvalid : false;
end if ;
-- check if ycoord between top and bottom screen scale boundsif ((ycoord >- ctop) and (ycoord <- cbottom)) or
((ycoord <- ctop) and (ycoord >- cbottom)) thenyvalid := true;
elseyvalid : false;
end if ;if (xvalid) and (yvalid) then
return true;else
return false;end if;
end ;
procedure CLEARSCREEN isT TEXT;
beginT := TO_TEXT(esc) & "Pp" & "S(E)" & esc & "\";
PUT(T);end ;
procedulre SETSCREENCOLOR(color in colortype) isx : integer;T : text;
beg inx := colortype'pos(color); -- xordinal position of color chosen
-- see colortype in types packageT : TOTEXT(esc) & Pp" & "5s(I" & integer'image(x) & ")"
& esc & "\";PUT(T);
end;
procedure SETREVERSEVIDEO isT TEXT;
beginT : TOTEXT(esc) & "Fp" & "S(1)" & esc 4PUT(T);
end ;
......... ............... . . . . , ,,, .- -.- - ---- - --,- - - - - - - - - - - - - - -
Specification Structure
0 2 Parts
0 Visible portiono extends from beginning
of package specificationup to word "private"
O Client modules can "see"and use the types,objects, subprograms inthis section
o Resources in this partof the spec are said to beexported
E Private portion0I Part or the specification
that follows the word"private"
[3 Types declared in thisportion of the spec canbe seen "textually" buttheir structuralcomponents are notaccessible to/corruptibleby the client
0 Declaration of types asprivate facilitates useof abstraction whereclient operates withlogical properties of thetype and cannot accessthe details of its physicalimplementation
0- Private types can only bedeclared in the visiblepart of a package; theirimplementation is in theprivate part of the package
0I 2 categories of private type0 private types - can use
operations declared in visiblepart of pkg spec, assignmentoperator, eq. and inequality op.
0 limited private types- sameas for private types exceptassignment, eq and inequalityoperations unavailable
),mm,,,mmm ~ ~ IM.hmm N H mm m
pacmago .3c!om% Is
type Frtacriof IS ty;o !s :
Nu.,eralrt: In,*q~e,-
Dwctenomntr PSIF.~OSN.0:lnlg" .1; ur Frion; -
fu*'ctfl on gp. FrW l r~on) return fn~egon;
tumarlott Vlaxereat longr; 0: y:-qor returnon return goracrion
f-C.0 V..~t w~2~~ Frec-lo,) return Fracl I on;
ftl'ec Ion Nut(. y Frcrionl reftun Int ; func-rion yot(. y; ract'an; return Faom;
IWIC-IoOance(. Fr: .-ron) reurn 16,090, *tncfion *'1
M. y: Frac-lor) return Fraoieon;
functIin (A y: Frc-*on, return, trjc-!on; fi~~n ~ y rcfn rtr cI.
fun Ifan *x y rtIC ) *fr P-'-in WC(O E .rSdlV oc m eru bid"
funltion -uai(. y Fc"ni FretuN to~an ufclc n 1:UC~ fraC-,tta return 000104n;
f~tCtifA -1-(X, y: Froc-lon; return Fraci-lc; *s-*(9 yf1? -SCi. ( Frea -er retrn WI w- aeI "e Io c Cer I snS
tc1'fon Eaeue(A: r,,!,,) return F-oioan; printe ous~- rc!Q) rtr Fa-l
futctton Pracx. t Fr~a P.-en o roturm ;nte.n; f1y9*Io FrciloTj - a-ctrvunTT;funcclion *1-tofrac V, P njcr- - return Oid;fmrqm~~a-o~:rtr Z-f
tut-o Roacex FracSV1 m retrnFer-on;prfv-'
O..a'.naror: 1;l..sa rolrd;
sa Ftac'ions;
Figure 1-7 Paci c'- i ge
pacxege. body Frc-fcn fs
coca 'Or um-f om way *%.e~r3c-!cf
func!fam qummr(x. FI~ct20n eofrt n toqr Isbegin
return C. oSerator;
- coca #or tonclifon wa~y 3ono-coca 'or fumcflon wany It
fuflct :n '(.y; F actan) rotrwn Orjet!On IS01: ne gar;
0n -%
-cre Or t,nio waye~ni-,~I~Z
- Coce rocr tonmtifl bOOy qo-
fvl f~z tc- n~~yttC
foc rn z.Wi'. Y: Frzc-!n, returm xCofefl Isbog I n
end ~-code 'or tN cr:on tody -
- OCd 'or .Nrcfn way )
fumdcTion r b orcc retur' In 0'er Is
rotur, 4nre/Cntend Plic-ro-t;
tune-', nro .c- fnlw.en' reru,, F,c-:on is
returnf
end rrOu
package KEYMANAGERistype KEY is private;procedure GETKEY(K -cut KEY);function Y< (X,Y KEY) return BOOLEAN;
privatetype KEY is new INTEGER range 0.. INTEGER'LAST,
end KEY-MANAGER; _
package body KEY-MANA ER isNEXTKEY : KEY:= 1 -- own variable - exists between
-- procedure callsprocedure GETKEY(K ,o3t KEY) isbegin
K :: NEXT.KEY; 7NEXT..XEY := NEXTKEY + I
end GETKEY,
function "<*(X.Y : KEY) ft4rn BOOLEAN isbegin
return INTEGER(X)<ISIWER(Y),end Yend KEY-MANAGER; "
[Taken from Programming with Ada by Peter Wegneri
If
package 3BR is
type NUMBERS is rang* 0 . 9
procedure TAKE (ANUMBER ont NUMBERS);
procedure StRve (NUMBER in NUMBERS);function NOV SERVING return NUMBERS;
and 5-9;
package body 5_1 is
SELV-A-MATIC :NUMBERS :- ;
procedure TAKE (A-NUMBER :eot NUMBERS) is
beginA NUMBER SERVAN-ATtC;
SERVA4-MATIC SgRYA&MATXC - 1;
sad TAKE;
procedure SERVE (NUMBER :in NUMBERS) is separate;
function Nou SERVING return NUMBERS is *oerate;
and BR;
with B R;
procedere ICE CREAM is
YOUR NUMBER :NUMBERS;
begin
TAKE (YOUR NUMBER);
loop
if NOW SERVING - YOURNUMBER then
SERVE (YOUR NUMBER);
exit;
end if;
end loop;
end ICE-CREAM;
with B B;
procedure ICE-CREAM is
YOUR NUMBER NUMBERS;
begin
TAKE (YOURNUMBER);loop
if NOV SERVING I YOUR NUMBER then
SERve (YOUR.NUMBERz);
exit;
elseYOUR NUMBER YOUR-NUMBER - 1;
oud it;
snd loop;
and ICE CREAM;
package B. is
type NUMBERS is private;
procedure TAKE (ANUMBE : out NUMBERS);
procedure SERVE (NUMBER : in NUMBERS);
function NOW SERVING return NUMBERS;
private
type NUMBERS is range 0 99;
dad B-1;
vith a-1;see BR ;procedure ICE CREAM is
YOUR NUMBE : NUHBERS;
begin
TARE (TOUR NUMBER);
loop
if NOV SERVING - YOUR NUMBER them
SERVE (TOUtRNUmiNE);
azit.ale*
YOUR NUMBER :- NOW SERVING;
ud if;
ead Loop;
end lCE CREAM;
package BR is
type NUMBERS is limited private;
procedure TAKE (A NUMBER : out NUMBEIS);procedure SERVE (NUMBR: is NUMBERS);
functiou NOV SERVING return NUMBERS;
fumctiou "-" (LEFT. RICET : in NUMBERS)
ratera BOOLEAN;function CLOSE ENOUGs (A NUMBER in NUMBERS)
rotor BOOLEAN;
type NUMBERS is raig O .. 99;
sad -1;
vich BR;use BR;
procedure ICECREAX is
YOURNUMBER NUMBERS;
procedure GO TOUQ is separate;
TAKE (TOUR NUMBE);it NOV SEING - TOUNUMIER them
SEVE (YOUR NUMBR);
eloif CLOSECENOUGE (TOUR NUMBER) then
while NOV SERVING /- TOURNUMBER loopmull; unit your turn
end loop;SERVE (YOURNUMBER);
elseGO TODQ;
end if;
end ICE CREAM;
-ds,.=. .,..
Implications of Using theSpecification's Private Section
O Forces recompilation of specificationand any client modules if the datastructure used to implement a typechanges.
o Can be avoided if data structure neededfor a package can be internal to thebody of the package but this disablesclient's ability to declare multipleobjects of a particular type. Habermanand Perry refer to "open type" and"unique object" solutions.
O Can be avoided by making private type an"access" (pointer) type
0
I(-I! .*d L U
01 -; -
cc- 2 E 2 z
C= r I
o t-2 .5CL c E- Z 3
o ~ ~ ~ ~ ~ -2 ar~* ~ ~ ..
o~z V -
-- --- - - = -
s S
.. SjIx 2 2 z a.7
uj C,
Z2
774
2'2
-3 SL :L
0 0.2
As ~ - --~ L. 'a- 'V
C .~ C22
-6
0% 0% 0-0 % -
999994 00 0 0%r. r 0%
we 0 0 000 r-4 r4 -4 0fu000)4.1 0 4.1V. M 00idi00 0 00 00 04MV0 r r. $4 i$~4 $4 0 00 k.dk-4C
4n.V W4 r4 4b44k QQQ lk p N A A N
0 $0
0
5.44
I0 000 00 0000% V.5 455. 5444 54.5
C 0.0
to0 m c-- 3c0 go09C -4C0 .4 Hx a 0
04 -r 0 0 0 V0 P ) -0V0 00-4-4-4- k 0-4V "4 0 0
0 -- I"4. VV VOw V0 4.0 Z A00 0 %,o VV 0 0 $ 4 01
V0 4 0 0 go N0$a *-N m e -4 N k * go, 0w-mm 4 4 1 0~.41 o-. X" 00 4.1k
to0 r. AwC Ow~ %moH go 00. "p -4 0 00000 0-4 go go%.w o 0 0f
04 0oV s0 445 O"41 *.05 E0 5
a0>, 0 0 41. 0-00 040 W4 000 41 $4 00 0000. %- b b-b%$4 *w 0 -40 $
-P 4 X X0 X X r4 X4 0..04 *. V0 0 V 540 ja %-w :2 0~ 00 V r
0.. ei4 a 4 .. X. 15 Ce z . es 2 .2' We V' 1 00 0 00a0 W44 a *f +1 0 V A O0Er $4 6=04 P>m 4 V X Zi c~ 0c We~ pa. 0 E- -4 VV
044 0 XX OX r 0 00-V V 4 Ca $ -4 -C4 CX C4 C CCC C - 9C0 c$44DO 544 00X0 ooX 00b'41 0o door.
Ow-HE L*- 041 00- %-9- -- - - -A0 41 , 9- " r
0-4 V 0 0 0 0 ::0 0 0 ( V U0 V0 0 0 0.466 v 4 0 c c6 +Ic N 'V c05 c c "4"4 9C$ O
0 0 0 4) 00V go~ 4%4 " 4.4 %4 U14 U 44 44 U44 44 > VZrZ V
QCa'baQe aoo2 rr&I=rtCnI L.
;-P0 rra.ction NCOc is arrav%1..2 ot inreqors-
IacKaqe LntIGT is& ftSw ruxtLU. Lnzwger_13(&nteqeri4
runction fakeractin.N. 0 x inteqerp return Fraction isF a Fraction;00qin
ii D Ift 0 thenF a- new FractionNoom:
*- or tractionst %. 0. the numerator carries the negative signmot. x4 D '% 0 tnr.
PCI) s-N:
*no tit~return Pt
OI soraise Zeroi~enomanatorE-rors
eno It*:
'unction MjmerA a Fraction) return inteqew- as
return A(1)saend hwser;
runction DewaoeA a Fractioni return integer is009&n
return A(2)tend LIenoo:
proceoure Put(A t in Fraction, isoeoin
lnt_1O.Put(~aNemr%%),4);Teu't10.Put Cu/"P1
Int.10. PuAt(Den.. iX) *I);Text1O. Put (*h tlerie a;
eno Put$
tunction aCD(X. Y t Integer) return Integer isbegin
ti V - 0 thenreturn ka
return iGCD(Y.A 000 '1):end ti I
Ono SCIDa
Pr.LCCLur* SfepoA. t 3 anl out Intoeri-,
arocedure S~e4pd, v e sn out integer)i inTemp S Inteverfoeg in
tam 1wactidmUma Is
- ~ia- MSEM Ieu lamte t- 0 uag..O:ae
tintim~~ l~taim3 3 2a Ma~ e Fraction L&F I fractions
-v $;o - Vzetim wafts- wfractiam 0, 6 h smmwmtor Crriamft aa "V @Lousi
if 0 4S =IP.MBtC~ 1- -91V.Dimlmtr s- -0:
V.-umt~ I- no
am aeetims
fintia. W~w(X t freatm) getarn integer isbein
roetg 1. Smarmtor;
ftwatim Dee(li acstion) return lataga is
ve~ I . Denmiatour
Izw Pat (Z a in fttim) isbein
TMEs I0.let(/):rut !O-fveenumz,i),
function a(x. I aInatw) in~lteger 19bein
If T -a tbmretur Is
frtarb WM(II a" T):
peireO6"MM ~(Z. T a In Mt 1atW),
aeoneave &no (Z. TI In mat iate) I0
TWO I- Ii1 I- Tot
Cumatim memme I Fraction) return Traction isa. 6 3 Intger
9 MW(MMr X))v a.me(mmuI)I.S 09tm
SOMPOD) I
ami uom
ftnation veciproall (: Fract ion) -etmn Fract ion is
function 0+ (X, T Fraction) return Fraction ISbegin
return Reduce Uabaftactio(rmor(X) -Daum (T) +Wwr (T) o* ns(Z),
and 6+0 1
efuntion O-(X t action) returnt Fraction isbegin
bsn(x)*Don(Y)) )
func ion '(X : acation) return Fraction inbegin
return R.educe( smkeFraction (ar (X) aowemr () , Damu(x) scumnn(y))and 1*01g
function a/O(2,, T 2 Fraction) Return Fraction isbegin
return Reduce( (X*%ciLrocn.L(T)) itend 0/0
function Equal (X, I : Fraction) retun boolesin isbegin
return rmorM *Dean=(M - MnrM*oa Xand Iqual.
function mc*(X, T Fraction) return bolen isbegin
return -c(Xein1 W' sr()*Csnow(X);and 6-u;
function 6 -O(2. T Fraction) return beeson Lubegin
return ptaer(x) eOmn(y) 3- saary) O (X) I
function 2wesoimam t1 Fractin) ae nlest Inbegin lsmvW))/
f~~tJ- -tW Weni( W I ~ u Fraction is
begingem beteti(Ilo
an resm lawro/atew,
and Fratiu
package MANAGER istype PASSWORD is private;NULLPASSWORD constant PASSWORD;function GET return PASSWORD;function ISVALID(P in PASSWORD) return BOOLEAN;
privatetype NODE;type PASSWORD is access NODE,
end MANAGER;
package body MANAGER istype NODE is range 0.. 7000
end MANAGER,
- , " +, o . ,.= !}.'. -" - - ' ' .- / - , I -- ,'
0 Reason private types must be includedin private part of the specificationrather than put in the body of a packageis that compiler needs to be able todetermine how much storage to allocatefor instances of private types declaredby client modules.
O "Inclusion of private data types in thepackage specification implies that achange in representation of the privatedata type will require recompilation ofthe program unit which contains thepackage specification, thus violating theprinciple that package specifications arerecompiled only when there arespecification changes which affect theuser. This appears to be a very heavyprice to pay for the simplification incompiling and loading that is achievedby including private declarations in thespec if ication part. "[Taken from Programmingwith Ada by Peter Wegner]
Using a Package
O via textual inclusion in theclient module
C package has NOT teen separately
compfled
0 package is visible in clientfrom the point it is first declared
0 spec and body do not have to be
textually contiguous in client but
spec must come first
[] via context specification using
the "with" clause
o package has been separately compiled
and is made visible via the *with* clause
0 this method supports ideas of modularity
and localization better than textual
inclusion method
o must prefix references to items with
the package's name and a period
G necessitates prefix form of notation
for use of an overloaded operator
such as 4+* or '-, etc.
0 can use 'renames" clause to allow
use of operators in infix form
0 can use *USE* clause to gain direct
visibility to items in the package
o use of "USE" clase can create
ambiguity and pollute the name space
Cl Both methods import ALLelements-of the visible part
of a package -- no selectiveimportation such as inModula 2 -- argues forcarefully segmenting packagesto achieve same effect
procedure COMPLEXLCOMPUTATIONS isprocedure ONE,procedure TWO;package COMPLEX is...procedure ONE is...procedure TWO is...package body COMPLEX is...
X, Y, Z • COMPLEX.COMPLEXNUMBER;begin
Z := COMPLEX.+"(X,Y);end;
with COMPLEX.procedure COMLELCOMPUTIATIONS is
procedure ONE;procedure TWO.procedure ONE is...procedure TWO is ...
X, Y, Z COMPLEX.COMPLEXNUMBER;beginZ : COMPLEX."+'(XY);
end;
with COMPLEX, use COMPLEX,procedure COMPLEXCOMPUTATIONS is
procedure ONE,procedure TWO;procedure ONE is...procedure TWO is ...
X, Y, Z : COMPLEX.NUMBER;beginZ:=X+Y;
end,
Affil
PaCkage GOLF-INFO Is
type G-CLFCLUB is (DPI VER, IRON, PUJTTER, WEDGE, MASH!E);type GOLF-SCCPE is range I 2CC;type HCLENLM1EE. is range 1 1 8,type HANDICAP Is range 0.. 36,type SCCRE-DA.A 1s array (HC'rLENrL5E) or GCLF-SCCRE,PAR...YR..CrCUR5E : constant GCLF-5CCORE := 72;PAP-V.ALUES: constant (5C'_RL.DATA:
(I =) 5, 2 > 3, 3 = > ', 4 = 4, 5 > 3, 6 > ~
13=> 4, 1-4 5, 15=> 3, 16=> 4, 17=> 4, 18=>_;
procedure CrUTTT CRECRE:in SCCRE-DA-1ATOTAL.- out GOL-SC.RE);
end GOCLF! NFO;
package body GCLFINF0 Is
procedu*re "Ct.PUITE-TCTAL-SCRE(-CCRES. In 5CORLDA7A,TOTAL. out GOLF-50GRE) is
b eg, nTOTAL := 0;-for FiCLE In FCLELr8ER loop
TOTAL :=TOTAL + 5CCRES(HOLE);end loop;
end;
end GOLF-INFO;
[Taken fromn Ada. An7 Introduction by Henr/ Ledgari1
with GOLF-INFO, TEXTIO;use GOLF-INFO, TEXTIO;procedure KEEP-SCORE is
MY-SCORES SCOREDATA;TOTALSCORE GOLFSCORE;
begin
PUT(Let's have the scores for each hole.");ror HOLE In HOLE-NUMBER loop
NEW-LINE;PUT(HOLE); PUT( ");GET(MYSCORES(HOLE);
end loop;
COMPUTLTOT AL_5CORE(MY._SCORES, TOTALSCORE);NEW-LINE;PUT('Your total Is *); PUT(TOTALSCOREJ);
NEW_..LINE,It TOTAL-SCORE < PAR-FOPCOURSE then
PUT(PARFORCOURSE - TOTALSCORE); PUT(" Under Par");elsIt TOTAL-SCORE = PAREFORCOURSE then
PUT("An Even Par");else
PUT(TCTAL.SCCPE - PAP,.FO._COUR5E); PUTC Over Par);end it;
end KEEPSCORE;
[Taken trom Ada: An Introduction by Henry Ledoardi
procedure OUTER ispackage HEIGHT is
ID INTEGER,VALUE FLOAT,
end HEIGHT.
package WEIGHT isID :INTEGER,VALUE: FLOAT,
end WEIGHT,
procedure INNER isuse HEIGHT, WEIGHT,
beginHEIGHT.VALUE := 65.3.WEIGHT.VALUE = HEIGHT .VALUE,VALUE := 63.5; -- unqualified name causes ambiguity
end INNER,
beginVALUE 6,3.5 -- illegal because outside scope of USE
-- statement so name must be qualifiedend;
[Example taken from Programming with Ada by Peter Wegnerl
L As
PROGRAM 3.8 Modula-2 Version of Program 3.7
(.This definition module is a separate compiland and iscompiled before the program ReverseName is compiled..)
DEFINITION MODULE Stacks;* SSEG:=8; e)('This is a compiler directive required by the particular operating system being
used. It assigns a segment number of a definition module. In general, this isnot required. *)
EXPORT QUALIFIED~ (°type -) Stack,
(aproc -) Empty.
(-proc -) Pop,(a proc -) Push,
(- proc -) Initialize,(-proc -) Remove;
TYPE Stack; (- Representational details hidden -)
PROCEDURE Empty(S: Stack) : BOOLEAN;(-Returns true if stack is empty..)
PROCEDURE Pop(VAR S Stack) CHAR:(- Strips top element off stack. *)
PROCEDURE Push(VAR S. Stack; X. CHAR);
(, Adds element to top of stack. e)
PROCEDURE Initialize(VAR S. Stack);(- Sets stack to empty. e)
PROCEDURE RemoveVAR S. Stack);(* Removes stack from memory. -)
END Stacks...... ..............................
L1..
u-A
L 0 u-
UU -
- ** LLI
"a u 0 x
-J 4c IL.UwM .. 0.
z 0 0
0 0 U) 3z N Z z 4c z a
z*w CL D -004 0 E. k E Oc5
-) 0 U) . 0. --
c z i. 0 0 ; CC L5 cc C w* j W ) wj uj U) 0 l _j -
E 0 0 z C UJ L6- uj 'U1, u* i IU c 0 0. Eu 3: LuLL
-J U. U. Ue oQ o i CI. uj z zU
IL. -MLU
cm
-C T
0I
CL E00 u
M .20
U *
-~- j
li - Ai2a U)I
>~ E c
e . ~~ . U~ > C
.t < :-J.aE >- w* q. " 0
u 0 LL m E rz 0a n i L . r o L. u~W
uj 2Oa 0.222 a o- u*o;0= E cm -0 vi 00 -u uK CCr uC
-a a 06 0 0 0 0. 0 85 5
0 IL < ) c-j x I I c -- a'0, ujI I L L
MODULE ReverseName; ( This is the program. a)
(In Modula-2. all reserved words must be given in uppercase. a
FROM Staciks IMPORT Empty. Pop. Initialize, Remove, Stack.
FROM InOut IMPORT WriteString. WriteL-n. Write, Read, EOL:
PROCEDURE Find Middle (VAR S. Stack). CHAR,(a We use an algorithm different from that in Program 3.7.a
VAR LocalStack: Stack,ch :CHAR.-
BEGINlnitialize(LocalS tack):REPEAT
ch: -Pop(S);-Push(Local Stack, ch);
UNTIL ch-ch:=Pop(S);Push (LocalS tack. ch).(* Now we restore the stack S to its original form. a
WHILE NOT Empty(LocalS tack) 00Push (S, Pop(L ocalS tack));
END;RETURN ch
END FindMiddle;-
VAR Name :ARRAYE1. .401 OF CHAR;A :Stack:
R r r o~r~a Ir OL)eC'L
Limitations onStructure Specifications in Ada
0] No support for declaration of structuregraph interconnections at specificationlevel
0 Can include this information withcomments as an alternative
package C isrequired(DE);is required by (At);procedure C I ( .);procedure C2( ...
end package C;
[Taken from System Design with Ada by R.IA. Buhr]
. .... ....... ..... . . ,la =mm ma
Package Applications
0 Encapsulate related data types,constants or objects.
0 only objects and types exported, no pgm units0 package body may or may not be present0 facilitates consistency by factoring out
common elements used by may modules
0 Encapsulate related program units.0 only program units exported, no objects
and types
0 Embody an Abstract Data Type (ADT)o objects, types, and program units exported0 state information not maintained in body of
the pkg0 supports abstraction and information hiding
0 Embody an Abstract-state machine.0 objects, types, and program units exported0 state information maintained in body of pkg
C Encapsulate tasks.*0 often used purely to enclose task(s) because
they cannot be separately compiled
VY
.ni
u
oac:xage TRIGPK- is
function FACTORIAL(n: in integer) return.ca-:
-- returns n' as a float inc point value
function SIMPLIFYianale_ in-degrees : in integer) return intecer:
-- returns an equivalent angle (in degrees) for ANGLEIN.DEGREES
-- which is positive and between 0 and 360
function RADIANS(degrees : in integer) return float:- returns radian value for DESREES
function SIN(anglein degrees z in intecer) return flcat;- returns the sine of PNGLEIN DEGREES
function C3S(ange _ir._degrees : in intece-) -e-rn-- returns the cosine of ANGLE INDE3PEES
end TRIG_PKG:
package body TRIG PKG is
FACT arrav(O.. 5, of f'oat
(i.0.1.0.2.0.6.0.24.0,
120. r.720. 0,5040.0,40320. 0,362980. 0,
3628800.0,39916800.0,479001600. o,
6227020800. O,8717829 12Zo. 0,1307674368000. 0:
funct:on FACTORIAL(n: in integer) return float isx : float := 1.0;
begi nif n ( 0 then
-- if r, is NEGATIVE return ZERO to indci:-e EO_ -
return 0.0;
elsif ((n >= 0) ard (n <=15)) thenreturn FACT(n);
elsif n ) 15 t.enfor i in 1..n 1,-op
x := x float(i';
end loop:return x;
end if;
end;
function sI~IV.n~idg~s:in inc~nger) return intwgwr is
angle integer
angle ;angle~indeqrws rem 30
if angle (0 thenangle ;-360 - angle;
end if;return angle:
*nd ;
,unc-:ion RQDrANSeqrwvs: in-i ntae- r,-g.irn -clat is
pi:float :- 3. l-1326z:begi1n
return' ( (~i /float (l180) ? :oat (amq-aes;end;
f tnction S:N(an~eixn~eqr. I in ittene l-e-: 1- i
sum : float :- 0.0:angle : intege-;
temo~anq..e :inteqe-;
te'no angle:- S t l PL: :n14 temo aq, S la0 t."*n
anqle to,,oangle - !e0:
angqle tomo _anale:end if;
fon I in 0..7 locoSum :- Sum ?,. oat'- i) *
end loco;
-Account for use of only first anc secoDnd quadrant ang~es
-- in eofflutat ionif te-o angle ) 180 the,
return (-sum);
*Sreturn Sum;and if;
and;
f'nc-on -_S nmq~eLr_!q-es :in intwer) r-..n~n '!oat is
sm:f'oat :- 0. *;
angle : intoeo-:temo-anqle Int.eqlr;
begintemp angle ; S:PLIP anleiwndeqrees);if twma~anqe >- 180 then
-- First and second quadrant anltt -ised forn c-itnostat.on
-- bMC-3Ul Ch)mG',tjtiOn iS te aCC~jrate
angle :~te~oanqhtr -180:
.an ql teoi~nqLui:end I f;
for i in 0_ 7 lonO
sum :- slim - fb(W-i ( (RmorANs(.anqle.-'./ ( F.ACT~a. 1 ) C
end loco:
-- AC=Ount for uwse Of On1'Y ftr-t aro seco3nd a-iddrant anr~ws
-- in comoutat ioni' temo anqle >- 180 tnen
rot urn (-Sum Ialso
e t urn Su~m:
end i'1;
nd;
end TRIG-O4(G:
-'V . ...-- -- -"--.. - -.
with TR:G PKG. GGI_ GRAPHIS S_PW. T YPES:
use TRSGOXG. GIGI GRPaw!C_OKG. Tv0FES:
package TURTLES is
subtype ANGLE is integer range 0..360:
type TURTLE is private;
TURTLE CONTROLS --
- PEN CONTROLSprocedure UP(myturtle : in out TURTLE):procedure DOWN(myturtle : in out TURTLE):function PEN IS-DOWN(myturtle : in turtle) return boclean;
procedure NEWPEN(myturtle : in out TURTE: colour : in CCLC RTYE):
- MOVEMENT CONTROLSprocedure NORTH(myturLe : in out TURTLE):procedure SOUTH(myturtle : in out TURTLE);procedure EAST(myturtle : in out TURTLE):procedure WEST(myturtle : in out TURTLE):
procedure MOVE(myturtle : in out TURTLE; r : in integer);procedure TURN(myturtle : in out TURTLE; a : in ANGLE):
procedure TURNTO(myturtle : in out TUR=LF: a : in ANGLE;
orivatetype POS:-=ON is (oen_up,oen_don):
type PEN is record
oenoosition : POSITION;pen_colour : COLORTYPE;
end record;
subtype XCOORD is integer range 0..768;subtype YCOORD is integer range 0..479;
tyoe POINT is recordx : XCOORD;
y : YCOORD;
end record;
tyme TURTLE is record
pen status : PEN := (pendown,white);headino : ANGLE 0;
location : POINT :=(350,20);
end record;
J TURTLES;
----- - --- - ----------- - - --------------------------- - - -- - -- - -------
package body TURTLES is
-- TURTLE PEN CONTROLS --
procedure SET PEN COLOUR(mturtle : in out TURTLE; colour : in COLORTYPE);procedure SET PEN_COLOUR(myturtle : in out TURTLE; colour : in COLORTYPE) isbegin
myturtle. pen status. pen colour := colour;end;
procedure NEW PEN(myturtle : in out TURTLE; colour : in CCLRT'e_. , isbegin
SETPENCOLOUR(myt,,rtle,color) ;end;
function PEN_IS_DOWN(myturtle : in TURTLE) return boolean isbegin
if mytur e. ._en-staaus.oenoosi-i-.on = pendown t.ienreturn t--ue:
elsereturn fal.se:
end i f:end;
edure UP(myturtle : in out TURTLE) isbL-lin
myturtle. penstatus. Denposit .on := pen_up;end;
procedure DOWN(myturtle : in out TURTLE) is
.vturtle. oen status. pen position := pen down:
-Ask
-- -IF - - -- - -- - -- _--_ - -
-DRAWING and UN-DRAWING th~e TURTLE -
rocedure TRANSFORM(myturtle :in TURTLE; x :in integer; y :in inteSger;newx :out XCDORD; newy :out YCOORD;theta :in ANGLE);
rocedure TRANSFOPM(myturtle in TURTLE; x in integer; y :in integer;new-x out XCOORD: newy :out YCOORD;theta :in ANGLE) is
eginnowx mfyturtle. location.x 4-
inteqer(f.oat(x)*C0S(theta) float,',./)*S:N(tneta'newy my1ur.le.11ocation.y +
innecer(fl oat (x)*S:N(thet a) + >at .'*CCIS (,'et amd;
rocedure DRAWTURTLE(myt'rre :in TUR7LE):rocedure DRAWjTURTLE(mytaur:e : in TURT LE) is
x,y :integer;egin
SETWRTINGMCDE~relace);SETWRTINGCOLOR (mytrle.e"_sa'. ec.~SETCRSRAT(myi;.rte. ocar.-on. m.m iy>r a. :~~nTRANSFORM (mytute., -1-8, x,, yurtI. mead:rncDRAWL INET (x, y I:TRANSFORM (mturtis, 24,0. x,v.
AWLINETO(xc,y);RANSFORM(myturs 1., 0. 18,9 X-y,
myt urt Ie. head ing);DRAWLINETO(x, y);TRANSFORM (myt urt le, 0, 0, ,
mytuirtleheading);DRAWLINETO (x, y);cT(7L'RSDRAT(myturtle. location. x,myturtle. locat!.on.y):.
.n, *4.
- AJite UNDRAW TURTLE (myturtle :in TURTLE':
"---'ure UNDRAWTURTLmyturtle :in TURTLE) is
:'z7W,1 I r INGMODE (er.3se);
SETCURSORAT (nyturt 1.. locat ion. x, myt urt le. locat ion. y);TRANSFORM~myturtlO,-1x,y,ryturtle.headi-ng);DRAW1 'NETC (x, y) ;TRAI j M (myt urt 1.e, 2 4, 0, x, y,
myt urt 1ie. head ing)DR%; -INETO (x, y) ;
TRANSFOPM Oyt urt Is, 0, 18,01 ,myt urt 1ia. head ing);
DRAWLINETO(x, y);IWNSFORM (myturts, 0, 0, xvy9
myturtle.heading);DRAWL INETO (,y) ;SETCURSORAT (myturt is. locat ion. x, myturt 1.. locat ion. y);
-- 7UR'rLE MOVE.rENT C3147RCLS --
procedure MOVEmyturtlw : L out TURTLE; mn in integer) isbeg in
UNDRAWTURTLE .mytur-tl*);if PFNISDOWN(myturtlw) than
SETWftITINGMODE~roplae);SETWRITINGCOLOR (myturt is. gn status. pen colour);DRAWLINIETO(intge.( FI~()CS.Otrl~oc~c)
float (mytuitw. locatton.0~ ),integer( float (n)*SN(myturt.le.heading,-
float (myturt le. location. y) ))
MOVECURSOR~AS(intger.( float (n)-COS (mytuv-tl. Iadirmg)-float )aytuit I.. llocat,.on. x) ),
integer( float (n)*SIN~nmyturtle.headling)-.end if;float (myturtle. location. y) )2
GUERYCURSCRPOS(mfyt 4re I. location. x,..iyturt.9. :ecat~on. v)DRAW-TURTLE )ryturt Is);
end;
procvdAre TURNmy.~r.n: : in 3ut TUR-'.Z: a : in QNGLZ Lsbegi n
UNDRAW ITURTILE )ryturt*);
DRAW TURTLE (mvtur7 I.)jend;
prtcedure TURN TOrnvr rtla in o-t TUqTLZ: a in ANGLE- isbeg in
UNORAW TURTLEnlyturte);mytArtl*.heaing :. a;DRAWURTL(rnyturtIe,,
end;
pr-3cmdurm NORTH4(rnyturte Io in out TURTLE) isbegin
TURNrTO(myturt:e,?o);MO'JE(rytur-t X, I);
end;
procedure SCUTHrnyturtle zin out TURTLE) isbegin
TURN -TO~myturt!e, 2'O);MOVE (.,y turt ,a. I);
end;
procedure EAST~myturtlo in out TUIRTL_ isbeg in
TURN TO (myt urt . w.MOVE (nyt urt 1.. I);
end;
2rocwauro 'TS(ryure:a in ou TURTLI ~Sbegin
TURN TO(myturt :.' 16);MOVE ( myt urt , 0. 12
and:
-------------------------------------------------------------
beg in
SETSCREENSCALE(O.760, 470.0);CLEARSCREEN;
SETCURSORAT (0, 0);and TURTLES;
L.
0 u u .
0 U3 LI C
Z=I- I u 0-
9- 0. .
0l 0 w 0
-u I U
-- ~~~~~ u z a I- -zSS -
I. L AA A
LI a
> 3 1 -P - P - -
C , Cz . I. m ) - U.
_j 2 - uI ui * IL) ' U) a 10 w r
M w U) w > 0n I T_I P.- I - 1 )->
LI m L C I- I I- 0 Ln
.4 - Z - LIX Li Z m
w j. a0 I x U) 0I 3 - a >0I (- c~ En 0 9- 0
me, w Li9 0
0 CLI .0 m0 00 u q). : c 0 u
- >. C I I . U C do
CL .0 C'
II-0 0
CL CL CL Cu l l (D a
Ci ix I. h.w
- i - >
I wa u1 u 0 0
Uw w x LI C j LI a
C? L L 1 1 01 C c
a)I al at - W x
0 0 w>u
.X L L 0 W cu a W Ca Ca 0 v
M. I Ca C ? W c?C? ?L - 0
package Termi nal0r iverPackage is
task Ternminal_..river isentry Read..Character(C :out Character):entry Wr ite-..Character(C in Character):entry Reset;entry ShutDown:
end Terminal-.Driver;
end Termlnal-DriverPackage:
with QueuePackage. LowLevel_10, System-,use LowLevel_10;
package body Terminal...DriverPackage is
task body Terminal..Driver is
-- Group all of the machine dependent C -s:!-ts together
ConsoleI.nputVector constant System. A.-:.sS :2 8#60#;Canso leOutputVector :constant System.A.Tss 8#64#:EnableInterrupts : Integer :x 8#100#:Write TimeOut :constant Duration :a .:NumberOfLines: constant :a 2;LineLength: constant :- 132:
task type Device..Reader isentry Interrupt;
*entry StartUpOone:,for Interrupt useat Cons a Ienpu t_.Vecto
end Device-.Reader;
task type Devi ceWri ter isentry Interrupt;entry StartUp~one;for Interrupt use at Consoe..Output...Ve~t0:
end Device-Writer;
package CharQueuePackage isnew Queue22:e(Charactf'1use CharQueuePackage;
type DriverStateBlock isrecord
InputCharBuffer, OutputChar~uffer5lockingQueue(Number-OfLines-LiCa-ength);
CurReader Device-Reader:CurWriter Device Writer;
end record;
type RetToBlock is access DriverState~lock:CurState: RefToBlock;
task body DeviceReader isTempInput : Character;
beginaccept Startjp~one:SendControl(Console-KeyboardControl. Enable....nterructs):loop
accept Interrupt doReceiveControl (Console.Keyboard...ata. TempInput):
end Interrupt;Aope(CurStat2. outc~,ar~uffer Tm!rU
end loop:end 3ec e ,,e
T enp C utpu C, aracter;begin
accept StartUpOone;Send-Contra I(Con so IePi-interControl , Enab Ie...Interrupts):accept Interrupt; -- spuri'ous interrupt caused by Send _Controlloop
Remove(CurState.OutputCharuffer. TempOutput);Send-.Control(ConsolePrinterData, TempOutput):select
accept Interrupt;or
delay Write_Time_Out:end select:
end loop:end Device-Writer:
procedure Shut~own~ld isbegin
abort CurState.CurReader;abort CurState.CurWriter;DestroyQueue(CurState. InputChar~uffer);Des troyQueue( CurS tate .QOutputCiarSuf far)
end Shut~own~ld;
procedure StartUp isbegin
CurState :- new DriverStateBlock;Init_.Queue(CurStata. IrputCharguffer);InitQueue(CurState.QutputCnar~uffer);Cu rState.Cu rRe ader.S tar tUoDo noCurState .CurWriter. StartUoCone;
end StartUp;begin
StartUp:
ConsoleOperations:loop
selectaccept ReadCharacter(C :out Character) do
Remove(CurState.InputCharfluffer. C);end ReadCharacter:
oraccept WriteCharacter(C :in Character) do
Append(CurState.OutputChar~uffer, C):end WriteCharacter;
oraccept Reset do
Shut~ownl d:StartUp:
end Reset:or
accept ShutDown:Shut~ownl d:exit ConsoleOperations:
orterminate:
end select;end loop ConsoleOperations;
exceptionwhen others a>
Shut~own~l d:
end TerminalDriver;
r'.d Tq- i-a' C-- jer Package; ~ ~ ~ ~ K
Teaching Packages
0 Start at the PACKAGE level andthen introduce the syntax byexample -- NOT at the syntaxlevel and then intro packages-- good way to produce Fortranprograms written in Ada
0- Give students preconstructedpackages and have them builddefined products with them
O Have students play "client"package and package developer
0 Have students develop a largerscale system with packages thatmust interface
O Have students build a systemwhich has a heirarchical structureof packages
0 Have students do a package andreplace its implementation andobserve results
0- Give students package with "open"data structure in the spec andhave them corrupt its integrityand then challenge them to dothe same thing with a packagewith the data structure in theprivate part of the spec
0l Data structures course very easyvehicle for introducing packagesunder topic of abstraction
0 Digital design course offersopportunity to intro packagesto encapsulate abstract-statemachines and tasks
UL
Ao
(D,
-4 .
*- 0
'0l
coilC co
z C
C0Z N(E > z
CU)C l
I LU
>LL LUC. C
Ix w
0
z
0
z 0 w F
14 LL c!) W
I- Xz-1
<1 00 Im CD>-<r a x - N
F- 0 um Iu
mi a.W> a naW C z x
im 0 0
F-
0 )U) Ix (t) H a H
ci 0) 1- L
(r wx w wU) I Ji () c
2: (E c! w x T
Z : H 0 (.X
0c LU (E LUCLI "Ci 0. > H H
H N 0
0 0 LU
H f0 m
z
Wi Itr
i Z Li F- LiCm 0 J zu
>U() I '
w z
Ul) I- I-Li ( 0 0 I
a- Li. LL
0 1 L
w a w 0iL .
i OW 0oH W
Ir-
U) CO
I-0')
-3 W
H cr 0 W W1m: LL > LwC MZ
z -I
I:1 - Z WW ZIt
Z > LL w w ZV~ LL x 00IlLLI-
CD a. a Z
I- co , 0 >- ZII xM 0oit
Q n" w" L o ) Ln(]I-- U)WO ZZU
C co 0 W 0 HU- -IO 0 [
W0 Wa.O > C w
) ca 0o
J C i
0
a. 0 (1)
F- LU C U(I) It ( r1 1
C r - CEmz:) W, 0 WO xW
u :z F- a a.() Cm z a. C w 1 I
W Z x~ WO) (1 0F- 0 .W W 0 C () F- It()
X: z am z a z W .a. IC 1 Cm 0
Cl) w a 1 3a L 0<r. Im u u. wLIJ 0 0J
WOW cm 0 rm c z .cz
C0) m w c .JI ILOa 0 >m (J 0 - zu z i m awz cm E F14 H (E w w z C
Wm m~ LU j ) - 0:F- x c 0 F- C UF- X
(j) cmM <C " w 0LL c
u x w u0 u WI a UJ I-a CI I C
m --Iz H "I
OY. WI z
F - I
0- O) LUO n
Z s" I-. I--
0 Q.J
13z
in wcW Z 0
a. 0 14 C0
z 0
C LC)
o 0: > UZ (I '"II- I
w a C J(C
i I--
I0 H -3 LL <1H ZL_ I- Q
0>u
LL
I W> C>
IjI- 1- u
11- x w z
F- U z WZc
(X CLIm H Z - CC)F- 1-- .
* (w (E (1
CD I > 4K 4
W > LL u a0 Im m0 0L1 0UZ
z C0> > > W
x W F- w -I a 00 0
1WO-U (JO wu LWJ C LL WLLW w Wx x
F- W I-
.WES Ur
CD Saw
IL C .
PO .; 091
u
01 laaa
me zmiam
Amok
+
(I) (ILL
F-IU-F
-i LL V) F- -ZY0C U. C ~'0) rHt)
F- WoCCOaC WC
U). W)V)u)(fl w w E)r Ww uW i a. xw I W C.)Z
n It-U) w c 0 >1-(IIW Q) Qz LLJ 0w )Z U Z Z '
I J W Z W H, w(
0 0 u.F- Z LL '
CL
II
CL C
0 CL
i i - ! .c! _ , -
GB )
ci, ) '
ic
,i~lll[ I I
zJin cDWW Lii
0~~~~ (ZHHLJz ZWLLL F- 1Z 0 WF
ir H (4U) Ha0 IUC(. - W Z
F- co -. j Z 1C a ax ) CO W II x WCLd rI uL it F-
a. u Jz wo0rm x z w X0 H (Z 0 Lw 0Lwi 3 VC>a. > -OrC
H (:r n w - 0 Q U)F- G1) 0W WUCJ J U)
C C (j)U)WL u WO 1 WIa:I MU) c C LuI x
w :3 C z JU4 l u v LI Iv wu U1) U) 0 U) 0)itUx ) (1)wd Ci <1~ a:o oi (X0a0( I
Im - a. - LL LL Ci U F I-
I I I I I I I
z0 I
3-I wF- W F-Ci M Im- <E <m z w w z0 V. .j 1
w Ca m0.C. 0ai z ai 0 x tZ.jm w j0 W 0
w wCL) F- (z
task [type] [is(entry_declaration)(representation clause)
end [task simple_name] I
task body task_simplename is(declarative_part]
begin[sequence of statements]
[exceptionexception handler(exception-handler}]
end (task_simple_name];
14
UI)rw a. z
>.I- I-I- I- < C
IC U)C.Z Z i(I )C I
a. H w 10CDZ • _ .,'I" I-I - • * mj (J - - -
I 0 C • * W 3 ZZ .J 0 m I Z D 0 0i .J a. x -" 3 u
C (I~ cr w 0mL ) 0 C.) I0 0 0- Z 0 0 C. U Z
SZ z "I"() M
xC 0 0 .CL a: U). z J>
wW I a.~ -U
Z I-I iW 0 -P- . W i, u m
Q)O C. ZLU m ) I 0 w
w I (r j
SIMPLEST FORM OF TASK ENTRY
ACCEPTTASK TI is
ENTRY ENTRYl;END Ti;
TASK BODY TI isB EGI NLOOP
ACCEPT ENTRYI Do<SOS>
END ENTRYI;<SOS>
END LOOP;END TI;
--WAIT FOREVER FOR CALL To ENTRYL
16
-- o,,.,_ - -
0 CIM w
0 .o W L
do=% 0 9 . .. H
I "rW 0 ,)
x U) WW W0 *W z x
0f cC J0J
v m- J JZO
Ima.w C C.
z 0. E0cn, _)i- -" 0 i
f- - I U) < 0
Cl " I 1 0 (JSZ M ciWZ 0-.1 Ct w4O O 0zW
F- F- co J wQ
'4 > 14 0 Z 0 (I(j)m Io m , z
.. . ..W~w C mW Z
>- ww j I
0% aWl 0 U
WX 0 z.
o- F- o Jwz w
0. 0Ime 0 Z11 z 0
F- ml .ua o 0U)CV I .(J).0
0 CL u z l w
I- F-U u caJ w0 wDl z 110 w IJ.I
ww) w ) jm w X :c z iI
w -I
0
0 W10 w~
I-
w wI0i. CL C>- >- wFe- F-CE -
I I:
F-D F- <E F
z <E m
QDA. Cm .- 11)Z
0.. j -I- W )V-44 1E I- a ILu u a w a
W-l u w l w 0 CEOLI<E 0<E~3 WrO > S u j0 CL uC 01
F- O- L) ZIJ w Q
11z z 1 Dw z0www w 0)ijm w
z cLU F
TASK TI IsENTRY ENTRYI;
END TI;
TASK BODY TI isBEGIN
LOOP
ACCEPT ENTRYI; -- 'SYNC' CALL ONLY<SOS>
END LOOP;END TI;
--WAIT FOREVER FOR CALL TO ENTRYI
--EVEN IF ENTRYI HAS PARAMETERS ASSOCIATED WITHIT, THE ACCEPT BLOCK DOES NOT HAVE TO HAVE ASEQUENCE OF STATEMENTS
20
Amlh
SELECT STATEMENT
USED BY THE TASK TO ALLOW OPTIONS
SIMPLEST FORM IS THE SELECTIVE WAIT (WAIT FOREVER)
TASK Ti isENTRY ENTRY1;ENTRY ENTRY2;
END T1;
TASK BODY T1 ISBEGIN
LOOPSELECT
ACCEPT ENTRY1 DO
END ENTRYl;<SOS>
ORACCEPT ENTRY2 DO
<SOS>END ENTRY2;<SOS>
--AS MANY 'OR' AND ACCEPT CLAUSES AS NEEDED
END SELECT;END LOOP;
END TI;-- WAIT FOR EITHER ENTRYI OR ENIRY2
21
SELECTIVE WAIT WITH ELSE (DON'T WAIT AT ALL)
TASK Ti isENTRY ENTRY1;
END TI;
TASK BODY TI usBEGIN
LOOPSELECT
ACCEPT ENTRYI Do<SOS>
END ENTRYI;<SOS>
ELSE<SOS>
END SELECT;END LOOP;
END TI;
IF THERE IS NOT A CALLER WAITING RIGHT NOW,DO THE ELSE PARt.
22
SELECTIVE WAIT WITH ELSE, MILTIPLEACCEPTS
TASK TI IsENTRY ENTRYI;ENTRY ENTRY2;
END T1;
IASK BODY TI isBEGIN
LOOPSELECT
ACCEPT ENfRYI DO<SOS>
END ENTRYI;<SOS>
ORACCEPT ENTRY2 DO
-- AS MANY 'OR' AND 'ACCEPT' CLAUSES AS NEEDED
ELSE<SOS>;
END SELECT;END LOOP"
END TI;
23
SELECT WITH DELAY ALTERNATIVE(WAIT A FINITE TIME)
TASK BODY TI IsBEGIN
LOOPSELECT
ACCEPT ENTRYI DO ....[ORACCEPT ENTRY2 ..... I
ORDELAY 15.0; -- SECONDS<SOS>;
END SELECT;END LOOP;
END TI;
IF ENTRYI CALLED WITHIN 15 SECONDS,
THEN YOU ACCEPT THE CALL. OTHERWISE,AFTER 15 SECONDS YOU WILL DO SOMETHING.
24
'DELAY' RULES
YOU MAY HAVE SEVERAL ALTERNATIVESWITH A DELAY STATEMENT.
SINCE DELAYS CAN BE STATIC, THE SHORTESTDELAY ALTERNATIVE WILL RE SELECTED.
ZERO AND NEGATIVE DELAYS ARE LEGAL.
You MAY NOT HAVE AN ELSE PART WITH
A DELAY, SINCE THE DELAY WOULD NEVERBE ACCEPTED.
25
'DELAY' RULES
YOU MAY HAVE SEVERAL ALTERNATIVESWITH A DELAY STATEMENT.
SINCE DELAYS CAN BE STATIC, THE SHORTESTDELAY ALTERNATIVE WILL RE SELECTED.
ZERO AND NEGATIVE DELAYS ARE LEGAL.
YOU MAY NOT HAVE AN ELSE PART WITHA DELAY, SINCE THE DELAY WOULD NEVERBE ACCEPTED.
25
-.[_. .. -' - .--w -+ -,.. .~ . - -.-- I - , ___.. .... + . . .. .. .- -
SELECT WITH DELAY ALTERNATIVE(WAIT A FINITE TIME)
TASK BODY Ti is
BEGINLOOP
SELECTACCEPT ENTRYI DO ....
[ORACCEPT ENTRY2 ..... I
ORDELAY <EXPRESSION>;
<SOS>;O R
DELAY <EXPRESSION>;<SOS>;
-- SHORTEST DELAY WILL GET CHOSEN
END SELECT;END LOOP;
END TI;
26
GUARDS CAN BE USED ON ANY ACCEPTSTATEMENT
WHEN SOMECONDITION =>ACCEPT ENTRYl ......
IF THERE IS NO GUARD, THE ACCEPT STATEMENTIS SAID TO BE OPEN.
IF THERE IS A GUARD, AND THE WREN CONDITIONIS TRUE, THE ACCEPT IS ALSO OPEN.
FALSE GUARD STATEMENTS ARE SAID TO BE CLOSED.
OPEN ALTERNATIVES ARE CONSIDERED. IF THERE ISMORE THAN ONE, THEN ONE IS SELECTED ARBITRARILY.
IF THERE ARE NO OPEN ALTERNATIVES (AND NO ELSEPART), THE EXCEPTION PROGRAMERRO1R IS RAISED.
27
I H 95-
TERMINATION
WHEN A TASK HAS COMPLETED ITS SEQUENCE
OF STATEMENTS, ITS STATUS IS COMPLETED
ADDITIONALLY, THERE IS AN OPTION THATALLOWS A TASK TO TERMINATE.
SELECTACCEPT ENTRYl DO .....
[ORACCEPT ENTRY2 DO ..... I
ORTERMINATE;
END SELECT;
THIS MAY NOT BE USED WITH EITHER THE
THE DELAY OR AN ELSE CLAUSE.
SINCE THIS IS USED ONLY WITH A 'WAIT FOREVER'TASK, THIS OPTION ALLOWS A TASK THAT ISWAITING FOREVER TO TERMINATE IF ITS PARENTIS ALSO READY TO QUIT.
28
r4
EHLz
((U
7-4.
[Li 'U
(UU
w0 .n
M- U
w ~w >>) x- rZ LL
W Z z x.J>- I-I 0 w
Wn W- ID0w
ciw F
ci C 0 0 0W ~W imn m
ED II W a-z z J I U~
t ZW J ->I CLH4 .i* W) wi
u.4 EU ZU) L) 0
W LL >~ U- u I
U) E)- xa.>C-0U) W C
I- Z LL ZE ~u -0 J w U
ZZ W Ur I-taW C U) coI -~ 0 ZI- U) a.IF- m W>
LU 0 m0 10 'I - I- I-
<ErI-
W ~U) WSW WW, IlI ~,
w I w I .J0 W I Z w 00I-. Z -I-Z W
0 1 nE 0 : z-
W L (D .- <[Li. Z: ZW 1 11 W
O 1 0 -
W w ) X CZOW c 0 Z
wj a- a. P4 -M H
1 0- o 3 w LJ - x -X
(O LO 0
Q W 0 oa x
Z it U)I C I .M C P4 <1 I di
I -I Z)
Jl- U)LL I
I I I I u I hI 0
IlI I I a I w I- J
1> Wa.
0 w O
z a. w Z: IY.Q 04 0 0
a w J w zw
CL
z 0 w w -
U) W I - u C)
z (E ~ H - 1 0) LU
ClE WOW) z U:. u
00 LLu0U)0 wUH U L w
00 U) (r z00-Q W H JZ
0.E x 0 JWLU Wfl F-uU)C c
U) J 0 w0
w m-ZW xrit1- MUZ X C x (j)
I >w I io w r14 )> i U) i
cr. w I X:a. w 0a. I o (E U 3
3 W W Xaw 0 >
Su a0W w r LX z z
E a.W 0
- - -~.Y--~-- ~ -~ --- - ----- - - -
zI-'
o II- I-
fr- -~L) IWWCD', 10
WIow
W Zz
oWOO N
I-CD
zww m~WW Wuu~
(Jo '-4
W~z 1-CDw 0~mJ~
IOCOmI~I WW0.1- (11-10 UwU
Co w
TASK SEMAPHORE isENTRY P; --GET RESOURCEENTRY V; --RELEASE
END SEMAPHORE;
TASK BODY SEMAPHORE isAVAILABLE :BOOLEAN :=TRUE;
B EG I NLOOP
SELECTWHEN AVAILABLEACCEPT P DO
AVAILABLE :=FALSE;END P,
ORWHEN NOT AVAILABLEACCEPT V DO
AVAILABLE :=TRUE;END V; -
ORTERMINATE;
END LOOP;END SEMAPHORE;
32.1
TASK SPECIAL ORS ISENTRY ASSTGN ( OBJECT : IN SOME TYPE );ENTRY RETRIEVE ( OBJECT : OUT SOMETYPE);
END SPECIAL_OPS;
TASK BODY SPECIALUPS ISTHEOBJECT : SOMETYPE;BEGIN
LOOPSELECTACCEPT ASSIGN(OBJECT:IN SOMETYPE)DO
THE OBJECT := OBJECT;END A-SIGN;
ORACCEPT RETRIEVE(OBJECT:OUT SOMETYPE)DO
OBJECT := THEOBJECT;EN!) RETRIEVE;
OR
TERMINATE;END SELECT;
END LOOP;END SPECIALOPs;
33
Ir LLz w>- F- W
w 0It (:J ->0 xC <1
(I (I)-- ) > (F- WI a. Hj Hi
(E Ci .J LL F'I F- I (
ED a wWIZ x W U) > . 1
.4 J z I Ji Z- OZ
U GI) wa
> - x Zw w Z H 0
Z I Wr w - UW F-w
I IX I-
CALL AND WAIT FOREVER
To CALL AN ENTRY, SPECIFY THFTASK NAME AND THEN THE FNTRY NAME
BEGIN
Ti. ENTRYl( DATA )
35
TIMED ENTRY CALL(WAIT FOR A FINITE TIME)
SELECTTI.ENTRYI(DATA);
OR <SOS>
DELAY 60;<SOS>
END SELECT;
YOU CANNOT USE AN 'OR' TO CALL TWO (OR MORE)TASK ENTRIES!!!
THIS WOULD BE EQUIVALENT TO STANDING IN TWO
DIFFERENT LINES AT ONCE-
36
Job...,.
CONDITIONAL ENTRY CALLS(DON'T WAIT AT ALL)
SELECTTI.ENTRYI(DATA);<SOS>
ELSE<SOS>
END SELECT;
NOTICE THE 'ORTHOGONAL ITY' OR THE
SELECT STATEMENT. IT IS USED INEITHER A TASK ENTRY CALL OR ANACCEPT STATEMENT.
ALSO NOTICE THAT INSTEAD OFI ACCEPT"••BEGIN... END ACCEPT;
IT IS'ACCEPT...DO .... END ENTRYNAME;
WHY???
37
w zJW H)WaZW
W -ZW Z
wu HZ W ZO0
M) > LL 0ZZ 0a 0H~ LUZ
o)II Z LL y
z IW ) (EZW C F
1-:3 j m L Z 0tY- L.L mI-c
wI
I I I
z 1-
'3:w 0U I--
1'- - W
zc
Z CDLLLJF - > C ZQ
ui w I.-
z w
Uw w r w zF- Ca) W >- I
F-W W W4
W I - L)0
1i 1- 0: 0>i II >D 0I~
0U wCU (0 c! -
0. OWO0D 1_4NZ
SYNCHRONIZATION OF DATA
TASK SYNC IsENTRY UPDATE ( DATA : IN DATA TYPE);ENTRY READ ( DATA :OUT DATATYPE);
END SYNC;
TASK BODY SYNC isLOCAL : DATATYPE;BEG I N
LOOP
SELECTACCEPT UPDATE(DATA rN DATATYPE) DO
LOCAL := DATA;END UPDATE;
ORTERMINATE;
END SELECT;
SELECTACCEPT READ (DATA OUT DATATYPE) DO
DATA := LOCAL;END READ;
ORTERMINATE;
END SELECT;
END LOOP;END SYNC;
40
FAMILIES OF ENTRIES
TYPE URGENCY is (LOW, MEDIUM, HIGH);
TASK MESSAGE isENTRY RECEIVE(URGENCY) (DATA : DATATYPE);
END MESSAGE;
TASK BODY MESSAGE isBEGIN
LOOPSELECT
ACCEPT RECEIVE(HIGH) (DATA:DATA_TYPE) DO
END RECEIVE;OR
WHEN RECEIVE(HIGH)'COUNT = 0 =>ACCEPT RECEIVE(MEDIUM) (DATA:DATA_TYPE) DO
END RECEIVE;OR
WHEN RECEIVE(HIGH)'COUNT+RECEIVE(MEDIUM)'COU TO =>ACCEPT RECEIVE(LOW) (DATA:DATATYPE) DO
END'RECEIVE;OR
DELAY 1-0; -- SHORT WAITEND MESSAGE;
41
SAME THING, WITH NO GUARDS
TYPE URGENCY Is (LOW, MEDIUM, HIGH);
TASK MESSAGE isENTRY RECEIVE(URGENCY) (DATA : DATATYPE);
END MESSAGE;
TASK BODY MESSAGE is
BEG INLOOP
SELECTACCEPT RECEIVE(HIGH) (DATA:DATATYPE) DO
END RECEIVE;ELSE
SELECTACCEPT RECEIVE(MEDIUM) (DATA:DATATYPE) DO
END RECEIVE;ELSE
SELECTACCEPT RECEIVE(LOW) (DATA:DATATYPE) DO
END RECEIVE;OR
DELAY 1.0; -- SHORT WAITEND SELECT;
END SELECT;END SELECT;
END MESSAGE;
41.1
i _ I ll L-6*
REPRESENTATION SPECIFICATIONS
LENGTH CLAUSE
T'STORAGESIZE
TASK TYPE T1 isENTRY ENTRY 1;FOR T1'STORAGE SIZE USE
2000"SYSTEM.STORAGE_UNIT);END 11;
THE PREFIX T DENOTES A TASK TYPE.
THE SIMPLE EXPRESSION MAY BE STATIC, AND IS USEDTO SPECIFY THE NUMBER OS STORAGE IINITS Tf SERESERVED OR FOR EACH ACTIVATION (NOT THE CODE) OFTHE TASK.
42
ADDRESS CLAUSE
TASK TYPE TI ISENTRY ENTRY1;FOR T1 USE AT 16#167A#;
END Ti;
IN THIS CASE, THE ADDRESS SPECIFIES THE ACTUALLOCATION IN MEMORY WHERE THE MACHINE CODEASSOCIATED WITH Ti WILL BE PLACED.
TASK TI ISENTRY ENTRYI;FOR ENTRY_1 USE AT 16#40#;
END TI;
IF THIS CASE, ENTRY_1 WILL BE MAPPED TO HARDWAREINTERRUPT 64.
ONLY IN PARAMETERS CAN BE ASSOCIATED WITHINTERRUPT ENTRIES.
AN INTERRUPT WILL ACT AS AN ENTRY CALL ISSUED BYTHE HARDWARE, WITH A PRIORITY HIGHER THAN ANYUSER-DEFINED TASK.
DEPENDING UPON THE IMPLEMENTATION, THERE CAN BEMANY RESTRICTIONS UPON THE TYPE OF CALL TO THEINTERRUPT, AND UPON THE TERMINATE ALTERNATIVES.
NOTE: YOU CAN DIRECTLY CALL AN INTERRUPT ENTRY.
43
---- ,=.,==......=, =.m. i m ail
TASKS AT DIFFERENT PRIORITIES
GIVEN 5 TASKS, 3 OF VARYING PRIORITY, I TO BE INTERRUPTDRIVEN, AND 1 THAT WILL BE TIED TO THE CLOCK.
PROCEDURE HEAVYSTUFF is
TASK HIGHPRIORITY IsPRAGMA PRIORITY(50); -- OR AS HIGH AS SYSTEM ALLOWSENTRY POINT;
END HIGH-PRIORITY;
TASK MEDIUMPRIORITY ISPRAGMA PRIORITY(25);ENTRY POINT;
END MEDIUMPRIORITY;
TASK LOWPRIORITY IsPRAGMA PRIORITY(1);ENTRY POINT;
END LOWPRIORITY;
TASK INTERRUPT DRIVEN ISENTRY POINT;FOR POINT USE AT 16061i; --INTERRUPT 97
END INTERRUPTDRIVEN;
TASK CLOCKDRIVEN is-- THERE ARE TWO WAYS TO DO TH 1
-- FIRST WAY IS TO HAVE ANOTHER TASK MONITOR-- THE CLOCK, AND CALL CLOCKDRIVEN.CALL-- EVERY TIME UNIT.ENTRY CALL;
--SECOND WAY IS TO ACTUALLY TIE CALL TO AN-- CLOCK INTERRUPT, AND LET CALL DETERMINE WHEN-- HE WISHES TO PERFORM AN ACTIONFOR CALL USE AT 16932 ; -- ASSUME INTERRUPT 5,
-- IS A CLnCK INTERRuPTEND CLOCK DRIVEN;
END HEAVY_STUF;
43.1
TASK QUEUE isENTRY INSERT(DATA IN DATA TYPE);ENTRY REMOVE(DATA :OUT DATA-TYPE);
END QUEUE;
TASK BODY QUEUE isHEADTAIL : INTEGER := 0;Q : ARRAY (1..100) OF DATATYPE;BEG! N
LOOPSELECT
WHEN TAIL - HEAD + 1 /: 0 AND THENTAIL - HEAD + 1 1= 100 =>
ACCEPT INSERT(DATA : IN DATATYPE) DOIF HEAD = 0 THEN HEAD := 1; END IF;IF TAIL = 100 THEN TAIL 0; END IF;TAIL := TAIL + 1;Q(TAIL) := DATA;
END INSERT;OR
WHEN HEAD /= 0 =>ACCEPT REMOVE(DATA :OUT DATA-TYPE) DO
DATA := Q(HEAD);IF HEAD =TALL THEN
HEAD 0;TAIL 0;
ELSE
HEAD HEAD + 1;IF HEAD > 100 THEN HEAD 1; END IF;
END IF;END REMOVE;
ORTERMINATE;
END SELECT;END LOOP;
END QUEUE;
44
- mANN&
TASK TYPE QUEUE is
ENTRY INSERT(DATA : IN DATA TYPE);ENTRY REMOVE(DATA :OUT DATATYPE);
END QUEUE;
TASK BODY QUEUE isHEAD,TAIL : INTEGER := 0;Q : ARRAY (1..100) OF DATATYPE;BEGIN
LOOPSELECTWHEN TAIL - HEAD 1 /= 0 AND THEN
TAIL - HEAD + 1 1 100 =>ACCEPT INSERT(DATA : IN DATATYPE) Do
IF HEAD = 0 THEN HEAD := 1; END IF;
IF TAIL = 100 THEN TAIL : 0 ; END IF;
TAIL := TAIL + 1;Q(TAIL) := DATA;
END INSERT;OR
WHEN HEAD /= 0 >
ACCEPT REMlOVE(DATA :Oi1T DATATYPE) DoDATA := Q(HEAD);I F HEAD = TAIL THEN
HEAD 0;TAIL : 0;
ELSEHEAD HEAD + 1;IF HEAD > 100 THEN HEAD 1; CND IF;
END IF;END REMOVE,
ORTERMINATE;
END SELECT;END LOOP;
END (UEUE;
MYQUEUE, Y0UR_)dJEUE :,il , --
AD-A18964 A4/ OFIC RLINTOM VA 21 AUG 87
UNCLAS S IIED F/G L2/3 ML
- nR
I II
III I1.8Si1.25 14 .
MWCROCOPY RLSCLUIIGN IfI1 CHARI
GE,;ER ICDATA TYPE PRIVATE;QUEUE_SIZE: POSITIVE = 100;
PACKAGE QUEUEPACK is
TASK QUEUE isENTRY INSERT(DATA : IN DATATYPE);ENTRY REMOVE(DATA :OUT DATATYPE);
END QUEUE;
PACKAGE BODY QUEUEPACK isTASK BODY QUEUE is
HEADTAIL : INTEGER := 0;Q : ARRAY (1..QUEUESIZE) OF DATATYPE;BEGIN
LOOPSELECT
WHEN TAIL - HEAD + 1 / 0 AND THENTAIL - HEAD + 1 /= QUEUE SIZE =>
ACCEPT INSERT(DATA : IN DATATYPE) DOIF HEAD = 0 THEN HEAD := 1; END IF;
IF TAIL = QUEUESIZE THEN TAIL := 0; END IF;
TAIL := TAIL + 1;Q(TAIL) DATA;
END INSERT;ORWHEN HEAD /= 0 =>ACCEPT REMOVE(DATA :OUT DATATYPE) DO
DATA := Q(HEAD);IF HEAD = TAIL THEN
HEAD 0;TAIL 0;
ELSEHEAD HEAD + 1;IF HEAD> QUEUESIZE THEN HEAD 1; END iF;
END IF;
END REMOVE;OR
TERMINATE;
END SELECT;END LOOP;
END QUEUE;
PACKAGE NEW QUEUE IS NEW QUEUE PACK(MY RE'CORD, 250);PACKAGE OLD-QUEUE IS NEW OUEUEPACK(INTEGER);
46
PROCEDURE INSERT INTEGER (DATA IN INTEGER ) RENAMESOLDQUEUE-INSERT;
PROCEDURE REMOVE INTEGER (DATA :OUT INTEGER ) RENAMESOLDQUEUE.REMOVE;
47
PROCEDURE SPIN (R RESOURCE) isBEGIN
LOOPSELECT
R.SEIZE;RETURN;
ELSENULL; --BISY WAITING
END SELECT;END LOOP;
END;
-OR--
PROCEDURE SPIN (R RESOURCE) isBEG IN
R.SEIZE;RETURN;
EN D
48
0 z z 00 0 0 0LL Z Z LL
w *0 0 0 C3
z I w a:0 0U a-w ea.i
Lu oS
05) ItW Ir WWF-- UCn ) ) ~U)
Nz
C. 0
I
>
LL 0
ala > I.
W
eI-,
0.+.
LI
0 0. u
o @soso.
0l 0 Co
o WI." 0 0g2 of Z soC
CCw ~
LU
U
c
U.r
I =0 %
Is, El u
N L IL)
z00 a
Na. LflA cou0o
>
0
Im L6.
>3>
0.>3
0 0 Cz
0 L0L
WILL. C9> LLiJU L
C Z 0
4*ZS 0 0
C C
az a. a 5,
A.
>2
BoUJ
Ijw
UdL
C IL
On 000J ac
-~cl
Saw
UJ
Czlaaa
c L Bo
UOUJ
L aWos.II *1I
U. 'o
A~w
'U
I-B
U.
CZ
I-BB zsb %0 11 ho
U.g Lfn
WIWu
IL I
C ~ mo
L CLw L. c 0ap Go
end
sof
LUJ
%00
LLLU
00L)
EE> %
Ul CM,
i Ia coa P- C
oco Co
-% LW
oz 0
o>
E
> 0
E U
EU L&Oz
ep*1.1 lawl
I -~ I. e
o >. EIZ E I
--
EI.LI U-
%0 =06 a
Lno
ml a few
a coc
cu L
L Co
U.
I U
> co
0
a n0
E 00
low o
0 I
. iJ la-
0 0 a
> E E
E >
J %0 CD0 LL - C 06
0 wLn IV1
a no am
0 z z 00 0 0 0LLZ xXLL
0 uS6 66
z z awI
1/ 0 cl )Q 1
c t w > : >:F-cw 0 G0a
c L L a. w .(I (j) 0 w w w w
z (au u u
C ww F-W WI-cnj W U)U)
0Im N
Ca Z0LC)
LL U. LJJW
z z00
a&as of&
M 0
am Waa *a
0~ N
mm Ci >~
02 z0
c a Caw SIISz-a
> Sj
oak I Cr C ia
CLU> : 7 C
In w0or>3 C- 0 LM 0
z L6 cv~L. r0U.
c U 0 u a s 2 +Li4 a o c
0z 0 1.L LU0
*0 >3 ccI0 CL cyI of1 o sf
> 0W 0 sob
S0 wC C LM
Cc so--
04'9 Ci cUa
UCW0 C t.z s 0
2 1 1 c C
go = 8
4
- - 7 ---
w Oa U.1> Bo
*LC> IS
loo Wo1 S
w)- Lfl
z .ZE .. W.
L U
fU z oou.0 w we 1 0 )mz1
z C c u .. 1 >)~c I=
W mi c m >zuz
O'LL Wc U L o
NC so0 ow0 C o
0g z0uJ
coo u .w UIc g
0U> 2 aAd C 4a.gEq..
IAmo
Ld
UULi z
C C0 z zo0:x 0 00 0 0(T0
Z LL X1 XLL x Z
0 H-
C- 0 QW Q nQW1aH W L H WH L
0r ~C3
CZE xL CL4 -W -4W
0. HU DC Li Li C
0 (J WO 10 w
imz zu 0Cx CD9 x
Ix
w 2
cw II
liaa
L gz 0
I- >
IV cxwY
00.. - l laN0 c ON-
84%O z N Z Lf wLaJ 0Z C C W w
c c
c' i
a a
UL
Li~ N a
W U4,
0
O OU .- 11W
Cc U
Z z owi
a E
..too On
0 u1=
mll
cu 0
01 u
f41 I-wU Lfl
$001w W
91 %0
N C9
Z w %1
seaN az g0- 14N
ko IP
0) o L In
2 C L CD
Ln'
U0)C
PW 41 41las,
bM La
w c~
z = il 0
c -M~z '4a..
.zgas C
P"C'Uc
W 2: 0: u(0) 0 0
wi z wi
0I I-4 ON-
z i
0 Wi Q UQWV) H- z Wij Wd
( It 0 ~ U) Q a
z > D 1 ~>> :a U OCx 0) 0 1 0C
<r ) 0D a. c. a-0. C 0. cr
(i) WW (3uW wu u U (r)uOu
<r H H IX 1-414 > C w> >
i-- n c > ) (.3 ) t
00b
urnn
cz
I uU.)_ V. laa,>Ln c
U.1 c laa, la
LMJ0z U.1
WL E ILM 0 0
o Iff -
E as U 0sW CW
UU WC mbIMCE I UL
LflIL 'Uu o - lea
wI E CC U. E a0 0 Pa E.y z 0 ais = 0 2l Pe
cMLfl4cW *1c U0
Pan a In- o a1 I." u
CD
urn L
toJ.~ ~ on
41L % mm o t Ll*u
(d C UJOgCLLJ
:" cp CZU1=0U1
Uw L E.O mu I
a. ZCC E Um i
US ~UJ W Uj' LWAU U'
Mo II 00 L Zbm
LW 01 = C
E wI 1"'* CL.-o AO
.0 =0C I m nU 1loo m lof'mx o
Il-r CZL+LJVLU E %
Lfl
w. o
Um I :u
L.
CZ- C
LLW Uj z u
mZ z
IMX X L
z z
u m I moo
CE*Z oft E
z I~ "
low oi7 C *
IagzNw
C
0 cu
o b0
CL mobemb
goe IgoLUL CCI-W 1 0 /Lu
%0~f mm L.0
Z CZ on a'LU%0G
01 C
0- +lg
IN-z z
- a.i 1- .
(1)1 0>0.
F- .-- .JHWi z ZCF-) ()Z
0D > 0 H (J) ~>>
I . ->. a.u..0 c
H www. I I.-
z F- W WI- W I-C. W(D Q.W Q inW
aI (I wW E9()z
x L U) rW (1) mWa > CCLm aaw
U) a.- i- I-I- I w w W
W w uu mu uWO0 W H'H WH
F- H > > -> >Z F 0 r iJz r>
".l 0w w "WWCY.C a u)cncr. n c0C- U) 0.
0 C
EsmE- C (
cz LF)U.)
lol l,E- z C
LU to C olCw . >si 0 c
%1 . lo -c L6 UJ.1.1 C wow. I to
I Zz low .
C to Po IlIu L uCI~ z COC ZC u C
jut Uota IlUL 1.1. c% CL r M zMcol w LL CLU .. z O &
0. ..wI -p a.Cz m Z 0No 0. L. L Zaccz CL 41 * 0"O c It"
Go LM 01 CLZ
a.. a co Lcp
CL1 1 .0
X 4a
low 0
L Z
c w (u.
I'4W1 Z I-ZDh.Cu Ul of ~
ago.
41 C M
CZ 41I.a'U :
II- + JU C o
.z
In C Mu
II LU
II wa
C C_
Z Iy
ZC Z& S L6
C9u mCo CL CcU1-
uLp CCCLS 0.u
SuC Cz~a soSPNIi Q
IMai
U.
pm
Pol 0
sC O
le
LVe
Cz a
Ca a sol
2 aaAss,
u-
a. z(1) H-
(E wI-I- z
w z w0 z
z w z (E
ED I U)J
z wz
Ml Z"II'I
zco 0w w a
J J -I.
0 0 JmH 0
cl) cl
M-P
F-zwz
0
U~00
z0
.
0U)
w
w
LL ClLLm w
zz~co
,-Czw
-Jz J41
LLO-J
C D )
Iz
wemWu U
j u
U
IN-CLASS EXERCISE
LET US DESIGN THE TASK SPECIFICATIONS FOR THE FOLLOWING
SENARIO.
THREE TASKS HAVE ACCES TO A TYPE KNOWN AS MESSAGETYPE.
TASKI PRODUCES MESSAGES. TASK_2 CAN RECEIVE MESSAGES,HOLD THEM IN A BUFFER (IF NECESSARY), AND SENDS THEM TO
TASK_3 WHEN THE DATE/TIME FIELD (PART OF MESSAGETYPE)SAYS TO.
TASK TASK_1 is
END TASKI;
TASK TASK_2 is
END TASK_2;
TASK TASK_3 Is
END TASK_3;
83
TASKING EXERCISE
WRITE A MAIN PROGRAM AND TWO TASKS TO SIMULATE A HOUSE ALARMSYSTEM. THE MAIN PROGRAM IS AN INPUT SIMULATOR TO THETASKS. ONE TASK KEEPS TRACK OF THE STATUS OF THE HOUSE.ANOTHER IS THE ACTUAL ALARM SYSTEM.
TASK 1: THE HOUSE STATUS (TASK NAME :HOUSE)THREE ENTRIES => OK, NOTOK, WRITE
THE ENTRIES OK AND NOTOK SET OR RESET A FLAG THATDETERMINES THE STATUS OF THE HOUSE. NOTOK WILL ALSO SET AVARIABLE TO TELL YOU WHICH ALARM IS CURRENTLY GOING OFF.BOTH OK AND NOTOK SHOULD PRINT OUT A MESSAGE VERIFYING THATTHEY WERE CALLED. THE WRITE ENTRY WILL PRINT THE STATUS OFTHE HOUSE. IF THERE IS AN ALARM CURRENTLY GOING OFF, WRITEWILL TELL YOU THE ALARM NUMBER.
TASK 2: THE ALARM SYSTEM (TASK NAME: ALARM)THREE ENTRIES => FIRE, INTRUDER, SHUTOFF
THE ALARM SYSTEM WILL ACCEPT ANY OF THE THREE ENTRYCALLS FROM THE INPUT SIMULATOR. IF THERE ARE NO ENTRY CALLSWITHIN 5 SECONDS, IT WILL CALL HOUSE.WRITE TO DISPLAY THESTATUS. FIRE AND INTRUDER EACH HAVE A PARAMETER INDICATIONTHE ALARM LOCATION. FIRE LOCATIONS ARE '1' THRU '9'.INTRUDER LOCATIONS ARE 'A' THRU 'Z'. FIRE AND INTRUDERSHOULD CALL HOUSE.NOTOK (AND TELL THE HOUSE WHERE THE ALARMIS SOUNDING), AND THEN PRINT OUT A MESSAGE
MAIN PROGRAM
THE MAIN PROGRAM WILL READ IN CHARACTERS FPOM THEKEYBOARD. IF THE CHARACTER IS A '1' THRU '9', CALL THE FIREALARM. IF THE CHARACTER IS A 'A' THRU 'Z' THEN IT CALLS THEINTRUDER ALARM. IF THE CHARACTER IS A '0'(ZERO), THE HOHSEIS RESET TO OK. IF THE CHARACTER IS A '', THEN THE ALARMIS SHUTDOWN, AND THE PROGRAM ENDS. ALL OTHER CHARACTERS DONOTHING.
THE HOUSE STATUS SHOULD BE OK TO START.
84
run cookie
The house is ok
The house is ok
&Invalid character. Try aqain
The house is ok
GHouse alarm set to not OK at location GIntruder in room G
The house is not ok ..alarm is off at location G
The house is not ok ..alarm is off at location G
4House alarm set to not OK at location 4Fire Alarm # 4 has been set off.
The house is not ok ..alarm is off at location 4
House alarm reset to OK.
The house is ok
The house is ok
The alarm has been turned off
85
wi.N TEXT 10;usE TEXTJO;
PROCEDURE COOKIE is
CHAR : CHARACTER;
TASK HOUSE isENTRY OK,ENTRY NOT OK (WHERE:CHARACTER);ENTRY WRITE;
END HOUSE
TASK ALARM isENTRY FIRE (LOCATION:CHARACTER);ENTRY INTRUDER (LOCATION:CHARACTER);ENTRY SHUTOFF;
END ALARM
86
TASK BODY HOUSE isTYPE CONDITION is (OK, NOT OK);ALARM STATUS : CONDITION :; OK;ALARMLOCATION : CHARACTER;
BEGINLOOP
SELECT
ACCEPT OK DOALARM STATUS : OK;PUT_LTNE(fHOUSE ALARM RESET TO OK.');
END OK;i OROR ACCEPT NOT OK (WHERE:CHARACTER)
DOALARM _TATUS :N NOT OK;ALARM-LOCATION :- WfERE;PUT_LTNE('HousE ALARM SET TO NOT OK AT*&
'LOCATION 9 & ALARMLOCATION);END NOTOK;
ORACCEPT WRITE DO
NEW LINE;CASE ALARM STATUS IsWHEN OK =>PUT LINE('THE HOUSE IS OK');WHEN NOT OK => PUT_LINE
('THE HOUSE IS NOT OKu&-.ALARM IS OFF AT LOCATION "&ALARMLOCATION);
END CASE;NEW LINE;
END WRITE;OR
TERMINATE;
END SELECT;END LOOP;
END HOUSE ;
87
TASK BODY ALARM is
BEGINLOOP
SELECTACCEPT FIRE (LOCATION:CHARACTER) Do
HOUSE.NOT-OK(LOCATION);PUT (*FIRE ALARM # ");PUT (LOCATION);PUT LINE (' HAS BEEN SET OFF-*);
END FIRE;OR
ACCEPT INTRUDER (LOCATION:CHARACTER) DoHOUSE.NOTOK(LOCATION);PUT ('INTRUDER IN ROOMPUT (LOCATION);NEW LINE;
END INTRUDER;OR
ACCEPT SHUTOFF;PUT_LINE ('THE ALARM HAS BEEN TURNED OFF*);
EXIT;OR
DELAY 5.0;HOUSE.WRITE;
END SELECT;.
END LOOP;
END ALARM;
88
BEGIN --MAINLOOP
GET (CHAR);SKIPLINE;CASE CHAR is
WHEN '1' .. '9' > ALARM.FIRE (CHAR);WHEN 'A' .. 'Z' => ALARM.INTRUDER (CHAR);WHEN 'A' >'Z' - ALARM.INTRUDER (CHAR);WHEN => HOUSE.OK;WHEN 'I' > ALARM.SHUTOFF;WHEN OTHERS => PUT_LINE
('INVALID CHARACTER. TRY AGAIN');END CASE;EXIT WHEN CHAR =
END LOOP;
END COOKIE;
89
Tutorial on Ada* Exceptions
by
Major Patricia K. Lawlis
lawlis%asu@csnet-relay
Air Force Institute of Technology (AFIT)and
Arizona State University (ASU)
21 August 1987
*Ada Is a registered trademark of the U.S. Government - Ada Joint ProgramOffice
Student Handout, "Ada Applications Proc ammer -AdvancedAda Software Engineering", USAF Teclhnical Training School,Keesler Air Force Base, July 1986.
" J. G. P. Barnes, Programming in Ada, 2nd edition,Addison-Wesley, 1984.
" Grady Booch, Software Engineering with Ada,Benjamin/Cummings, 1983.
" Theodore F. Elbert, Embedded Programming in Ada, VanNostrand Reinhold, 1986.
" Putnam P. Texel, Introductory Ada: Packages forProgramming, Wadsworth, 1986.
" ANSI/MIL-STD-1815A, "Military Standard - Ada ProgrammingLanguage" (LRM), U. S. Department of Defense, 22 January1983.
i mu aimllli l i I I I2
=> Overview
* Naming an exception
Creating an exception handler
* Raising an exception
* Handling exceptions
• Turning ott exception checking
* Tasking exceptions
* More examples
t ANN3
* What is an exception
* Ada exceptions
* Comparison
- the American way
- using exceptions
• A run time error
" An unusual or unexpected condition
* A condition requiring special attention
* Other than normal processing
1S
* An exceptioti has a name
- maybe predefined
- may be declared
* The exception is raised
- may be raised implicitly by run time system
- may be raised explicitly by raise statement
• The exception is handled
- exception handler may be placed in any frame
- exception propagates until handler is found
if no handler anywhere, process .aborts
,,,,, I ... ,,,.. .. ,6
package StackPackage is
type StackType is limited private;
procedure Push (Stack in out Stack-Type;Element in ElementType;OverflowFlag out boolean);
end StackPackage;
with Text_(O;with StackPackage; use StackPackage;procedure FlagWaving is
Stack "Stack_Type;Element "ElementType;Flag "boolean;
begin
Push (Stack, Element, Flag);if Flag then
Text_lO.Put ("Stack overflow");
end if;
end FlagWaving;
-.
package StackPackage is
type Stack_Type is limited private;StackOverflow,StackUnderflow : exception;
procedure Push (Stack "in out Stack_Type;Element: in Element_Type);
-- may raise StackOverflow
end Stack_Package;
with Text_10;with Stack_Package; use Stack_Package;procedure MoreNatural is
Stack : Stack_Type;Element : ElementType;
begin
Push (Stack, Element);
exceptionwhen StackOverflow =>
TextlO. Put ("Stack overflow");
end MoreNatural;7a
0 Overview
=> Naming an exception
* Creating an exception handler
* Raising an exception
* Handling exceptions
* Turning off exception checking
* Tasking exceptions
* More examples
-- ,, ,, , ,ra n mmn m lnmlmmnni m I ~ mmm N8
0 Predefined exceptions
• Declaring exceptions
0 I/0 exceptions
.9
* In package STANDARD (also see chap 11 of LRM)
* CONSTRAINTERROR
violation of range, index, or discriminant constraint...
" NUMERICERROR
execution of a predefined numeric operation cannotdeliver a correct result
• PROGRAMERROR
attempt to access a program unii which has not yetbeen elaborated...
" STORAGEERROR
storage allocation is exceeded...
* TASKINGERROR
exception arising during intertask communication
exception_declaration identifierlist exception;
* Exception may be declared anywhere an object declarationis appr6priate
* However, exception is not an object
- may not be used as subprogram parameter, recordor array component
- has same scope as an object, but its effect mayextend beyond its scope
Example:
procedure Calculation is
Singular : exception;Overflow, Underflow :exception;
begin
end Calculation;
" Exceptions relating to file processing
* In predefined library unit 10_EXCEPTIONS(also see chap 14 of LRM)
• TEXT_10, DIRECT_10, and SEQUENTIAL_10 with it
package 10_EXCEPTIONS is
NAMEERROR exception;USEERROR :exception; --attempt to use
--invalid operation
STATUSERROR : exception;MODEERROR :exception;DEVICEERROR :exception;ENDERROR exception; --altempt to read
--beyond end of fileDATAERROR exception; --attempt to input
--wrong typeLAYOUTERROR :exception; --for text processing
end 10_EXCEPTIONS;
12
Overview
Naming an exception
=> Creating an exception handler
Raising an exception
Handling excepiions
Turning oif exception checking
Tasking exceptions
More examples
13
• Defining an exception handler
* Restrictions
* Handler example
14
• Defining an exception handler
• Restrictions
" Handler example
14
I~i PMRdL
*Exception condition is "'caught" and "handled" by an exception
handler
*Exception handler may appear at the end of any frame (block,
subprogram, package or task body)
begin
exception- - exception handler(s)
end;
Form similar to case statement
exceptionhaldler --when exception-choice (I exception-choice) =>
sequence of-statements
exception..Shoice :=exception_namne Iothers
Exception condition is "caught" and "handled" by an exception
handler
Exception handler may appear at the end of any frame (block,
subprogram, package or task body)
begin
exception-- exception handler(s)
end;
Form similar to case statement
exceptionhandler ::=when exception_choice (I exception_c hoice) =>
sequence ofstatements
exception_choice *:= exception-name Iothers
15
• Exception handlers must be at the end of a frame
* Nothing but exception handlers may lie between exceptionand end of frame
• A handler may name any visible exception declared orpredefined
* A handler includes a sequence of statements
- response to exception condition
• A handler for others may be used
-must be the last handier in the frame
- handles all exceptions not listed in previoushandlers of the frame(including those not in scope of visibility)
- can be the only handler in the frame
16
procedure Whatever is
ProblemCondition exception;
begin
exception
when ProblemCondition =>Fix_It;
when CONSTRAINTERROR =>Report_It;
when others =>Punt;
end Whatever;
17
Overview
* Naming an exception
• Creating an exception handler
=> Raising an exception
* Handling exceptions
* Turning off exception checking
* Tasking exceptions
* More examples
18
" How exceptions are raised
0 Effects of raising an exception
" Raising example
19
* Implicitly by run time system
- predefined exceptions
• Explicitly by raise statement
raisestatement ::= raise [exception-name];
the name of the exception must be visible at thepoint of the raise statement
a raise statement without an exception name isallowed only within an exception handler
20
* Control transfers to exception handler at end of frame(if one exists)
a Exception is lowered
" Sequence of statements in exception hander is executed
" Control passes to end of frame
If frame does not contain an appropriate exception handler,the exception is propagated
21
h . * . . . . .. ... . . . . . . . -
procedure Whatever isProblemCondition exception;
RealBadCondition "exception;
begin
if ProblemArises thenraise ProblemCondition;
end if;
if Serious_Problem thenraise RealBad Condition;
end if;
exception
when ProblemCondition =>Fix_It;
when CONSTRAINTERROR =>ReportIt;
when others =>Punt;
end Whatever;
22
rr
*overview
* Naming an exception
* Creating an exception handler
* Raising an exception
=> Handling exceptions
" Turning off exception checking
• Tasking exceptions
* More examples
23
i i II I I I I I il I IIII I IIIAI II.
" How exception handling can be useful
* Which exception handler is used
* Sequence of statements in exception handler
* Propagation
0 Propagation example
24
Normal processing could continue if
- cause of exception condition can be "repaired"
- alternative approach can be used
- operation can be retried
* Degraded processing could be. better than termination
- for example, safety-critical systems
* If termination is necessary, "clean-up" can be done first
2'
* If exception is raised during normal execution, system looksfor an exception handler at the end of the frame in which theexception occurred
* If exception is raised during elaboration of the declarativepart of a frame
- elaboration is abandoned and control goes to theend of the frame with the exception sti(f raised
exception part of the frame is not searched for anappropriate handler
effectively, the calling unit will be searched for anappropriate handler
if elaboration of library unit, program execution isabandoned
-- all library units are elaborated with themain program
If exception is raised in exception handler
- handler may contain block(s) with handler(s)
. if not handled locally within handler, control goesto end of frame with exception raised
26
IIAlI I
• Handier completes the execution of the frame
- handler for a function should usually contain areturn statement
* Statements can be of arbitrary complexity
- can use most any language construct that makessense in that context
- cannot use goto statement to transfer into ahandler
- if handler is in a block inside a loop, could use exitstatement
* Handler at end of package body applies only to packageinitialization
* Occurs if no handler exists in frame where exception is raised
" Also occurs if raise statement is used in handler
• Exception is propagated dynamically
- propagates from subprogram to unit calling it(not necessarily unit containing its declaration)
- this can result in propagation outside its scope
* Propagation continues until
- an appropriate handler is found
- exception propagates to main program (still withno handler) and program execution is abandoned
28
procedure DoNothing is
procedure Has_It is
Some_Problem exception;
begin
raise SomeProblem;
exceptionwhen SomeProblem =>
Clean_Up;raise;
end HasIt;
procedure Callsit isbegin
Has_It;
end Calls_It;
begin -- DoNothing
CallsIt;
exceptionwhen others => Fix_Everything;
end Do_Nothing;
O0it
" Overview
* Naming an exception
* Creating an exception handler
* Raising an exception
• Handling exceptions
=> Turning off exception checking
* Tasking exceptions
* More examples
30
* Overhead vs efficiency
• Pragma SUPPRESS
* Check identifiers
• . . n i n n- - m l ll I NN II IIL
* Exception checking imposes run time overhead
- interactive applications will never notice- real-time applications have legitimate concerns
but must not sacrifice system safety
* When efficiency counts
- first and foremost, make program work- be sure possible problems are covered by exception
handlers- check if efficient enough - stop if it is
- if not, study execution profile-- eliminate bottlenecks-- improve algorithm
avoid "cute" tricks
- check if efficient enough - stop if it is- if not, trade-offs may be necessary- some exception checks may be expendable since
debugging is done
- however, every suppressed check poses newpossibilities for problems
-- must re-examine possible problems-- must re-examind exception handlers
- always keep in mind-- problems will happen-- critical applications must be able to
deal with these problems32
Improving the a 4yn~h-is far better - and easier inthe long run - than s~ippressing checks
32a
Only allowed immediately within a declarative part or
immediately within a package specification
pragma SUPPRESS (identifier [,J ON =>] name]);
- identifier is that of the check to be omitted(next slide lists identifiers)
. name is that of an object, type, or unit for whichthe check is to be suppressed
-- if no name is given, it applies to theremaining declarative region
An implementation is free to ignore the suppress directivefor any check which may be impossible or too costly tosuppress
Example:
pragma SUPPRESS (INDEX_CHECK, ON => Index);
33
* These identifiers are explained in more detail in chap 11 ofthe LRM
• Check identifiers for suppression of CONSTRAINTERRORchecks
ACCESSCHECKDISCRIMINANTCHECKINDEXCHECKLENGTHCHECKRANGECHECK
" Check identifiers for suppression of NUMERICERROR checks
DIVISION CHECKOVERFLOWCHECK
• Check identifier for suppression of PROGRAMERROR checks
ELABORATION-CHECK
" Check identifier for suppression of STORAGEERROR check
STORAGECHECK
• m • . . ..
I | 1in .
" Overview
* Naming an exception
* Creating an exception handler
* Raising an exception
• Handling exceptions
" Turning off exception checking
=> Tasking exceptions
* More examples
35
II im mmm llikm
* Exception handling is trickier for tasks
* Exceptions during task rendezvous
* Tasking example
b Rules are not really different, just more involved
- local exceptions handled the same within frames
If exception is raised
" during elaboration of task declarations
- the exception TASKINGERROR will be raised at thepoint of task activation
- the task will be marked completed
* during execution of task body (and not resolved there)
- task is completed
- exception is not propagated
* during task rendezvous
this is the really tricky part
37
• If the called task terminates abnormally
exception TASKINGERROR is raised in calling task at thepoint of the entry call
* If the calling task terminates abnormally
no exception propagates to the called task
• If an exception is raised in called task within an accept (andnot handled there locally)
the same exception is raised in the calling task at the pointof the entry call(even if exception is later handled outside of the accept inthe called task)
• If an entry call is made for entry of a task that becomescompleted before accepting the entry,
exception TASKINGERROR is raised in calling task at thepoint of the entry call
procedure Critical-Code is
Failure exception;
task Monitor isentry DoSomething;
end Monitor;task body Monitor is
begin
accept DoSomething do
raise Failure;
end DoSomething;
exception -- exception handled herewhen Failure =>
Term inationMessage;
end Monitor;
begin -- CriticalCode
Monitor.DoSomething;
exception -- same exception will be handled herewhen Failure =>
CriticalProblemMessage;
end CriticaiCode;39
, Overview
* Naming an exception
* Creating an exception handler
* Raising an exception
• Handling exceptions
* Turning off exception checking
* Tasking exceptions
=> More examples
-Alm.
* Interactive data input
" Propagating exception out of scope and back in
• Keeping a task alive
41
with Text_10; use Text10i;
procedure Getinput (Number out integer) is
' -_type inputTyPe is integer range o.1 00;
package tnt_10i is new Integerjo (Input-Type);
InNumber -.InputType;
begin -- Get_Input
loop -- to try again after incorrect input
begin -- inner block to hold exception handler
put ("Enter a number 0 to I00O);
Int -io.get (In_-Number);Number: In_-Number;exit; .- to exit loop after correct Input
exceptionwhen DATAERROR ICONSTRAINTERROR =
put ("Try again, tat fingers!");Skipj-ine; -- must clear buffer
end; -- inner block
end loop;
end GetjlnPut;
declarepackage Container is
procedure HasHandler;procedure RaisesException;
end Container;
procedure Notin_Package is
beginContainer. Raises-Exception;
exceptionwhen others => raise;
end Notin_Package;
package body Container isCrazy :exception;procedure HasHandler is
beginNotin_Package;
exceptionwhen Crazy => TellEveryone;
end HasHandler;procedure RaisesException is
beginraise Crazy;
end Raises_Exception;end Container;
beginContainer. HasHandler;
end;43
task Monitor isentry Do_Something;
end Monitor;
task body Monitor isbegin
loop -- for never-ending repetition
selectaccept DoSomething do
begin -- block for exception handler
raise Failure;
exceptionwhen Failure => Recover;
end; -- block
end DoSomething; -- exception must be-- lowered before exiting
end select;
end loop;
exceptionwhen others =>
TerminationMessage;end Monitor;
~-s ..- ~ t4
- IAAQCk. ~~- ~'- C
- ~ IcK7~a- C-; ~ c~ /&~~-~
p
/