Introduction to Ada95 Volume 1 of 8 COP 4232: Software Systems Development © Dr. David A. Workman...
-
Upload
aubrey-york -
Category
Documents
-
view
214 -
download
2
Transcript of Introduction to Ada95 Volume 1 of 8 COP 4232: Software Systems Development © Dr. David A. Workman...
Introduction to Ada95Volume 1 of 8
COP 4232: Software Systems Development
© Dr. David A. Workman
School of Computer Science
University of Central Florida
October 1999
Revised: August 2002
October 21, 1999 (Revised 2002)
(c) David A. Workman 2
Ada References
Ada95 STANDARD DOCUMENTS– Ada 95 Reference Manual, International Standard ANSI/ISO/IEC-8652:1995.
– Ada 95 Rationale.
– Ada Information Clearinghouse (probably out of date) [email protected]://sw-eng.falls-church.va.us/
October 21, 1999 (Revised 2002)
(c) David A. Workman 3
Ada References
Ada95 Reference Sources– http://www.gnat.com
The home page of Ada Core Technologies, the maintainers of GNAT
– http://lglwww.epfl.ch/AdaThe Ada WWW server in Lausanne, Switzerland; this server has a wealth of Ada-related information.
– http://lglwww.epfl.ch/Ada/FAQ/comp-lang-ada.htmlAda frequently-asked questions (FAQs).
– http://lglwww.epfl.ch/Ada/Tutorials/Lovelace/lovelace.htmlLovelace, a free interactive Ada 95 tutorial.
– http://lglwww.epfl.ch/Ada/Resources/Books/Textbooks.htmlAn annotated list of Ada-oriented textbooks.
October 21, 1999 (Revised 2002)
(c) David A. Workman 4
Ada References
Ada95 Reference Sources
– http://wuarchive.wustl.edu/languages/ada/The Public Ada Library (PAL); this contains lots of software.
– http://sw-eng.falls-church.va.us/The Ada Information Clearinghouse.
– http://www.acm.org/sigada/The Association for Computing Machinery (ACM)'s SIGAda home page.
– There is also a newsgroup, comp.lang.ada, specifically dedicated to Ada.
October 21, 1999 (Revised 2002)
(c) David A. Workman 5
Ada95
HISTORY
In the early 1980’s, the Department of Defense developed Ada to serve as the standard programming language for developing embedded real-time systems for military applications. The standard was released in 1983 as MIL-STD-1815A. Now known as Ada83.
In the late 1980’s work began on revising the ‘83 standard to include features specifically supporting OO programming, information systems applications, and distributed computing. The new standard was recently released as an ISO and ANSI standard. Now known as Ada95.
October 21, 1999 (Revised 2002)
(c) David A. Workman 6
Ada95
FEATURES
– Constructs for Information Hiding and Data Abstraction
– Strong-typing and subtyping
– Large-scale, incremental software development (hierarchical libraries)
– Full support for Object-Oriented programming
– Generic programming for reuse
– Support for concurrent programming using shared data (protected types)
– Multi-tasking (multi-threaded execution control)
– Support for systems programming
– Support for distributed applications
– Support for information systems applications
– Support for interoperability with C, Fortran, and Cobol
October 21, 1999 (Revised 2002)
(c) David A. Workman 7
The Ada ProgrammingEnvironment
Ada Source
File
Program
Library
Ada Compiler
&
Library Mgr
Compilation Units Library Units
October 21, 1999 (Revised 2002)
(c) David A. Workman 8
Ada95 Library Structure
Standard ( package ) Standard ( package )
Stystem ( package )
Stystem ( package )
Interfaces ( package ) Interfaces ( package )
User-defined Compilation Units
User-defined Compilation Units
Text_Io ( package ) Text_Io ( package )
Direct_Io( package ) Direct_Io( package )
Sequential_Io( package ) Sequential_Io( package )
Calendar( package ) Calendar( package )
Unchecked_Conversion ( function ) Unchecked_Conversion ( function )
IO_Exceptions( package ) IO_Exceptions( package )
Unchecked_Deallocation ( procedure ) Unchecked_Deallocation ( procedure )
Ada ( package )
Ada ( package )
October 21, 1999 (Revised 2002)
(c) David A. Workman 9
Ada95 Library Structure
Ada - Asynchronous_Task_Control - Calendar - Characters Handling Latin_1 - Command_Line - Decimal - Direct_IO - Dynamic_Priorities - Exceptions - Finalization - Interrupts Names - IO_Exceptions - Numerics Complex_Elementary_Functions Complex_Types Discrete_Random Elementary_Functions Float_Random Generic_Complex_Elementary_Functions Generic_Complex_Types Generic_Complex_Functions
Ada (continued) - Synchronous_Task_Control - Tags - Task_Attributes - Task_Identification - Text_IO Complex_IO Editing Text_Streams - Unchecked_Conversion - Unchecked_Deallocation - Wide_Text Complex_IO Editing Text_Streams
• Interfaces - C Pointers Strings - COBOL - Fortran
• System - Address_To_Access_Conversion - Machine_Code - RPC - Storage_Elements - Storage_Pools
Ada (continued) - Real_Time - Sequential_IO - Storage_IO - Streams Stream_IO - Strings Bounded Fixed Maps Constants Unbounded Wide_Bounded Wide_Fixed Wide_Maps Wide_Constants Wide_Unbounded
Bold font : New Ada95 Library UnitsNormal font: Ada 83 Library Units
Bold font : New Ada95 Library UnitsNormal font: Ada 83 Library Units
October 21, 1999 (Revised 2002)
(c) David A. Workman 10
Ada Program Units
DEFINITION 1: Program Unit
A Program Unit is a basic building block for Ada Programs. The seven types of program units are:
- Procedure Unit - Function Unit - Package Unit - Task Unit - Protected Unit - Protected Entry - Generic Unit
Package Units
Subprogram Units
Subprograms
October 21, 1999 (Revised 2002)
(c) David A. Workman 11
Library Units
DEFINITION 2: Library Items and Units
A Library Item is a “compilation unit” that is the declaration, body, or renaming of a Library Unit. Each Library Unit (except Standard) has a parent unit, which is a library package or generic library package. A library unit is a child of its parent. The root library units are the children of the predefined library package Standard. Library units can be any of the following types of program units.• Procedure Unit• Function Unit• Package Unit• Generic Unit
October 21, 1999 (Revised 2002)
(c) David A. Workman 12
Ada Compilation Units
DEFINITION 3: Compilation Unit
A Compilation Unit is a Progam unit, Subunit, or group of Ada statements that otherwise define one of these units for separate compilation. The types of Compilation unit are:
- Subprogram Declaration (Root or Child) - Subprogram Body - Package Declaration (Root or Child) - Package Body - Generic Declaration - Generic Body - Generic Instantiation - Subunits - Renaming declaration for a Library unit
October 21, 1999 (Revised 2002)
(c) David A. Workman 13
Ada Program Structure
Context Clause(what’s needed from library) with Unit1, Unit2, ...;
procedure Main is
end Main;
Unit1.Info
Unit2.Info
Program Library
Unit1Unit2
...
Main procedure(entry point for
program execution)
Library units(typically packages)e.g. Ada.Text_Io
for example:Ada.Text_Io.Get(…);Ada.Text_Io.Put(…);
October 21, 1999 (Revised 2002)
(c) David A. Workman 14
Compilation Unit Examples
SUBPROGRAM DECLARATIONS
procedure Alpha(X,Y: in INTEGER; Z: out FLOAT); -- Library root unit
with Ada.Text_Io; -- Note that Text_Io is a child of package Ada, a root unit.
procedure Print( File: in Ada.Text_Io.File_Type; S : in STRING);
function Ada.Text_Io.EOF( F: File_Type ) return BOOLEAN;
-- Child function of Ada.Text_Io; it automatically has visibility to package
-- specification of Ada.Text_Io (and to Ada) and therefore does not need to
-- have a context clause to gain this visibility.
October 21, 1999 (Revised 2002)
(c) David A. Workman 15
Ada95 Library: Example
Standard ( package ) Standard ( package )
User-defined Compilation Units
User-defined Compilation Units
Ada ( package )
Ada ( package )
Text_Io ( package )Text_Io ( package )
EOFEOF
AlphaAlpha PrintPrint
This slide shows the changes to the Ada Library structure aftercompiling the units on the previous slide.
This slide shows the changes to the Ada Library structure aftercompiling the units on the previous slide.
October 21, 1999 (Revised 2002)
(c) David A. Workman 16
Compilation Unit Examples
SUBPROGRAM BODIES
procedure Alpha( X,Y: in INTEGER; Z: out FLOAT) is -- the following is a declaration of Subunit Min. function Min return INTEGER is separate; -- the parameters X,Y,Z are global to Min.begin Z := FLOAT( X + 2*Y - Min);end Alpha;
function Ada.Text_Io.EOF( F: File_Type) return BOOLEAN isbegin return End_Of_File(F);end Ada.Text_Io.EOF;
October 21, 1999 (Revised 2002)
(c) David A. Workman 17
Ada95 Library: Example
Standard ( package ) Standard ( package )
User-defined Compilation Units
User-defined Compilation Units
Ada ( package )
Ada ( package )
Text_Io ( package )Text_Io ( package )
EOFEOF
AlphaAlpha PrintPrint
This slide shows the changes to the Ada Library structure aftercompiling the units on the previous slide.
This slide shows the changes to the Ada Library structure aftercompiling the units on the previous slide.
MinMin
logical nesting (child units)
physical nesting (subunits)
October 21, 1999 (Revised 2002)
(c) David A. Workman 18
Compilation Unit Examples
SUBUNITS (bodies of subprograms, packages, and tasks)
separate( Alpha ) -- subunit ancestryfunction Min return INTEGER isbegin -- References to X,Y are references to the parameters -- X and Y declared as parameters in Alpha. if X <= Y then -- Conditional statement return X; else return Y; end if;end Min;
October 21, 1999 (Revised 2002)
(c) David A. Workman 19
Compilation Unit Examples
PACKAGE DECLARATION
package Universal is type Metric is digits 8 range -1.0e1_000 .. 1.0e1_000; Pi : constant := 3.1415926; -- Named Number Root_2 : constant := 1.414213562; -- Named Number E : constant := 2.718281828; -- Named Number Zero : constant Metric := 0.0; -- Constant (Metric)end Universal;
October 21, 1999 (Revised 2002)
(c) David A. Workman 20
Compilation Unit Examples
PACKAGE DECLARATION
with Ada.Text_Io;package Complex_Pkg is type Complex_Type is private; function Create( Re, Im: FLOAT ) return Complex_Type; function “+” (X,Y: Complex_Type ) return Complex_Type; function “-” (X,Y: Complex_Type ) return Complex_Type; function “*” (X,Y: Complex_Type ) return Complex_Type; function “/” (X,Y: Complex_Type ) return Complex_Type; function Re ( X: Complex_Type ) return FLOAT; function Im ( X: Complex_Type ) return FLOAT; procedure Get( File: in Text_Io.File_Type;Data: out Complex_Type); procedure Put( File: in Text_Io.File_Type;Data: in Complex_Type);private type Complex_Type is record Re,Im: FLOAT; end record;end Complex_Pkg;
Not visible toclients
October 21, 1999 (Revised 2002)
(c) David A. Workman 21
Compilation Unit Examples
PACKAGE BODY
with Ada.Float_Text_Io;package body Complex_Pkg is -------- function Create( Re, Im: FLOAT ) return Complex_Type is begin return (Re, Im);-- an example of a “record aggregate”. end Create; -------- function “+” (X,Y: Complex_Type ) return Complex_Type is begin return (X.Re + Y.Re, X.Im + Y.Im); end “+”; -------- -- etc.end Complex_Pkg;
Only library unitsneeded only by body
Text_Io is stillvisible from
package spec.
October 21, 1999 (Revised 2002)
(c) David A. Workman 22
Compilation Unit Examples
GENERIC DECLARATION
Genericparameters
generic type Data_Type is private; with function “<=“( X,Y: Data_Type ) return BOOLEAN;function Gmin(A,B:Data_Type) return Data_Type;
Name of the Generic Unit (Gmin)
Kind of Generic Unit (function)
October 21, 1999 (Revised 2002)
(c) David A. Workman 23
Compilation Unit Examples
GENERIC BODIES
function Gmin( A,B: Data_Type) return Data_Type isbegin if A <= B then -- Conditional statement return A; else return B; end if;end Gmin;
October 21, 1999 (Revised 2002)
(c) David A. Workman 24
Compilation Unit Examples
GENERIC INSTANTIATIONS
with Gmin;function Min is new Gmin( INTEGER, Standard.”<=“);
with Ada.Text_Io; package Ada.Float_Text_Io is new Ada.Text_Io.Float_Io( FLOAT );
with Ada.Text_Io;package Ada.Integer_Text_Io is new Ada.Text_Io.Integer_Io( INTEGER );
Both Ada.Float_Text_Io and Ada.Integer_Text_Ioare Ada95 library units. They are defined in exactlythis way as instantiations of generic units declaredwithin Ada.Text_Io.
Both Ada.Float_Text_Io and Ada.Integer_Text_Ioare Ada95 library units. They are defined in exactlythis way as instantiations of generic units declaredwithin Ada.Text_Io.
October 21, 1999 (Revised 2002)
(c) David A. Workman 25
Compilation Unit Examples
RENAMING DECLARATIONS
with Ada.Float_Text_Io;package Float_Io renames Ada.Float_Text_Io;
with Ada.Integer_Text_Io;package Int_Io renames Ada.Integer_Text_Io;
October 21, 1999 (Revised 2002)
(c) David A. Workman 26
Scope and Visibility
• DEFINITION A declaration in a program may affect the interpretation of certain parts of a program but not others. The part of a program in which a declaration has its effect is called its scope.
Scope rules are based on the notion of declarative region, a collection of possibly discontiguous segments of program text, called frames, possibly in different compilation units, possibly in the same compilation unit.
• DEFINITION Many declarations for the same identifier may have overlapping scope. A declaration of an entity is said to be visible at the site of an identifier within its scope, if that identifier may refer to the declared entity. If more than one declaration of an identifier is visible at a point of reference, the identifier is said to be overloaded.
Rules of visibility uniquely determine what declaration applies to a given identifier in a given program context.
October 21, 1999 (Revised 2002)
(c) David A. Workman 27
Declarative Regions
genericsubprogramdeclaration
genericsubprogram
body
subprogramdeclaration
subprogrambody
optional
task [object | type]
declaration
taskbody
task entrydeclaration
protected [object | type ]
protectedbody
privatepart
protected entry
declaration
protected entrybody
packagedeclaration
packagebody
privatepartchild package
declaration
child packagebody
child privatepart
acceptstatement
blockstatements
loopstatements
exceptionhandlers
recordtypes
typeswith
discriminants
logical nesting
physical nesting
October 21, 1999 (Revised 2002)
(c) David A. Workman 28
Scope and Visibility
Frame: A
Frame: B
Declarations: X,Y
Declarations: Y, Z
ref: X, Y, Z, A.Y, B.Y
1: Definition in frame A (global)2: Definition in frame B (inner hides outer)3: Definition in frame B (local)4: Definition of Y in frame A5: Definition of Y in frame B
1-3: direct visibility4-5: select visibility
Direct visibility: Compiler begins at the point of reference looking at declarations inenclosing frames, from inner-most to outer-most, the first declaration of the given name encountered is the one used.
Direct visibility: Compiler begins at the point of reference looking at declarations inenclosing frames, from inner-most to outer-most, the first declaration of the given name encountered is the one used.
Select visibility involves the use of compoundnames formed using “dot notation.” In X.Y.Z,“X” must be directly visible, Y must be declaredin the frame named X, and Z must be declaredin the frame named Y. If X is not an enclosingframe, then X and all but the last name must benames of packages.
Select visibility involves the use of compoundnames formed using “dot notation.” In X.Y.Z,“X” must be directly visible, Y must be declaredin the frame named X, and Z must be declaredin the frame named Y. If X is not an enclosingframe, then X and all but the last name must benames of packages.
October 21, 1999 (Revised 2002)
(c) David A. Workman 29
Global Visibility Rules
Package STANDARD is -- All predefined language features -- E.g., basic types and operatorsend STANDARD;
Logical nestingaffords direct visibilityto any name declared within STANDARD.
Your Compilation Unit
Context Clause
Package STANDARD.Ada is -- Environment declaration visible to all -- logically and physically nested packages -- and subprograms.end Ada;
Package STANDARD.System isend System;
Package STANDARD.Interfaces isend Interfaces;
Packages Ada, System, and Interfaces are child units (logically nested) of package STANDARD.
Your Library Units
October 21, 1999 (Revised 2002)
(c) David A. Workman 30
Package Visibility Rules
Package Declaration (public)
Private Part
Package body
Child private part
Child package (public)
Child body
Subprogrambody
Child subpgm (public)
SeeNotes page
October 21, 1999 (Revised 2002)
(c) David A. Workman 31
Unit Dependencies
DEFINITION 4: Unit Dependency
A Compilation unit U semantically depends on Compilation unit X, if:
(1) U is a subunit or child unit of X; (2) U is the body of the unit having declaration (specification) X; (3) X is a Library unit declared in the context clause of U.
X: Parent X: Declaration X:Lib. Unit
U: Subunitor Child
U: Body U:Any Unit
(1) (2) (3)
October 21, 1999 (Revised 2002)
(c) David A. Workman 32
WITHing Diagrams
A WITHing Diagram is a directed graph consisting of nodes representing Ada Library units (or their parts) and edges directed from a given node to all other nodes denoting compilation units upon which the given unit depends.
Unit X
Unit A
Unit B
Unit C
with A,B,C; procedure X ;
October 21, 1999 (Revised 2002)
(c) David A. Workman 33
WITHing Diagrams
• Unit interfaces and their bodies should create distinct nodes in the WITHing graph.
This rule also applies to subprograms if the subprogram declaration is compiled separately from its body.
• Subunits or Child units and their corresponding parent units should create distinct nodes in a WITHing graph. Subunits implicitly with the body of their parent. Child units implicitly with the declaration (specification) of their parent.
• A with for a package is a with for its declaration(specification), not its body.
• A with for a subprogram is a with for its declaration, if the declaration was separately compiled, else its a with for the body.
• A WITHing Diagram cannot have cycles!!!
October 21, 1999 (Revised 2002)
(c) David A. Workman 34
WITHing Diagrams EXAMPLES
with Ada.Text_Io;package Complex is type Complex_Type is private; ... procedure Get( File: in Ada.Text_Io.File_Type; Data: out Complex_Type);private ...end Complex;
with Ada.Numerics.Elementary_Functions;use Ada.Numerics.Elementary_Functions;package body Complex is
... Sqrt(X) ...
end Complex;
ComplexSpec
Ada.Text_Io
ComplexBody
Ada.Numerics
Ada.Numerics.Elementary_Functions
Ada
October 21, 1999 (Revised 2002)
(c) David A. Workman 35
WITHing Diagrams
EXAMPLES
package A is ...end A;
with B;package body A is ...end A;
package B is ...end B;
with A;package body B is ...end B;
with D;package C is ...end C;
with C;package D is ...end D;
October 21, 1999 (Revised 2002)
(c) David A. Workman 36
Procedure Units PROCEDURE DECLARATIONS
[ Context Clause ][ private ] procedure Unit-name [ ( Parameter-declarations) ] is Declarations -- optionalbegin Executable-statements -- at least one[ exception -- optional Exception-handlers ]end Unit-name;
PROCEDURE BODY
[ Context Clause ] [ private ] procedure Unit-name [ (Parameter-declarations ) ] [ is abstract ];
Unit-name => [ Parent-unit . ] Identifier
October 21, 1999 (Revised 2002)
(c) David A. Workman 37
Procedure Units
PARAMETER DECLARATIONS
[1] Identifier { , Identifier}* : [ mode ] Subtype-mark [ := Expression ]
[2] Identifier {, Identifier }* : [ mode ] access Subtype-mark [ := Expression ]
mode => in | out | in out ; defines the direction of data flow; all parameters in Ada95 are passed by-copy or by-reference. The transmission method is determined by the class associated with Subtype-mark as specified below:
by-copy => All Elementary types together with all private types whose full view is a by-copy type.
by-reference => All Tagged, Protected, and Task types. All non-private types with limited in their declarations. All composite types having a subcomponent that is a by-reference type. All private types whose full view is a by-reference type.
Subtype-mark => In [1] it declares the name of the subtype associated with each Identifier.
=> In [2] it denotes the designated subtype of an anonymous access type; each Identifier defines a different access type; parameters declared in this fashion are called access parameters. Access parameters must be of mode in.
Expression => Declares the default value for in parameters only. This expression is evaluated at runtime when the procedure is called. The value must agree with the
subtype defined by Subtype_mark. If a parameter is declared to have a default value, then it may be omitted in the call statement that invokes the procedure.
October 21, 1999 (Revised 2002)
(c) David A. Workman 38
Procedure Units
with Ada.Text_Io;procedure Program2 is -- This program prompts the user for: name, phone, and address. -- Then echoes this information back. Blank : constant CHARACTER := ‘ ‘; Blank_Line : constant STRING(1..35) := (others => Blank); Name : STRING(1..25) := (others => Blank); Phone : STRING(1..15) := “ “; Address : array(1..3) of STRING(1..35) := (others => Blank_Line); Index : NATURAL; -- End of Declaration Section -- Continue with next Slide
EXAMPLE
October 21, 1999 (Revised 2002)
(c) David A. Workman 39
Procedure Units
begin -- Prompt for User’s Name Ada.Text_Io.Put(“Enter your name(1..25) followed by ENTER.”); Ada.Text_Io.Get_Line( Name, Index); -- Prompt for User’s Phone Number Ada.Text_Io.Put(“Enter your Phone Number (aaa)xxx-xxxx followed by ENTER.”); Ada.Text_Io.Get_Line( Phone, Index); -- Prompt for User’s Address Ada.Text_Io.Put_Line(“Enter each of three address lines.” & “Press ENTER after each line.”); -- Read three lines from User for i in Address’RANGE loop Ada.Text_Io.Put( INTEGER’IMAGE(i) & ‘?’ ); Ada.Text_Io.Get_Line(Address(i),Index); end loop; -- Remainder of Program left as an exercise. Ada.Text_Io.New_Line; -- New_Line writes an EOL mark to the Default Output File.end Program2;
EXAMPLE (continued)
October 21, 1999 (Revised 2002)
(c) David A. Workman 40
Function Units FUNCTION DECLARATION
FUNCTION BODY
Unit-name => [ Parent-unit. ] Identifier
[ Context Clause ][ private ] procedure Unit-name [ ( Parameter-declarations) ] return Result-subtype is Declarations -- optionalbegin Executable-statements -- at least one and must contain a return statement[ exception -- optional Exception-handlers ]end Unit-name;
[ Context Clause ] [ private ] function Unit-name [ (Parameter-declarations ) ] return Result-subtype[ is abstract ];
October 21, 1999 (Revised 2002)
(c) David A. Workman 41
Function Units
function Sqrt( X: in FLOAT) return FLOAT is -- This function computes the square root of its parameter, X. -- If X is negative, the function raises an exception SQUARE_ROOT_ERROR. SQUARE_ROOR_ERROR: exception; Epsilon : constant FLOAT := 1.0e-5; -- defines the root precision. Old_Root : FLOAT := 0.0; New_Root : FLOAT;begin -- Check for negative argument. if X < 0.0 then raise SQUARE_ROOT_ERROR; end if; if X = 0.0 then return 0.0; end if; -- Normal case: X > 0.0 New_Root := X/2.0; -- first guess while abs( New_Root - Old_Root) > Epsilon loop Old_Root := New_Root; New_Root := (Old_Root + X/Old_Root)/2.0; end loop; return New_Root;end Sqrt;
EXAMPLE
October 21, 1999 (Revised 2002)
(c) David A. Workman 42
OverloadingDEFINITIONS
A name is said to be overloaded at a place of reference if there is more than one declaration of the name visible at that place.
– Ada permits the overloading of subprogram names, certain operators, and literals of enumeration types.
– Overloadable Operators: and, or, xor, not, abs, mod, rem, “+”,“-”,“*”,“/”,“&”,“**”,“=“,“<“,“>“,“<=“,“>=“
– Two declarations are valid instances of overloading if and only if they both denote declarations of subprograms (operators and enumeration literals are treated as functions in this context), and their profiles are distinct.
– Two overloaded subprogram having identical profiles are called homographs; homographs may not occur in the same frame; if two homographs occur in distinct frames, one nested within the other, the outer homograph is hidden by the inner homograph at every place within the inner frame.
October 21, 1999 (Revised 2002)
(c) David A. Workman 43
Overloading: Examplesprocedure Example is
Green: BOOLEAN := TRUE;
subtype Non_Negative is FLOAT range 0.0..FLOAT’LAST;
type Autum_Colors is ( Red, Orange, Yellow, Brown );
type Traffic_Colors is (Red, Yellow, Green );
function Red (X: NATURAL) return Autum_Colors is … end Red;
function “+”(X: FLOAT; Y:INTEGER) return FLOAT is … end “+”;
function “+”(X: NATURAL; Y: FLOAT) return POSITIVE is … end “+”;
function “+”(X: Non_Negative; Y: POSITIVE) return Non_Negative is … end “+”;
procedure Red is … end Red;
begin
...
end Example;
What are the possible instances of overloading?Are there any homographs?Are there illegal instances of overloading?
October 21, 1999 (Revised 2002)
(c) David A. Workman 44
Subprogram ProfilesDEFINITIONS
PROFILE: The profile of a subprogram is used by the Ada compiler to distinguish one sub-program from another, particularly during overload resolution. For the purpose of computing profiles, primitive operators are treated as functions with one (unary operators) or two (binary operators) parameters. Enumeration literals are treated as functions with no parameters.
Access parameters also contribute to the profile. An access parameter, access S, would be distinguished from another access parameter on the basis of subtype S, and would be distinguished from any non-access parameter of subtype S.
Subprogram profiles are tuples of the form:
(procedure, n = #parameters, {Parameteri(Subtype:mode)}1 i n )(function , n = #parameters, {Parameteri(Subtype:mode)}1 i n , Result_Subtype )
TYPE CONFORMANT: Two profiles are type conformant if they are both procedure profiles or both function profiles, they have the same number of parameters (n), and corresponding parameters have the same base types, and for functions, the base types of their results are the same. If corresponding parameters are access parameters, then their designated base types must be the same.
October 21, 1999 (Revised 2002)
(c) David A. Workman 46
Subprogram ProfilesEXAMPLES[1] procedure Program2; profile(Program2) = [procedure, 0]
[2] procedure Alpha( X,Y: in Age; out access Distance); profile(Alpha) = [procedure, 3, Age:in , Age:in , @Distance:out]
[3] function Sqrt( X: in Distance) return Feet; profile(Sqrt) = [function, 1, Distance:in , Feet]
with Text_Io;[4] procedure Print( File: Text_Io.File_Type; Data: in NATURAL); profile(Print) = [procedure, 2, Text_Io.File_Type:in, NATURAL:in ]
[5] type Color is (Red, Yellow, Green, Blue); profile(Red) = profile(Yellow) = profile(Green) = profile(Blue) = [function, 0, Color ]
[6] function “*”(X : Distance; Y: Old_Age) return NATURAL; profile(“*”) = [function, 2, Distance:in, Old_Age:in, NATURAL]
[7] function “*”(Y: Feet; X : POSITIVE) return Age; profile(“*”) = [function, 2, Feet:in, POSITIVE:in, Age]
X,Y: FLOAT;subtype Feet is FLOAT range 0.0..1000.0;subtype Distance is FLOAT range X..Y;subtype Age is NATURAL range 0..125;subtype Old_Age is Age range 70..125;
Ada Types
© Dr. David A. Workman
School of EE and Computer Science
University of Central Florida
August 2002
October 21, 1999 (Revised 2002)
(c) David A. Workman 48
Ada95 Types
DEFINITION: TYPE
An Ada type is characterized by a set of VALUES, a set of PRIMITIVE OPERATIONS defined on those values, and a set of ATTRIBUTES defined on its subtypes and objects.
DEFINITION: TYPE CLASS
An Ada Type Class is a collection of types that share the same primitive operations and attributes (but not necessarily the same value set).
PRINCIPLE of INHERITANCE
If C denotes a type class defined by Ada, and S denotes any containing class, then all attributes and primitive operations defined for S are implicitly defined for C, that is, all types in C.
October 21, 1999 (Revised 2002)
(c) David A. Workman 49
Ada95 Types
DEFINITION: SUBTYPE
A subtype is characterized by a base type and a constraint on the value set of that base type. The declaration of a type always defines its first subtype. The value set associated with all subtypes of a given type must be subsets of its first subtype.
DEFINITION: OBJECTS
Objects are variables and constants that contain values of a given subtype. Objects can be created and intialized as part of: (a) elaborating a declaration; (b) evaluating an allocator, aggregate, or function call; or (c) passing a parameter by copy. Prior to reclaiming storage for an object, it is finalized, if necessary. The value of a constant cannot be changed between its initialization and its finalization.
October 21, 1999 (Revised 2002)
(c) David A. Workman 50
Ada’s Type Hierarchy
Elementary Elementary
AccessAccess
To Objects To Objects
To Subpgms To Subpgms
ScalarScalar
DiscreteDiscrete
RealReal
Floating PointFloating Point
Fixed Point (ordinary)Fixed Point (ordinary)
Fixed Point (decimal)Fixed Point (decimal)
EnumerationEnumeration
Signed IntegerSigned Integer
Modular IntegerModular Integer
CompositeComposite
UniversalUniversal
TaskTask
Untagged Record
Untagged Record
Protected Protected
Tagged RecordTagged Record
without (ND)Discriminantswithout (ND)Discriminants
withDiscriminants(KD,KDD,UD)
withDiscriminants(KD,KDD,UD)
LimitedLimited
PrivatePrivate NonLimited NonLimited
Task and ProtectedTypes are always
LimitedArrayArray
ConstrainedConstrained
UnconstrainedUnconstrained
October 21, 1999 (Revised 2002)
(c) David A. Workman 51
Ada’s Attributes
Access, AlignmentInput, Output, Read, Write,
Size, Unbounded_AccessMax_Size_In_Storage_Elements
Access, AlignmentInput, Output, Read, Write,
Size, Unbounded_AccessMax_Size_In_Storage_Elements
Universal
Storage_SizeStorage_PoolStorage_SizeStorage_Pool
Access
Access(Subpgms)Address, Body_VersionPartition_Id, Version
Access(Subpgms)Address, Body_VersionPartition_Id, Version
Program Units
Range, LengthFirst, Last
Component_Size
Range, LengthFirst, Last
Component_Size
Array
Bit_Order, Class(tagged)Constrainted(objects)
First_Bit, Last_BitPosition
Bit_Order, Class(tagged)Constrainted(objects)
First_Bit, Last_BitPosition
Record
Class, TagExternal_Tag
Class, TagExternal_Tag
Tagged
Callable(Obj)Caller(Entry)
Count, IdentityStorage_Size
Terminated(Obj)
Callable(Obj)Caller(Entry)
Count, IdentityStorage_Size
Terminated(Obj)
Task CountCount
Protected
Base, First, Last, Image,Max, Min, Pred, Succ,
Range, Valid, Value, Width,Wide_Width, Wide_Image,
Wide_Value
Base, First, Last, Image,Max, Min, Pred, Succ,
Range, Valid, Value, Width,Wide_Width, Wide_Image,
Wide_Value
Scalar
Aft, Delta, Fore, Small,Round(Dec), Scale(Dec)Aft, Delta, Fore, Small,Round(Dec), Scale(Dec)
Fixed Point Adjacent, Ceiling, Compose,
Copy_Sign, Denorm, Exponent, Floor, Fraction, Leading_Part,
Machine, Machine_Emin,Machine_Emax, Machine_Mantissa, Model, Model_Emin, Model_Emax, Model_Epsilon, Model_Mantissa,
Model_Small, Remainder,Rounding, Safe_First, Safe_Last,
Scaling, Signed_Zeros, Truncation, Unbiased_Rounding
Adjacent, Ceiling, Compose, Copy_Sign, Denorm, Exponent, Floor, Fraction, Leading_Part,
Machine, Machine_Emin,Machine_Emax, Machine_Mantissa, Model, Model_Emin, Model_Emax, Model_Epsilon, Model_Mantissa,
Model_Small, Remainder,Rounding, Safe_First, Safe_Last,
Scaling, Signed_Zeros, Truncation, Unbiased_Rounding
Floating Point
Digits, Machine_Rounds,Machine_Radix, Machine_Overflows
Digits, Machine_Rounds,Machine_Radix, Machine_Overflows
Real
Val, PosVal, Pos
Discrete
ModulusModulus
Modular Integer
October 21, 1999 (Revised 2002)
(c) David A. Workman 52
Ada’s Type Hierarchy: OperationsUniversal
membership {in, not in }conversion { type( expression )}
qualification { type’( expression )}allocation { new }
Universalmembership {in, not in }
conversion { type( expression )}qualification { type’( expression )}
allocation { new }
IntegerInteger
Arrayconcatenation1 { & }
slicing1 { [i..j] }in-equality2 {<, <=, >, >= }logical3 {not, and, or, xor}
Arrayconcatenation1 { & }
slicing1 { [i..j] }in-equality2 {<, <=, >, >= }logical3 {not, and, or, xor}
Floating Point
Floating Point
Fixed PointFixed Point
Non-limitedassignment { := }equality { =, /= }
Non-limitedassignment { := }equality { =, /= }
CompositeCompositeScalarin-equality { <, <=, >, >= }
Scalarin-equality { <, <=, >, >= }
AccessAccess
Legend
1One-Dimensional Arrays (any)
2 One-Dimensional Arrays (Discrete)
3 One-Dimensional Arrays (Boolean)
Numericadding { +, - }
multiplying { mod, rem, *, / }magnitude { abs }
power { ** }
Numericadding { +, - }
multiplying { mod, rem, *, / }magnitude { abs }
power { ** }
TaskTask
Limited(none)
Limited(none)
Protected Protected
DiscreteDiscrete
{not, and, or, xor }{not, and, or, xor }
ModularModular
BOOLEANBOOLEAN
{and then, or else }{and then, or else }
PrivatePrivateRecordRecord
Introduction to Ada95Declarations
© Dr. David A. Workman
School of EE and CS
University of Central Florida
August 2002
October 21, 1999 (Revised 2002)
(c) David A. Workman 54
Basic Declarations
OBJECTS
[1] Identifier-list : [ aliased ] [ constant ] Subtype-spec [ := Expression ] ;
[2] Identifier-list : [ aliased ] [ constant ] Array-definition [ := Expression ] ; -- anonymous arrays
Subtype-spec => Subtype-name [ Constraint ]Array-definition => array ( Dimension-spec {, Dimension-spec }*) of [ aliased ] Component-spec
Dimension-spec => Subtype-name -- Constrained Arrays => L-bound .. U-bound -- Constrained Arrays
=> Subtype-name range L-bound .. U-bound -- Constrained Arrays
Component-subtype => Subtype-name [ Constraint ]
Constraint => range L-bound .. U-bound -- Scalar constraint => ( Index-subtype {, Index-subtype }* ) -- Index constraint => ( Descriminant-value {, Descriminant-value }* ) -- Discriminant constraint
Index-subtype => Subtype-name [ range L-bound .. U-bound ] => L-bound .. U-bound
October 21, 1999 (Revised 2002)
(c) David A. Workman 55
Basic Declarations TYPES type Base-type is Type-Definition ;
Type Class Type Definition Enumeration => ( Ordered-list-of-literals ) Integer => range L-bound .. U-bound Modular => mod integer -- the modulus > 0 Floating Point => digits integer [ Range ] Fixed Point => delta real Range Decimal Fixed Point => delta real digits integer [ Range ] integer => an expression of some Integer type real => an expression of some Real type Range => range L-bound .. U-bound
Enumeration Type example: type Week_Days is (SUN, MON, TUE, WED, THR, FRI, SAT); position numbers => 0 1 2 3 4 5 6
Integer Type example: type C_Char is range -128..127; position numbers => -128, -127, …, 0, +1, +2, …, +127
October 21, 1999 (Revised 2002)
(c) David A. Workman 56
Basic DeclarationsMORE TYPES
type Base-type is Type-Definition ;
Type Class Type Definition
Arrays => array ( Dimension-spec { , Dimension-spec }* ) of [ aliased ] Cmpont-subtype
Basic Records => record Cmpont-decl { Cmpont -decl } end record;
Access ( Objects) => access [ all | constant ] Subtype-name [ Constraint ]
Cmpont-subtype => Subtype-name [ Constraint ] Cmpont-decl => Cmpont-name { , Cmpont-name } : Cmpont-subtype [ : = expression ]; Dimension-spec => Subtype-name [range L-bound .. U-bound ] | L-bound .. U-bound
=> Subtype-name range <> -- Unconstrained Arrays
Constraint => range L-bound .. U-bound -- Scalar types => ( Index-subtype { , Index-subtype } ) -- Unconstrained
Arrays => ( Descriminant-value {, Descriminant-value } ) -- Types with known
-- Descriminants
Constrained Arrays
Discriminated Record, Protected and Task types
October 21, 1999 (Revised 2002)
(c) David A. Workman 57
Declaration Examples
TYPES
type Colors is ( Red, Orange, Yellow, Green, Aqua, Blue, Purple );type Grade is ( ‘F’, ‘D’,’C’,’B’,’A’); -- A Character type (subclass of Enumeration)type Meters is digits 7; -- Unconstrained Floating Point type (no range constraint)type Age is range 0..100; -- An Integer typetype Byte is mod 256; -- A Modular typetype Char is range -128..127; -- An Integer typetype String_Ptr is access STRING; -- An Unconstrained Access (pointer) typetype Vector is array(1..3) of aliased Meters; -- Constrained Array typetype Matrix is array( POSITIVE range <>, -- 1st dimension
INTEGER range <>) -- 2nd dimension of FLOAT range -1.0..1.0e3; -- Unconstrained Array type
type Person is record -- Non-discriminated Record type
Name: STRING(1..25); Age: NATURAL := 0; end record;
October 21, 1999 (Revised 2002)
(c) David A. Workman 58
Declaration Examples
OBJECTS
X,Y,Z : aliased FLOAT; -- aliased variablesPi : constant := 3.1415926; -- Named numberZero: aliased constant FLOAT := 0.0; -- aliased constantBlank: constant CHARACTER := ‘ ‘; -- normal variablePrice: constant STRING := “$12.95”; -- normal constantDone: BOOLEAN := FALSE; -- normal variableA: Matrix; -- array variableT: array( 1..5, ‘A’..’Z’) of aliased STRING(1..15); -- anonymous arrayP: String_Ptr := T(1,’C’)’ACCESS; -- normal pointer variable
October 21, 1999 (Revised 2002)
(c) David A. Workman 59
Access Type Declarations
TYPES of FORM [1] (continued)
Class Access => access [all | constant ] Access-subtype -- access to objects => access [ protected ] Subprogram-spec -- access to subprograms
Access-subtype => Subtype-name [ Constraint ] Subprogram -spec => procedure [ ( Parameter-specs ) ]
=> function [ ( Parameter-specs ) ] return Subtype-name
RULES:(1) If all appears in an access type definition, then the type is considered a general-access-to-variable.(2) If constant appears in the definition, then the type is considered a general-access-to-constant. Otherwise, the access type is pool-specific..
October 21, 1999 (Revised 2002)
(c) David A. Workman 60
Access Types
ACCESS TYPES (continued)
RULES:(1) Values of Access-To-Constant types can point to dynamic variables, aliased (declared) variables, and aliased (declared) constants of some designated subtype, but the objects pointed to by such access values cannot be changed (they are treated as being constants).
(2) Values of General-Access-To-Variable types can point to dynamic variables or aliased (declared) variables, but not to constant objects.
(3) Values of Pool-Specific access types can only point to dynamically allocated variables.
Dynamic Variables
Aliased VariablesAliased Constants
General-Access-To-Variables
Pool-Specific-Variables General-Access-To-Constant
October 21, 1999 (Revised 2002)
(c) David A. Workman 61
Declaration Examples
-- S is some previously defined subtype type TP is access S; -- Pool Specific access type type TA is access all S; -- General-Variable access type type TC is access constant S; -- General-Constant access type type Fn_Ptr is access function (X: access S) return S; -- Access to Function type -- Dynamic Variable: new S X: aliased S; -- Aliased (declared) Variable C: aliased constant S := exp; -- Aliased (declared) Constant P: TP := new S; -- OK Q: TA := new S; -- OK Z: TC := new S; -- OK function “abs”( X: access S) return S is begin … end “abs”; FP: Fn_Ptr := “abs”’ACCESS;begin
ACCESS TYPES
[1] P := X’ACCESS; -- ILLEGAL! [2] Q := X’ACCESS; -- OK [3] Q := C’ACCESS; -- ILLEGAL [4] Z := X’ACCESS; -- OK [5] Z := C’ACCESS; -- OK [6] Z.ALL := Q.ALL; -- ILLEGAL [7] Q.ALL := FP(P); -- OK [8] P.ALL := FP(Q); -- OK [9] P.ALL := FP(Z); -- ILLEGAL (actual parameter must be General-Variable access type)
SeeNotesView
October 21, 1999 (Revised 2002)
(c) David A. Workman 62
Subtype Declarations
subtype Subtype-name is Existing-subtype [ Constraint ] ;
Constraint => range L-bound .. U-bound -- Scalar => digits integer [ range L-bound .. U-bound ] -- Floating or Fixed Decimal => delta real [ range L-bound .. U-bound ] -- Ordinary Fixed Point => ( Index-subtype { , Index-subtype }* ) -- Unconstrained Array => ( Descriminant-value { , Descriminant-value }* ) -- Types with Descriminants
DEFINITION
RULES:(1) Subtype declarations define a new named subtype by imposing a constraint on the value set of an existing base type indicated by Existing-subtype. Constraint defines this constraint.(2) Subtypes (anonymous or named) are used to limit the set of values a variable, parameter, or function result can assume.(3) The Constraint must define a compatible subset of the value set defined by Existing-subtype.(4) Every base type declaration (e.g. INTEGER, STRING) implicitly declares a subtype by the same name, its first subtype.(5) Excepting Scalar subtypes, if Constraint is specified, then Existing-subtype must be unconstrained.
October 21, 1999 (Revised 2002)
(c) David A. Workman 63
Subtype Declarations
EXAMPLES (Subtypes)
-- Named subtypes: type Dollar is delta 0.01 range -1.0e5..+1.0e5; -- delta constraint type FLOAT is digits 7; -- unconstrained floating point subtype subtype NATURAL is INTEGER range 0..INTEGER’LAST; -- Range constraint subtype Name_Subtype is STRING(1..35); -- Index constraint subtype Rectangle is Polygon(Sides => 4); -- Discriminant constraint subtype Non_Negative is NATURAL; -- No additional constraint subtype Small_Float is FLOAT digits 5 range -1.0e3..+1.0e3; -- Digits constraint subtype Deca_Dollar is Dollars delta 10.0; -- Delta constraint
-- Anonymous subtypes: X : FLOAT range -10.0..150.0; A : STRING(1..25); T : array(1..5) of INTEGER range 0..100; task Control;
October 21, 1999 (Revised 2002)
(c) David A. Workman 64
Subtype Declarations
CONTRAINED (C) vs. UNCONSTRAINED (~C) SUBTYPES
A subtype is unconstrained if its base type has unknown discriminants, or if it allows a range, index, or discriminant constraint, but does not impose one. All indefinite subtypes are unconstrained. All class-wide types are unconstrained.
DEFINITE(D) vs. INDEFINITE (~D) SUBTYPES
A subtype is indefinite if its declaration does not provide the compiler with enough information to create objects in that subtype. The subtypes considered to be indefinite include the unconstrained array types, types declared with unknown discriminants, types with unconstrained discriminants without defaults, and the class-wide types; otherwise, a subtype is considered to be definite.
October 21, 1999 (Revised 2002)
(c) David A. Workman 65
Subtype Declarations
Type Class Subtype Description Constrained (Yes | No)
Definite (Yes | No)
Enumeration All subtypes Yes Yes Integer All subtypes Yes Yes Modular All subtypes Yes Yes Fixed Point All subtypes Yes Yes Floating Point Subtypes declared with range constraint Yes Yes Floating Point Subtypes declared only with digits1 No Yes Unconstrained Array
First subtype No No
Constrained Array All subtypes Yes Yes Record(ND)2 All subtypes Yes Yes Record (KD)2 First subtype No No Record (KDD)2 First subtype No Yes Record(UD)2 All subtypes No No
NOTES:1The predefined type FLOAT is an unconstrained floating point type.2 ND = No Discriminants; KD = Known Discriminants(without Defaults); KDD = Known Discriminants with Defaults;UD = Unknown Discriminants.
October 21, 1999 (Revised 2002)
(c) David A. Workman 66
Subtype DeclarationsType Class Subtype Description Constrained
(Yes | No) Definite
(Yes | No) Protected Same as Record Types … … Task Same as Record Types … … Class-Wide3 All subtypes No No Access to Subprogram
All subtypes Yes Yes
Access to Unconstrained Array
First subtype No Yes
Access to Discriminated Type
First subtype No Yes
Access to Floating Point4
All subtypes No Yes
Access to all other
All subtypes Yes Yes
NOTES:3 All class-wide types are of the form: T’CLASS, where T is a tagged record type. All class-wide subtypes are indefinite and unconstrained because they are discriminated types without defaults (the tag is a hidden discriminant).4 Floating Point subtypes to which no range constraint has been declared. The ARM clearly states that subtypes of this form are unconstrained. However, it is inconsistent in its description of access types. Generally, access to any unconstrained type is considered to be unconstrained. All access types are definite types because access objects can be created and initialized to null without knowing the subtype of the object they point to.
October 21, 1999 (Revised 2002)
(c) David A. Workman 67
ExpressionsExpression => Relation { and Relation } | Relation { and then Relation }
=> Relation { or Relation } | Relation { or else Relation }=> Relation { xor Relation }
Relation => Simple-exp [ Relop Simple-exp ]=> Simple-exp [ not ] in Range => Simple-exp [ not ] in Subtype-name
Simple-exp => [ Unary-addop ] Term { Binary-addop Term }*
Term => Factor { Mulop Factor }*
Factor => Primary [ ** Primary ] => abs Primary => not Primary
Primary => Numeric-literal | String-literal => null => Name => Aggregate => Qualified-expression => Allocator => ( Expression )
Relop = { <, >, <= , >= , = , /= }Relop = { <, >, <= , >= , = , /= }
Unary-addop = { +, - }Unary-addop = { +, - }
Binary-addop = { +, - , &}Binary-addop = { +, - , &}
Mulop = { *, /, mod, rem }Mulop = { *, /, mod, rem }
October 21, 1999 (Revised 2002)
(c) David A. Workman 68
Expressions
ARRAY COMPONENTS and SLICES
Indexed-component => Array-prefix ( Index-exp1, … Index-expn )
Array-prefix denotes an array object (or value) having n dimensions.Index-expi must denote a discrete-valued expressions belonging to the indexsubtype of the ith dimension.
Array-slice => Array-prefix ( Discrete-range )
Array-prefix denotes an array object (or value) having 1 dimension!Discrete-range => L-bound .. U-bound | Subtype-name | Range-attribute-exp must specify a subrange of the index subtype for Array-prefix. The value of this expression is a 1-dimensional array of the same type as Array-prefix and having bounds deter-mined by Discrete-range.
October 21, 1999 (Revised 2002)
(c) David A. Workman 69
Expressions
ARRAY AGGREGATES (1 of 2)
Array-aggregate => ( Cexp1, Cexp2, … , Cexpn ) -- [1] => ( Cexp1, Cexp2, … , others => Cexp ) -- [2] => ( choice-list => Cexp {, choice-list => Cexp }) -- [3]
Choice-list => Choice1 | … | Choicen
Choice => Index-exp => L-bound .. U-bound => others
In the above, Cexp denotes an expression that defines the value of one or more componentsof an array structure. [1] and [2] are positional aggregates. In [1], the component expressions must correspond 1-1 with values of the index subtype of the first dimension of an array type, T,determined by context external to the aggregate. If the implied type, T, of the aggregate is for an N-dimensioned array, then the component expressions Cexp1, Cexp2, … , Cexpn must denote (N-1)-dimensional array objects, values or aggregates conformant to the N-1dimensional subarray represented by dimensions 2 .. N of T.
In [2], the positional expressions define only the first K components and the others expressiondefines all remaining components (at least one).
October 21, 1999 (Revised 2002)
(c) David A. Workman 70
Expressions
ARRAY AGGREGATES (2 of 2)
Array-aggregate => ( Cexp1, Cexp2, … , Cexpn ) -- [1] => ( Cexp1, Cexp2, … , others => Cexp ) -- [2] => ( choice-list => Cexp {, choice-list => Cexp }) -- [3]
Choice-list => Choice1 | … | Choicen
Choice => Index-exp | L-bound .. U-bound | others
[3] is an association aggregate, where Choice-list designates a set of index values and thecorresponding Cexp defines the component value at each of those index positions. EachChoice designates a single index position, a range of index positions, or in the case of others, all remaining index positions. The others Choice can only be used once in the aggregate and it must occur in the last Choice-list by itself (list with one choice).
No two Choice values can designate the same index position, and taken together must designate every index position defined by the array type, T.
Choice expressions must be static with the following exceptions:( others => Cexp )( Index-exp => Cexp )( L-bound .. U-bound => Cexp )
October 21, 1999 (Revised 2002)
(c) David A. Workman 71
Array Aggregates
type Week_Days is (SUN, MON, TUE, WED, THR, FRI, SAT);type Work_Hrs is ( AM_8, AM_9, AM_10, AM_11, PM_1, PM_2, PM_3,PM_4);type Activities is ( COT4210, COP4232, COP5021, Office, Meeting, Free );subtype Courses is Activities range COT4210..COP5021;type Schedule_Type is array( Work_Hrs, Week_Days range MON..FRI) of Activities; ---Fall_Schedule: Schedule_Type := ( AM_8..AM_11 => (others => Free), PM_1 | PM_2 => ( MON | WED => Office, others => Free), PM_3 => (MON | FRI => Free,
TUE | THR => COT4210 WED => Meeting),
PM_4 => (TUE | THR => Office, others => Free ));
Examples
October 21, 1999 (Revised 2002)
(c) David A. Workman 72
Array Aggregates
type Assignments is (Quiz1, Quiz2, Exam1, Exam2, Final );type Grade_Type is (‘F’,’D’,’C’,’B’,’A’, ‘X’);subtype Score_Type is NATURAL range 0..100;type Grade_Info is record Grade: Grade_Type; Score : Score_Type; end record;---Nstudents: POSITIVE := User_Input; -- User_Input is a functiontype Book_Type is array(POSITIVE range 1..Nstudents, Assignments ) of Grade_Info;type String_Ptr is access STRING;type Names_Type is array( Book_Type’RANGE ) of String_Ptr;---Grade_Book: Book_Type := (1..Nstudents => ( others => (Score => 0, Grade => ‘X’)));
Examples
October 21, 1999 (Revised 2002)
(c) David A. Workman 73
Ada Attributes
Attribute Definition Type or SubtypeS’FIRST Denotes the first value in the value set defined by subtype S SS’LAST Denotes the last value in the value set defined by subtype S SS’POS(x) Denotes the position number of x in S’BASE (S’BASE --> UI)S’VAL(n) Denotes the value (x) in S’BASE for which S’POS(x) = n (UI --> S’BASE)S’IMAGE(x) Denotes the STRING literal denoting the value of x. (S’BASE --> STRING)S’VALUE(y) Denotes the value (x) in S’BASE represented by STRING y (STRING --> S’BASE)S’PRED(x) Denotes the largest value y:(y < x ) in S’BASE. S’BASES’SUCC(x) Denotes the smallest value y:( x < y) in S’BASE S’BASES’WIDTH(t) Denotes max{ S’IMAGE(x)’LENGTH : x in S } UIS’MAX(x,y) Denotes the larger of x and y in S’BASE S’BASE x S’BASE -> S’BASES’MIN(x,y) Denotes the smaller of x and y in S’BASE S’BASE x S’BASE -> S’BASE
Scalar Base Types
IMAGEVALUE
MAXMIN
FIRSTLAST
WIDTH
POSVAL
DiscreteSubtypes
Only
ScalarSubtypes
PREDSUCC
October 21, 1999 (Revised 2002)
(c) David A. Workman 74
Ada Attributes
type Alpha is ( A, B, AB, ‘A’, ‘B’);subtype Alpha2 is Alpha range B..’A’;type Age is range NATURAL’FIRST..125;--------------------------------------------------------------- VariablesX: Alpha2 := AB;Y: Age range 0..21 := 0;---------------------------------------------------------------beginAlpha’FIRST = AAlpha’LAST = ‘B’Alpha2’FIRST = BAlpha2’PRED(X) = BAlpha2’PRED(B) = AAge’SUCC(Y+50) = 51Age’PRED(Y) = CONSTRAINT_ERRORY’WIDTH = 3Age’WIDTH = 4Alpha’VAL(3) = ‘A’Alpha’POS(X) = 2Alpha’IMAGE(X) = “AB”Alpha’IMAGE(Alpha’SUCC(AB)) = “‘A’”Alpha’POS(Alpha2’VALUE(“B”)) = 1 or 4 or CONSTRAINT_ERROR?
Examples
October 21, 1999 (Revised 2002)
(c) David A. Workman 75
Ada Attributes
EXPRESSION BASE TYPE VALUE Beta’WIDTH
Alpha’POS(Three)
Alpha’IMAGE(Alpha’VAL(4))
Age’WIDTH > 5
Alpha’VAL(Beta’POS(One))
Alpha’IMAGE( Alpha’SUCC(‘B’))
A’FIRST(2)
A’LAST
A
A(Two,Two)
Alpha’POS( Three ) > Beta’POS(One)
type Alpha is ( One, Two, Three, ‘A’, ‘B’, C);type Beta is ( Three, Two, One );subtype Age is NATURAL range 0..100;A: array( Alpha, Beta) of Age := (Alpha => (Beta => 50));B: Beta := Beta’(Two);
Exercises
Introduction to Ada95Statements
Dr. David A. Workman
School of EE and CS
University of Central Florida
© May 1996 (Revised 2002)
October 21, 1999 (Revised 2002)
(c) David A. Workman 77
Statements
• Assignment
• raise
• procedure-call
• return
• basic-loop
• exit
• for-loop
• while-loop
• conditional (if [elsif] [else])
• case
• block
• goto
• entry-call
• accept
• select
• requeue
• delay
• delay until
• abort
Basic StatementsBasic Statements Tasking StatementsTasking Statements
Labels:<<Identifier>> Statement ;
Statement names:Identifier : Statement ;
Labels areonly used in
goto statements!!
Labels areonly used in
goto statements!!
Statement names are
used in loop exit statements!!
Statement names are
used in loop exit statements!!
October 21, 1999 (Revised 2002)
(c) David A. Workman 78
Assignment StatementsDefinition
Variable := Expression;
RULES:(1) The base type of Expression must agree with that of Variable and neither can be limited. Otherwise, a compile-time error will occur.
(2) If the value of Expression does not belong to the subtype of Variable, a CONSTRAINT_ERROR exception will be raised at runtime.
(3) If Expression denotes a Universal Real(Universal Integer) value, and the base type of Variable belongs to the class of Real(Integer) types, then conversion is implicit.
(4) For array assignments, the shape (# dimensions), style (Index base types) and size( dimension length) of Variable and Expression must be the same.
(5) It Variable belongs to a class-wide type, T’CLASS, then Expression shall be dynamically tagged, or of type T and tag-indeterminant. The tag of Expression must always agree with that of Variable.
October 21, 1999 (Revised 2002)
(c) David A. Workman 79
Assignments
EXAMPLES (Array assignments)
type Matrix is array(CHARACTER range <>, POSITIVE range <>) of BOOLEAN;type Table is array(CHARACTER range ‘A’..‘Z’, POSITIVE range 1..5) of BOOLEAN;--A: Matrix(‘A’..’Z’, 6..10); -- 26 x 5B: Matrix(‘A’.. ‘E’, 1..26); -- 5 x 26C: Table; -- 26 x 5D: Matrix(CHARACTER’VAL(CHARACTER’POS(1))
..CHARACTER’VAL(CHARACTER’POS(26)), 11..15);begin
A := B; -- Compile time error (size mismatch) A := C; -- Compile time error ( base type mismatch) A := D; -- OK! D := A; -- OK!
October 21, 1999 (Revised 2002)
(c) David A. Workman 80
Assignments
EXAMPLES( continued )
type Age is range 0..120;subtype Old_Age is Age range 80..Age’LAST;subtype Teen_Age is Age range 13..19;A: Age;B: INTEGER;C: Old_Age;D: INTEGER range -25...0;X: STRING(1..10);Y: STRING(51..60);U: array(1..10) of CHARACTER;V: STRING(X’RANGE) := X; -- X and V have same index boundsW:STRING(1..X’LENGTH) := Y; -- W’LENGTH = X’LENGTH = Y’LENGTHbegin --------------------------------------------------------------------------------------------- A := B; -- Compile error: base type mismatch C := 50; -- CONSTRAINT_ERROR A := C; -- Always OK. D := B; -- CONSTRAINT_ERROR possible C := D; -- Compile error: base type mismatch U := X; -- Compile error: base type mismatch ( U has an anonymous type)
October 21, 1999 (Revised 2002)
(c) David A. Workman 81
LOOP StatementsDefinition
[ name: ] [ Head ] loop -- At least one executable statements -- Any number of loop exit statements end loop [name];
Head =>
for Parameter in [reverse] Subtype |while Condition
RULES:(1) Loop names are optional. Loop names are not labels!
(2) The for loop Parameter is read-only and defined local to the loop body; its base type and value set are determined by the Subtype specification.
(3) The Subtype can be specified as a range, a subtype name, a subtype name and range constraint, or by an array ‘RANGE attribute. If the value set defined by the Subtype specification is empty, the loop will not be executed.
(4) If in is specified, the for loop Parameter takes on successively larger values in the range Subtype’FIRST..Subtype’LAST beginning with Subtype’FIRST. If in reverse is specified, Parameter begins with Subtype’LAST and takes on successively smaller values in that range.
October 21, 1999 (Revised 2002)
(c) David A. Workman 82
Loops EXAMPLE
Outer: while Condition1 loop if Condition2 then goto Fine; end if;
Inner1: for i in ‘A’.. ‘Z’ loop ... exit Outer when Condition3; ... exit when Condition4; end loop Inner1; -- Inner2: for i in reverse NATURAL range 1..100 loop ... end loop Inner2; -- Inner3: for i in A’RANGE loop ... end loop Inner3;end loop Outer;Statement;<<Fine>> -- This is a label
not Condition1Condition2
Condition3
October 21, 1999 (Revised 2002)
(c) David A. Workman 83
Loops
procedure Sort( N,M: T ) is A: array(N..M) of FLOAT; Temp: FLOAT;begin -- Fill A
Outer: for i in A’FIRST ..T’PRED(A’LAST) loop
Inner: for i in T’SUCC(Outer.i)..A’LAST loop if A(Outer.i) > A(i) then
Temp := A(Outer.i);
A(Outer.i) := A(i);
A(i) := Temp;
end if; end loop Inner;
end loop Outer;
end Sort;
loop namesloop names
loop parameter (Outer.i )loop parameter (Outer.i )
loop parameter (Inner.i )loop parameter (Inner.i )
EXAMPLE