BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis...

112
SLIDES Introduction to Ada 83 Programming Page 1 BASICS OF ADA PROGRAMMING Frequent criticisms of Ada are its complexity the slowness of Ada compilers the slowness of the code produced by Ada compilers the relative difficulty of low-level programming (direct control of the computer hardware) C programmers also complain that Ada programs take a lot of typing at the keyboard (too many words and not enough single-symbol abbreviations) as well as being inflexible in many ways. The Ada language standard is known as ANSI/MIL- Std-1815a and was the result of many years of studies and discussion by an international group of researchers and experts. Funding was provided by the U.S. Department of Defense (DoD) The Ada 9X effort began in 1988 and by mid-1994 a definition for the new Ada version was complete. Ada is a much more complex language than C and Pascal but the complexity of C++ is about the same order of magnitude as Ada 95. So complexity

Transcript of BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis...

Page 1: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 1

BASICS OF ADA PROGRAMMINGFrequent criticisms of Ada are

its complexitythe slowness of Ada compilers

the slowness of the code produced by Ada compilersthe relative difficulty of low-level programming (direct control of the computer hardware)C programmers also complain that Ada programs take a lot of typing at the keyboard (too many words and not enough single-symbol abbreviations) as well as being inflexible in many ways.

The Ada language standard is known as ANSI/MIL-Std-1815a and was the result of many years of studies and discussion by an international group of researchers and experts. Funding was provided by the U.S. Department of Defense (DoD)The Ada 9X effort began in 1988 and by mid-1994 a definition for the new Ada version was complete.Ada is a much more complex language than C and Pascal but the complexity of C++ is about the same order of magnitude as Ada 95. So complexity does not seem to be the factor that discourages programmers from using a language!This complexity of Ada and C++ is also reflected in compilation time and machine-code image size. Both Ada and C++ compilers execute many checks and analyses that are not made for C and FORTRAN. Ada and C++ also have to include large amounts of code for run-time support which inflates the executable code size considerably.Most of these criticisms arise because Ada was designed

to be as easy as possible to maintain (maintain = correct and enhance)

Page 2: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 2

to allow the compiler and run-time support to detect as many errors as possible and give clear error messages to programmers (the opposite of C)to support large teams of programmers working on same projectto be used for a specific type of application, viz. embedded control systems--not writing operating systems (C), teaching programming and compiler writing (Pascal), extensive text and financial transaction processing (COBOL and PL/I)

Ada is designed to be a language for code that has to be read more frequently than it is written. The extra typing involved in writing an Ada program as compared to C is intended to make programs more readable and easier to understand and maintain.Ada developed packages as the vehicle for program libraries whereas C++ provides the class concept. The package is deliberately made to look like a larger scale unit than a class but the difference is superficial. Both can be used in similar ways to create reuse libraries.The Ada language was designed to be a universal language for real-time embedded systems to be used in aircraft, space and weapons control systems, air traffic control, railroad control, power plant control systems, etc. Correctness and reliability of the programs written using the langauge are fundamental considerations in the language design.Ada statements:The reference used most consistently in the material that follows is Norman Cohen, Ada as a second language , McGraw-Hill 1986. All statements end in a ‘;’--even before end (Pascal) or ‘}’ (C). In Pascal, the ‘;’ may be omitted before the reserved word end. This is because ‘;’ is a separator in that language. In Ada, as in C and

Page 3: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 3

PL/I, the symbol ‘;’ is a terminator and is always placed at the end of statements.‘Not equal’ is the combination ‘/=’. The symbol <> (Pascal) has another use. The symbol combination ‘<>’ that is used for not equal in Pascal has a different meaning in Ada. The symbol combination ‘/=’ used in Ada is more similar to that used in C, namely ‘!=’.A block of code has the form:

begin...

end ;Upper/lower case is NOT significantConditionals:

if ... then ... end if ;if ... then ... else ... end if ;

The use of end if in Ada removes the dangling else problem of Algol 60 and Pascal. No begin ... end is necessary after then or else, e.g.

if x < y then x := x + 1;

y := y - 1;z := (x + y)/2 ;

else y := y - 1;z := (x + y) / 2;

end if ;Extended conditionals:To better structure a sequence of nested if’s, we can use elsif:

if ... then ...elsif ... then

Page 4: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 4

...elsif ... then ...else ...end if ;

Here we can compare the use nested if ... then ... else...end if’s, which implies excessive indentation and numerous end if’s, with the use of the ‘elsif’ construct. Algol 68 used the same idea and several other languages also use it (not Pascal):

if x < 0 then put (“Negative input values are invalid”);

elsif Even(x) -- assume “Even” is a user defined functionthen put(“The input should be an odd number”);

elsif x > N then put(“Input values must be less than “ &

integer’image(N)) ;else Process(x) ;end if ;if x < 0

then put (“Negative input values are invalid”);else if Even(x)

then put(“The input should be an odd number”);else if x > N

then put(“Input values must be less” & “ than “ & integer’image(N)) ;

else Process(x) ;end if ;

end if ;end if ;

Loops:

Page 5: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 5

loop ... end loop ; Note that the reserved words loop, end loop enclose the statements in the body of the loop and therefore begin/end are not needed.Loop control:

for var in ...loop ... end loop ;

while ...loop ... end loop ;

Note that the ‘var’ in the for loop is not declared earlier: the for loop creates a new variable for the loop only. It is a different variable to any defined previously and ceases to exist after the loop ends. Examples:

for J in 1..10loop

A(J) :=J2 - 2 J ;-- array index is enclosed in parentheses, not square brackets

-- the symbol combination ‘’ denotes exponentiationB(J) := 2 J + 1;

end loop ;while X /= Yloop

if X > Y then X := X - Y ;else Y := Y - X;

end loop ;A loop does not need a ‘for’ or ‘while’ to control it:

Page 6: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 6

loop ... exit when ...; ...end loop ;loop

if X > Y then X := X - Y ;else Y := Y - X;

end if ;exit when X = Y;

end loop ;Ada has a case statement (like Pascal; somewhat like the switch of C):

case var iswhen ... | ... | ... => ...when ... =>...when others => ...

end case ;Unlike C only one option is ever executed. Unlike most languages, all possible values of ‘var’ must be accounted for in the alternatives. The when others option is not necessary but is convenient. No ‘break’ (C) is used.Assume C is a variable whose type is integer in the range 1 though 10:

Page 7: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 7

begincase C iswhen 1..3 => put(“Small number”);when 4 | 5 => put(“Medium number”);when 6..10 => put(“Larger number”);end case ;-- when others was not used

end ;Ada procedures:Ada does NOT use the keyword PROGRAM (Pascal) or main (C). Ada programs will have a main procedure but it is only distinguished from other parts of the program by the order of compilation and linking.

with ..., ..., ..., ...; -- the context clauseprocedure ...* is -- Pascal programmers, note the ‘is’

... -- declaration partbegin ...end ...*;

* it is correct and helpful but not necessary to put the name of the procedure after the final end.So far we have seen a program consisting of only one procedure (Fig. 1). Typically Ada programs consist of many separate compilation units--pieces that are compiled separately and stored in a program library.

Subprogram

Figure 1

Page 8: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 8

The most significant Ada construct for encapsulating closely related data and operations is the package.

Packages (Fig. 2):Packages always have a specification (like a MODULA-2 definition or a C header file)Packages that declare subprograms (procedures or functions) in their specification must then have a package body where the body of the subprogram is given.In this case a procedure must have a declaration and a body (as indicated in Fig. 3)

Exported entities: Types Constants Variables Exceptions Procedures Functions Tasks (include. entries) Nested package specifications

Package specification Package body

Local types, constants,variables, exceptions,subprograms, tasks andpackages

Implementations (bodies)of exported subprogramsand tasks

Optional initialization codebegin ...end;

Private part:(full declaration ofprivate types)

Figure 2

Page 9: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 9

Subprograms that are called from within the program may require parameters.

Nested procedures are permitted (unlike C) and may have parameters.If a procedure is going to be placed in a package and will be used by other parts of a program, the procedure declaration will contain the parameters and will appear in a package specification:

package P is...procedure Prompt_For_Input

(Message : in String; Value : out Integer);...

end P;The corresponding procedure body appears in the package body:

package body P is...procedure Prompt_For_Input

(Message : in String; Value : out Integer) is-- perhaps some declarations

Subprogram body

Subprogramspecification

Figure 3

Page 10: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 10

begin...

end Prompt_For_Input;...

end P;

Page 11: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 11

Object And Type DeclarationsWe have seen the basic structure of a procedure:

procedure ... is... -- declarations

begin... -- statements

end ;Examples. A procedure without a separate declaration:

with Text_IO;procedure Proc1(X : Character) is

Y : Character ;begin

Y := Character’SUCC(X) ;Text_IO.put(Y);

end ;A procedure may have a separate declaration:

procedure Proc1(X : Character);Corresponding body:

with Text_IO;procedure Proc1(X : Character) is

Y : Character ;begin

Y := Character’SUCC(X) ;Text_IO.put(Y);

end ;Declaration of integers variables (a variable is one kind of Ada object--it is given a representation in the computer):

Page 12: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 12

Next : Integer;One_Earlier, Two_Earlier : Integer := 1;Amount_Printed : Integer RANGE 0..100; -- constrained

Constant declarations are like variable declarations with the word constant after the colon:

Stopping_Value : constant Integer := 0;Other variable declarations:

Letter1 : Character := ‘}’;Truth_Value1 : Boolean := true;Message1 : String (1..10) := “Hi there!!”;Real_Number1 : Float := 0.54;Letter2 : Character;Truth_Value2 : Boolean;Message2 : String (1..10);Real_Number2 : Float;

Next we have to see how to declare user-defined typesInteger types:

type Year_Type is range 1901..2099;Variables of type Year_Type:

Current_Year, Year_Of_Birth : Year_Type;Next_Leap_Year : Year_Type := 1992;Turn_Of_Century : constant Year_Type := 2000;

Error because of constraint: Independence_Year : Year_Type := 1776;

The type Integer is predefined and on a 16-bit PC is probably:type Integer is range -65768..65767;

Similarly, Float is a predefined floating-point type, we shall skip the other details about real numbers for now. Ada distinguishes floating-point and fixed-point types.

Page 13: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 13

Enumeration types:type Traffic_Signal_Type is (Red, Yellow, Green);type Rainbow_Type is

(Red, Orange, Yellow, Green, Blue, Indigo, Violet);Note that the same enumeration literals may appear in different types of the same program (overloading).We can distinguish them as Traffic_Signal_Type.Green and Rainbow_Type.Green, while Orange is unique. For example,

Traffic_Signal_Type.Red..Green has 3 elementsRainbow_Type.Red..Green has 4 elements

Integers and enumeration types are known as discrete types and may be used for index ranges.Ranges may have 1 element or be empty by writing the upper and lower limits backwards.Arrays:

type Table_Type isarray (1..10, 0..10) of Float range 0.0..100.0;

The ranges of the indices are constrainedtype Rainbow_Type is

(Red, Orange, Yellow, Green, Blue, Indigo, Violet);type Person_Type is (James, Janet, Joan, John);Likes : array (Person_Type, Rainbow_Type) of Boolean;type Frequency_Table_Type is array(‘A’..’Z’) OF Integer;Frequency_Table : Frequency_Table_Type;Next_Char : Character;...Frequency_Table (Next_Char) := 10;

Unconstrained arrays:type Matrix_Type is

Page 14: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 14

array (Integer range <>, Character range <>) of Float;Matrix : Matrix_Type (10..50, ‘E’..’e’);>>>> Objects cannot be unconstrained <<<<

For now, only types and formal parameters of procedures can be unconstrained--they do not have to be represented in the computer. variables must be represented and therefore their size needs to be known.Unconstrained ranges, and constrained ranges cannot be mixed.If you start getting errors when you program with unconstrained arrays then read pages 83 and 84 to see if you have one of the errors mentioned by Cohen.Note that variables of type string are constrained (starting the index at 1 is not necessary, but it is normal):

Var1 : String(1..10) := “0123456789”;Var2 : String(1..5); Var3 : String(1..15);...Var2 := “ABCDE”;Var3 := Var1 & Var2;

Record types:type Buffer_Type is

record Length : Integer range 0..128;Content : String(1..128);

end record ;

Page 15: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 15

Some fields may have default values:type Buffer_Type is

record Length : Integer range 0..128 := 0;Content : String(1..128);

end record ;Variables whose type is a record with default values will automatically have their fields initialized by the defaults, unless overridden.Notice how the Get_Line for strings automatically returns the length of the input string:

Text_IO.Get_Line(Input_Sentence.Content,Input_Sentence.Length);

The expression Input_Sentence.Content(Input_Sentence.Length) then accesses the string in its final valid position.Note that records may be assigned in a single instruction:

Statement_List (Statement_Count) := Input_Sequence;Expressions (see Cohen 4.3.3) are allowed in type declarations:

package P1 isfunction F1 return Integer;function F2 return Integer;function F3 return Integer;

end P1;with P1;procedure Proc is

X : Integer range P1.F1..P1.F2 := P1.F3; -- legal but-- dangerous see later remarks on “elaboration”

begin...

end Proc;

Page 16: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 16

Arrays have a special property which is the anonymous array type. If variables of an array type are declared, then an anonymous array type is created and each time the anonymous type is DIFFERENT.

Input_List, Output_List : array (1..Num_Inputs) of Integer;The type of Input_List is something like Anon_Array_Type_One and the type of Output_List is something like Anon_Array_Type_Two. The following assignment is illegal:

Input_List := Output_List;because the types are different. The declaration above is completely equivalent to

Input_List : array (1..Num_Inputs) of Integer;Input_List : array (1..Num_Inputs) of Integer;

And very different fromTYPE Array_Type IS array (1..Num_Inputs) of Integer;Input_List_1, Output_List_1 : Array_Type;

Here the assignment is perfectly legal.Input_List_1 := Output_List_1;

Some convenient ways of initializing arrays are:Input_List, Output_List : Array_Type := (others => 0);Input_List, Output_List : Array_Type

:= (1..Num_Inputs-3 => 5, Num_Inputs-2..Num_Inputs => 6);Arr : array (1..3, 4..8) of Integer := ((56, 78, 21, 19, 99), (0, 4,

299, 83, 0), (1, 2, 3, 4, 5));Arr : array (1..3, 4..8) of Integer :=

(1 =>(4=>56, =>78,6=>21,7=>19,8=>99),2 =>(4=>0,5=>4,6=>299,7=>83,8=>0),

3 =>(4=>1,5=>2,6=>3,7=>4,8=>5))

Page 17: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 17

Access Types (Pointers)We assume familiarity with the concept of pointers.Pointers types are declared as follows:

type Letter_Pointer_Type is accessCharacter range ‘A’..’Z’;

type Name_Pointer_Type is access String;Note that constraints are not necessary in the access type declaration. Access variables are declared in the normal way:

Name_Ptr : Name_Pointer_Type;Letter_Pointer : Letter_Pointer_Type;

We cannot write Var : access String, the type must be given a name.However an allocator must be used to give a value to such a variable, either in the declaration or in a statement:

Name_Ptr_1 : Name_Pointer_Type := new String (1..10);Letter_Ptr_1: Letter_Pointer_Type:= new Character;Name_Ptr_2 : Name_Pointer_Type := new String’(“Fred”);Letter_Ptr_2: Letter_Pointer_Type:= new Character’(‘F’);begin

...Name_Ptr := new String’(“Harry”);Letter_Pointer := new Character’(‘H’);...

end ;When variables have values, they must be constrained, hence the problems with strings. Note that new ... ( ) defines an index range, new ...’( ) defines an initial value (which itself may define an index range! <<< Get used to this notation.)

Page 18: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 18

Next,Var1, Var2 : Letter_Pointer_Type:= new Character’(‘F’);

is equivalent toVar1 : Letter_Pointer_Type:= new Character’(‘F’);Var2 : Letter_Pointer_Type:= new Character’(‘F’);

and so allocates two separate storage values.The content of memory that is pointed to by an access variable Var is denoted Var.ALL, compare the dereferencing operations ‘^’ in Pascal and ‘->‘ in C++.

Var1 := Var2 and Var1.all := Var2.all are both legal but have a different effect.Ada is very type conscious:

type Ltr_Ptr_Type_1 is access Character range ‘A’..’z’;type Ltr_Ptr_Type_2 is access Character range ‘A’..’z’;Ptr_1 : Ltr_Ptr_Type_1 := new Character’(‘a’);Ptr_2 : Ltr_Ptr_Type_2; begin

Ptr_2 := Ptr_1; -- TYPE CONFLICT!end ;

When access variables point to records we need a notation to refer to the fields.

type Buffer_Type isrecord Length : Integer range 0..128;

Content : String(1..128);end record ;

type Buffer_Ptr_Type is access Buffer_Type;Buff_ptr : Buffer_Ptr_Type

:= new Buffer_Type’(Length=>4,Content(1..4)=>“abcd”);

Page 19: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 19

Buff_ptr.all.Length = 4. This can be abbreviated to Buff_ptr.Length. Note that the Ada compiler insert the dereference ‘.all’ automatically:

Buff_ptr : Buffer_Ptr_Type := new Buffer_Type’(Length=>4,Content(1..4)=>“abcd”);

Buff : Buffer_Type := (Length=>4,Content(1..4)=>“abcd”);Buff.Length = Buff_ptr.Length is legal Ada and true in this case. The right hand side is an abbreviation for Buff_ptr.ALL.Length.Note the slice Array_Var (range), e.g. Content(1..4).Example:

S_1, S_2 : String (1..10);S_1 (2..6) := S_2 (6..10); -- is legalS_3 : String (1..5);S_4 : String (7..11);S_3 := S_4; -- is legal and means S_3 (1..5) := S_4 (7..11).

Logically speaking S_3 (1..5) := S_4 (7..11) is equivalent to for Idx in (1..5) loop S_3(Idx) := S_4 (Idx + 6); end loop ;

Just make sure the number of values in the ranges are the same.Applications of access types are those of Pascal pointer types. We shall see rather later in the course that certain insecurities in Pascal pointers have been removed.Arrays of pointers to strings allow arrays of varying length strings to be constructed:

type Page_Type is array (1..55) of String; -- is ILLEGALA legal construct is:

type Line_Ptr_Type is access String;type Page_Type is array(1..55) of Line_Ptr_Type;

Page 20: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 20

Ada solves the declaration order problem of recursive data structures differently from Pascal:

Legal Pascal Ada equivalenttype type Node_Type; Link_Ptr_Type = ^Node_Type; -- an incomplete

declarationNode_Type type Link_Ptr_Type is

= record access Node_Type;Data : Data_Type; type Node_Type isNext : Link_Ptr_Type record

end ; Data : Data_Type;Next : Link_Ptr_Type;

end record ;You cannot “forward reference” type names.Subtypes And Type EquivalenceType conversions in Ada are mostly illegal:

I : Integer; F : Float;make F := 2; F := I; and I := F; are all illegalF := Float(I); and I := Integer(F) are legal, the latter rounds to the nearest integer.Even different type names create type incompatibility:

type T1 is range 1..10;type T2 is range 1..10;X : T1; Y : T2;X := Y; is illegal, X := T1(Y) is an “explicit type conversion” and is OK.

Subtypes are assignment compatible and so can be helpful:

Page 21: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 21

type T1 is range 1..10;subtype ST1 is T1 range 2..5;subtype ST2 is T1 range 3..8;X : T1; Y : ST1; Z : ST2;X := Y is OK, Y := X is OK but at run-time the value of X will be checked to see if it lies in 2..5, if not, an exception (CONSTRAINT_ERROR) is raised. Y := Z is also OK if the constraint check does not raise an exception.

Subtypes can constrain arrays:type T1 is array (Integer range <>) of Character;subtype ST1 is T1(10..30);

Scan the examples in Chapter 6. Predefined subtypes:subtype Natural is Integer range 0..Integer’MAXsubtype Positive is Integer range 1..Integer’MAX

andtype String is array (Positive range <>) of Character;

Variables declared to be of a certain subtype ST of the type T are assignment compatible with variables declared to be of the type T.StatementsAssignment X := expr; type checking is done by compilerProcedure calls Name (Param_1, ..., Param_n);I/O depends on the operations defined in Text_IOif... then ... else ... end if and case ... end case statements were described earlier.A procedure stub of the following form is illegal:

Page 22: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 22

procedure P isbeginend ;

A null statement is needed:procedure P isbegin

null ;end ;

Loops were discussed earlier, however loops can be named (see next page)

Outer_Loop: for X in 1..20 loop...Middle_Loop : loop

...Inner_Loop: while Y = Z loop

...exit Outer_Loop when ...;exit Middle_Loop when ...;...

end loop ;...exit when ...;...

end loop ;...

end loop ;We shall not use goto, but note that the use of goto is very strict: you can only jump to a label somewhere in the group of statements which contains the goto itself,

Page 23: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 23

e.g. you cannot goto a statement inside a loop if the goto is not in that loop, you cannot goto the else part of an if statement if the goto is in the then part.delay 0.5; will make the program suspend for about 1/2 a second.To declare a new variable for a part of a program, we can use blocks (the name is optional):

Name: declare .... -- declare new variables herebegin

...end ; -- the variables disappear here

ExpressionsMost basic features of expressions are familiar from Pascal. Recall that ( ) is used for arrays instead of [ ]. Note also that the dereference ‘.all’ of access types can be omitted if particular fields are accessed. Ada adds the use of attributes:For a type or subtype T which is a discrete type, we can use T’FIRST and T’LAST to denote the first (or least) element in T and the last (or greatest) element in T. What Pascal called MAXINT is now Integer’LAST.We also have T’VAL and T’POS:

Character’POS(‘A’) = 64 (Pascal uses Ord(‘A’))Character’VAL(64) = ‘A’ (Pascal uses Chr(‘A’))

Another attribute familiar from Pascal:Character’SUCC (‘A’) = ‘B’Character’PRED (‘B’) = ‘A’

We can review ‘VALUE and ‘IMAGE if we need them. You can look up the attribute list in an Ada manual.

Page 24: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 24

We have already seen a little of the notation of aggregates. At this time the textbook gives several examples. Positional aggregates for linear arrays, named aggregates, positional aggregates for multi-dimensional arrays, the use of others, etc. Similar use of aggregates apply to records, although the use of others. Others can only apply to fields of the same base type (they could be different subtypes of the same type).We have seen qualified expressions and type conversions earlier.Compound expressions

Highest Precedence**, abs, not

*, /, mod, rem+, - (unary positive/negative)

+, - (binary plus/minus), & (binary string operation)=, /=, <, <=, >, >=, in, not in

and, or, xor, and then, or elseLowest precedence

Note that in X**Y, the type of Y must be Integer. The type of X is normally a floating point type (e.g. Float) and the value of X**Y will be the same floating point type unless there is a constraint error. IF Y > 0 then X could also an integer type and then X**Y would be of that integer type unless there is a constraint error. The value of 2**(-2) is an error, the value of 2.0**(-2) is 0.25. You cannot write X**(0.5). In that case you would need to write EXP(0.5 * LOG(X)).Note abs X, abs (X**Y), (abs X)**Y are OK, abs X**Y is illegal.Note X/Y is integer division if X and Y are integers (when there are negatives involved truncate toward zero: 4/(-3) = (-4)/3 = -(4/3) = -1).

Page 25: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 25

If X and Y are both the same floating point or fixed point types, the value of X/Y is that same type and is the usual quotient.For integer types

X rem Y = X - (X/Y)*Y = (SGN X)(|X| - (|X|/|Y|)*|Y|)SGN(X mod Y) = (SGN Y), |X mod Y| < |Y| and X = Y*N + X mod Y for some N.

Catenation:“Party on “ & “dudes” & “!”Text_IO.Put (“This is how to get very long “ &

“messages on to the screen “ &“when they do not fit in the “ &“program because of indentation”);

‘&’ also works for other 1-dimensional arrays: if Arr : array (1..2) of Integer; thenArr := (1 => 0) & (1 => 1); should make Arr be (0,1).“Party on “ & (1 => ‘.’)

Relational operators. Usual things from Pascal (including enumerated types: false < true) plus comparison of 1-dimensional arrays: “Box” < “boX” < “bookcase” < “box”in, not in apply to rangesand then and or else are useful additions to force predictable short-circuit evaluation.not, and, or, xor can be applied to arrays of booleans:

type T is array (1..n) of Boolean;X, Y : T

X xor Y is an array satisfying (X xor Y) (J) = X(J) xor Y(J)

Page 26: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 26

Miscellaneous Details:In FUN1(X) * FUN2(Y) - FUN3(Z)/FUN4(W), Ada does not define the order of function calls. All sorts of values can arise if any function modifies any of the variables by accessing them as global variables.Integer literals: 2#1010101#, 16#f2ba4# = 16#F2BA4#, 8#1733#, 10#673# = 673.Literals with radix point:

2#10.001# = 1*21 + 0*20 + 0*2-1 + 0*2-2 + 1*2-3

16#C1A.0B1# = 12*161 + 1*161 + 10*160 + 0*16-1 + 11*16-2 + 1*16-3

With exponents (which are written in base 10 but signify the power of the base number indicated):

2#10.001#E-4 = 2#0.0010001# = 2#10.001# * 2-4

-16#5.1234#E10 = -16#51234000000# = -16#5.1234# * 1610

Integer’VALUE(“235”) = 235Integer’VALUE(“-16#” & “ABC” & “#”) = -2748Integer’VALUE(“2#101_010_1#”) = 85

Ada introduces “universal integers” and “universal reals” which can be automatically converted to specific integer or real types:

type T is range 5..10;X : T;X := X+2; is legal if X < 8, 2 is converted to type T.

More on attributes ... Some_Subtype’FIRST may have a predecessor!Some attributes can be read from the “BASE TYPE” of a subtype: e.g. Some_Subtype’BASE’FIRST, however take care that the implementation of numeric types often create bigger base types than the named base type would indicate.

Page 27: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 27

SubprogramsWe have already seen that a subprogram (procedure or function) may have a separate declaration and body, or just a single body.Parameters can be of 3 types:

procedure P (X1, Y1 : T1; X2 : in T2;X3, Y3, Z3 : out T3; X4 : in out T4);

in is the default mode for parameters (X1 and Y1 are of mode in).Normally, in out parameters which are scalar types are copied in to the subprogram at the beginning and copied out at the end. If the parameters are structured, call by reference may be used by some implementations. We shall see how this can give different results when there is aliasing or exceptions.Parameters which are of mode IN can be given default values:

function F (X, Y : Integer := 0) return T;Function parameters can only be of mode in. Functions can return types with any structure (e.g. strings or arrays).Parameters may be unconstrained.We shall see that parameter passing can be positional or using named notation. A function must contain at least one return statement which gives the value returned by the function. A procedure may use return which acts as an exit, however it is not required.Recursion is allowed.Nested subprograms are allowed (like Pascal, unlike C)

Page 28: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 28

Subprogram names may be overloaded —the same name used for different procedures. However the compiler must be able to tell which subprogram is being called:

procedure Modify (A : in Some_Array_Type; B : out Some_Array_Type) is

begin... -- change entries in A to produce B

end ;procedure Modify (A : in Some_Array_Type;

B : out Integer) isbegin

... -- use the entries in A to compute B end ;procedure Modify (A, B : in Some_Array_Type;

C : out Some_Array_Type) isbegin

... -- combine entries in A and B to produce C end ;function Modify (A : Some_Array_Type)

return Some_Array_Type isbegin

... return some array derived from A end ;

These subprograms would be called in different ways and with different numbers and types of parameters and so the compiler can distinguish them.You can even overload operatorswith Text_IO;package Int_IO is new Text_IO.Integer_IO(Integer);

Page 29: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 29

package Matrices istype Num_Array is

array(Integer range <>, Integer range <>) of Integer;function “+” (A, B : Num_Array) return Num_Array;function “-” (A, B : Num_Array) return Num_Array;procedure Print (Name : String; A : in Num_Array);

end Matrices;with Text_IO, Int_IO;package body Matrices is

function “+” (A, B : Num_Array) return Num_Array isL1 : Integer := A’FIRST(1);L2 : Integer := A’FIRST(2);U1 : Integer := A’LAST(1);U2 : Integer := A’LAST(2);C : Num_Array(L1..U1, L2..U2);

beginif L1 /= B’FIRST(1) or L2 /= B’FIRST(2) or

U1 /= B’LAST(1) or U2 /= B’LAST(2)then raise CONSTRAINT_ERROR;end if;for I in L1..U1 loop

for J in L2..U2 loopC(I,J) := A(I,J) + B(I,J);

end loop ;end loop ;return C;

exception when CONSTRAINT_ERROR =>C := (OTHERS => (OTHERS => 0));

return C;end “+”;

Page 30: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 30

function “-” (A, B : Num_Array) return Num_Array isL1 : Integer := A’FIRST(1);L2 : Integer := A’FIRST(2);U1 : Integer := A’LAST(1);U2 : Integer := A’LAST(2);C : Num_Array(L1..U1, L2..U2);

beginif L1 /= B’FIRST(1) or L2 /= B’FIRST(2) or

U1 /= B’LAST(1) or U2 /= B’LAST(2)then raise CONSTRAINT_ERROR;end if;for I in L1..U1 loop

for J in L2..U2 loopC(I,J) := A(I,J) - B(I,J);

end loop ;end loop ;return C;

exception when CONSTRAINT_ERROR =>C := (OTHERS => (OTHERS => 0));

return C;end “-”;procedure Print (Name : String; A : IN Num_Array) isbegin

Text_IO.Put_line(“The array “ & Name & “:”);for J in A’FIRST(1)..A’LAST(1) loop

for K in A’FIRST(2)..A’LAST(2) loopInt_IO.Put(A(J, K), 3);

end loop ;Text_IO.new_line;

end loop ;Text_IO.new_line;

end Print;end Matrices;

Page 31: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 31

with Matrices;package Swappack is

procedure Swap (X, Y : in out Integer);procedure Swap (X, Y : in out Matrices.Num_Array);

end Swappack;with Matrices; use Matrices;package body Swappack is

procedure Swap (X, Y : in out Integer) isbegin

X := X + Y;Y := X - Y;X := X - Y;

end ;procedure Swap (X, Y : in out Num_Array) isbegin

X := X + Y; -- The “use Matrices” is essential to be able toY := X - Y; -- use these operators infixX := X - Y;

end ;end Swappack;with Matrices, Swappack, Text_IO, Int_IO;procedure Mdriver is

X : Integer := 7; Y : Integer := 8;Ch : Character;A : Matrices.Num_Array(1..2, 1..2) := ((1, 2), (3, 4));B : Matrices.Num_Array(1..2, 1..2) := ((4, 5), (6, 7));

beginText_IO.Put_line(“Before Swap”);Text_IO.Put(“X: “); Int_IO.Put(X);Text_IO.Put(“ Y: “); Int_IO.Put(Y);Text_IO.New_Line;

Page 32: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 32

Swappack.Swap (X,Y);Text_IO.Put_line(“After Swap”);Text_IO.Put(“X: “); Int_IO.Put(X);Text_IO.Put(“ Y: “); Int_IO.Put(Y);Text_IO.New_Line;Text_IO.Put_line(“Before Swap”);Matrices.Print(“A”, A);Matrices.Print(“B”, B);Swappack.Swap (A,B);Text_IO.Put_line(“After Swap”);Matrices.Print(“A”, A);Matrices.Print(“B”, B);Text_IO.New_Line;Text_IO.Put_line(“Press a key to continue, followed by <ret>“);Text_IO.get(Ch);Text_IO.Put_line(“Before Swap with alias”);Text_IO.Put(“X: “); Int_IO.Put(X);Text_IO.New_Line;Swappack.Swap (X,X);Text_IO.Put_line(“After Swap with alias”);Text_IO.Put(“X: “); Int_IO.Put(X);Text_IO.New_Line;Text_IO.Put_line(“Before Swap with alias”);Matrices.Print(“A”, A);Swappack.Swap (A,A);Text_IO.Put_line(“After Swap with alias”);Matrices.Print(“A”, A);

END Mdriver;

Page 33: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 33

Output:Before SwapX: 7 Y: 8After SwapX: 8 Y: 7Before SwapThe array A: 1 2 3 4The array B: 4 5 6 7After SwapThe array A: 4 5 6 7The array B: 1 2 3 4-----------------------Before Swap with aliasX: 8After Swap with aliasX: 8Before Swap with aliasThe array A: 4 5 6 7After Swap with aliasThe array A: 0 0 0 0

Page 34: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 34

The last value of the matirx A occurs when Ada passes array parameters by reference. Some implementations use copy in/ copy out which would return the original value of A.DiscriminantsSpecial things about discriminants and discriminated records: using the discriminant and changing the discriminant value.type R (N : ...) is

recordField_1 : ....;case N is --legal use of N after CASE

when ... => Field_2 : ...;when ... => Field_3 : ...;-- Ada will verify that all values of N are accounted for

end case ;end record ;

type R (N : ...) isrecord

Field_1 : Some_Unconstrained_Array_Type (1..N);-- legal use of N as an index constraint

end record ;type R (N : ...) is

recordField_1 : Some_Other_Discriminant_Record_Type (N);-- legal use of N in a discriminant constraint

end record ; type R (N : ...) is

recordField_1 : Some_Unconstrained_Array_Type (1..N + 1);-- ILLEGAL use of N, uses not just the name

end record ; type R (N : Integer) is

Page 35: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 35

recordField_1 : Integer := N + 7;-- legal use of N as a default expression

end record ;type R (N : ...) is

recordField_1 : Integer range 1..N;-- ILLEGAL use of N as a range constraint

end record;Discriminants with default values:type R1 (N : Integer := 7) is

recordField_1 : Some_Unconstrained_Array_Type (1..N);

end record ;type R2 (N : Color := Blue) is

recordcase N is

when Red | Green => Field_2 : ...;when Blue | Black => Field_3 : ...;when others => ...

end case ;end record ;

Legal variable declarations (X and Y are legal because of default value):

X : R1; X1 : R1(6); Y : R2; Y1 : R2(N => Yellow);X := (N => 3, Field_1 => (‘a’, ‘b’, ‘c’)) -- the whole record may be changed, including the discriminant.

X := (2,(‘x’, ‘y’)) -- is also OKX1 := (N => 3, Field_1 => (‘a’, ‘b’, ‘c’)) -- ILLEGAL, X1 is constrained to N = 6.

Page 36: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 36

Records without defaults force their variables to be constrained and therefore unchangeable:type R1 (N : Integer) is

recordField_1 : Some_Unconstrained_Array_Type (1..N);

end record ;X : R1; -- illegalX1 : R1(6); -- legal but discriminant is now fixed

PackagesWe have seen packages as the means to modularization.What we have seen are library packages. They are compiled separately and can be “with-ed” into other packages, procedures or functions:

with Text_IO;package / procedure X is ...

But packages can be nested in other compilation units (less frequent):

package P1 is...package In_P1 is

...procedure P(...);...

end In_P1;...

end P1;

package body P1 is...package body In_P1 is

Page 37: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 37

...procedure P(...) isbegin

...end P;...

end In_P1;...

end P1;package P2 is

...end P2;

package body P2 is...package In_P2 is

...procedure P(...);...

end In_P2;...package body In_P2 is

...procedure P(...) isbegin

...end P;...

end In_P2;...

end P2;The packages can be declared inside procedures also:

Page 38: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 38

procedure Pr1 (...);procedure Pr1 (...) is

...package In_Pr1 is

... -- procedures or nested packagesend In_Pr1;...package body In_Pr1 is

... -- procedures and bodies of above procedures

... -- nested packages and bodies of above packagesend In_Pr1;...

end Pr1;Nesting of packages within other packages or procedures is allowed to any depth.>> An important detail about declarations. Procedure bodies and package bodies (and later on task bodies) are called later declarative items. They all go at the end of the declarative part.You cannot declare types, variables, constants, (basic declarations) after you have started declaring the bodies of procedures, etc., (later declarations)Nor can you give only the declaration of another procedure, only the specification of a package (or task)¾basic declarations¾in the later declarative part.Packages within package specifications are accessible from the outside, packages within procedures and package bodies are not:

Page 39: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 39

with P1;package X is ... P1.In_P1.P(...) ...

Note: there is a similar prefix for to make hidden variables visible in various contexts, e.g.,

procedure Pr ( ... ) isX : Integer; -- this X is Pr.Xprocedure In_Pr ( ... ) is

X : Integer; -- this X is Pr.In_Pr.X or just In_Pr.Xbegin

Pr.X := X;end ;

begin...

end ;

Page 40: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 40

FLOATING-POINT TYPESTYPE Capacity_typ IS DIGITS 10 RANGE 0.0..10_000.0;

precision range“Range...” can be omitted.The precision specifies the accuracy of the elements of the type as approximations of real numbers. For 10 digits, if the first 10 digits in the representations of two real numbers differ in at least one position, then the corresponding elements of this type would be different. e.g.,

1324.62317892345325 and1324.62317992345325

would be approximated by different elements of type “Capacity_typ” while

0.00001234567891234 and0.00001234567891134

could be represented by the same element of “Capacity_typ.”Fixed-Point TypesTYPE Batting_avg_typ IS DELTA 0.001 RANGE 0.0..1.0;

precision rangeBoth range and precision are required.The precision gives the maximum distance between two successive values of this type. Successive values can be closer together, e.g., “Batting_avg_typ” may be represented internally by multiples of 2-10.Subtypes of either of the above types can only define smaller ranges or less accuracy in terms of digits or delta.

Page 41: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 41

All real number representations are approximations. To discuss the inaccuracies more carefully, we need to look at MODEL NUMBERS.Model Numbers For Fixed-Point SubtypesConsiderTYPE fix IS DELTA d RANGE low..hi;Find k so that 2k £ d < 2k+1 and let s = 2k

for example if d = 5, k = 2 and s = 4, if d = 0.1, k = -4 and s = 0.0625 (= 1/16), if d = 0.001, k = -10 and s = 0.0009765625 (= 1/1024).Next find the smallest n so that -n * s £ low and n * s ³ hi. Then the model numbers for the type “fix” are

-(n - 1) * s, -(n - 2) * s ... -s, 0, s, ... (n - 2) * s, (n - 1) * sand these are represented exactly in memory. The actual type “fix” may have more numbers which are larger or smaller than those shown. The range must be symmetric about 0 (if x is a same number so is -x).

Page 42: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 42

Model Numbers For Floating-Point SubtypesTYPE flt IS DIGITS NLet B be the 1+ # (binary digits needed to hold as much information as N decimal digits). B = 1 + é N *(log(10)/ log(2))ù, which is slightly more than 1 + 3.32N :N 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ....B 5, 8, 11, 15, 18, 21, 25, 28, 31, 35, 38, ...The model numbers are 0 and all values that can be written in the form

sign * mantissa * 2exponent

where sign is -1 or +1, exponent is in the range -4*B .. 4 * B and mantissa is a binary fraction consisting of a decimal point followed by B binary digits, the first of which MUST BE 1.The representation can allow safe numbers with a larger range of exponents.The range constraint does not affect the computation of the model numbers of a floating point type.Model numbers are guaranteed to be represented exactly. Other real numbers may be represented exactly or approximated by some value in the type. Safe numbers for a particular type are those that have an exact representation in this particular implementation. Hence, for a given type the safe numbers are implementation dependent. The IEEE standard floating point number representations use 32, 64 and 96 bits. If a real number representation would fit into the 32-bit standard, with an 8-bit biased exponent and a 23-bit mantissa, then the safe numbers would likely be those provided by the 32-bit standard, even though the accuracy might be greater than the one requested.Real number representation

Page 43: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 43

The are a number of representations, e.g.

where SGN, MS is the sign of the number, i.e., the sign of the mantissa, ES is the sign of the exponent, EXP VAL is the exponent and MANTISSA VAL is the mantissa of the number.Format A is used in IBM 370, iAPX432, Univac 1108, CRAY-1, DG Eclipse, PDP11, MC68020, IEEE Standard, format B; was used in the B5500 and C was used in the CYBER 205.A form of scientific notation is used. Numbers are converted to binary mantissa/exponent format: 0×1... r exp, where r may be 2 or 16 depending on the designers of the computer. For example,

BASE 10 BASE 21 0×1 21, 5 0×101 23

0×5 = ½ =1 2-1 0×1 20

The part 0×1... before the ‘‘ is called the mantissa.Note that when we write 2.67E5 the compiler interprets that as 2.67 105, i.e., it assumes base 10 notation. This number is 0×1000001001011111000 219 in our binary notation. Some languages allow the programmer to use other bases, e.g., Ada: 8#327# is 327 in octal, 8#12.65#E11 is 12.65 octal 811 (where the exponent 11 is in decimal !!!), 16#1A.65#E11 is 1A.65 hexa-decimal 1611 (where the exponent 11 is in decimal).So far, we have only part of the story. Different implementations choose different ways to represent the binary 0×1... r exp. We shall only discuss the IEEE 32-bit standard (IEEE has similar 64 and 96 bit standards).

EXP VALSGN MANTISSA VAL

EXP VALMS MANTISSA VAL

EXP VAL SGN MANTISSA VAL

A:

B:

C:

ES

Page 44: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 44

Note that all of the binary numbers will start 0×1. In normal decimals we can have 0×1, 0×2, 0×3, etc., but binary numbers can only start 0×1. We use the exponent 2exp to make sure the number does not begin 0×0...Now, if every number starts 0×1..., we do not need to store the 0×1. Hence mantissas as stored as the 23 bits after the 0×1:

MANTISSA 23 BITS STORED0×1 000000000000000000000000×11001 100100000000000000000000×1000000011 00000001100000000000000

The sign on the number is stored in the sign bit, 0 = positive, 1 = negative.Finally, the exponent is biased. You could choose to store the sign of the exponent as in format B or you can, as IEEE does, add a fixed number to the exponent to make sure the number stored is positive. Hence, when the exponent is stored. the IEEE 32-bit standard first adds 127 to the exponent before storing it in an 8-bit field. 2-126 gets the exponent field 1 = 00000001, 2-1 gets the exponent field 126 = 01111110, 210 gets the exponent field 137 = 10001001, 2127 gets the exponent field 254 = 11111110.The exponent fields 0 = 00000000 and 255 = 11111111 have a special use and are not available to normal floating point numbers. Hence the largest number that can be stored in IEEE 32-bit format is

0×111111111111111111111111 2127 =111111111111111111111111 2103 = (1000000000000000000000000 - 1) 2103 = 2128 - 2103 = 3.402823567797 E 38 (approx). This number is stored as

01111111011111111111111111111111

exp val mantissa valsgn

Page 45: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 45

The smallest number, greater than 0, representable in IEEE 32-bit format is 0×100000000000000000000000 2-126 = 2-127 = 5.877471754111 E -39 (approx). This number is stored as

00000000100000000000000000000000

exp val mantissa valsgn

Infinity and zeroThree values are reserved in the IEEE 32-bit format. The exponent field cannot be used to represent 2-127 or 2128 so that the field can be used to designate the zero and infinite values. There is also an “illegal” value that can be recognized:+Infinity:-Infinity:

111111111000000000000000000000000

exp val mantissa valsgn

Zero:000000000000000000000000000000000

exp val mantissa valsgn

Not a (floating-point) number:011111111.......some non-zero value.......

exp val mantissa valsgn

An illegal value may be inserted by the implementation for a FLOAT variable X as a result of the assignment X = A + B when A = +infinity and B = -infinity, which does not have a defined value. At least, it is possible to assign a value in the case of division by zero X = 1.0/0.0 should insert the +infinity value for X. The ZERODIVIDE error can then be ignored at run time.The following table may be helpful to fully understanding the representation:

011111111000000000000000000000000

exp val mantissa valsgn

Page 46: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 46

BASE 10 SIGN EXP-VAL MANTISSA-VAL0 0 00000000 000000000000000000000001 0 10000000 00000000000000000000000-1 1 10000000 000000000000000000000002 0 10000001 000000000000000000000003 0 10000001 100000000000000000000004 0 10000010 000000000000000000000005 0 10000010 01000000000000000000000

-11 0 10000100 011000000000000000000002001 0 10001010 11110100010000000000000

1000000 0 10010011 11101000010010000000000½ 0 01111111 00000000000000000000000-¼ 1 01111110 000000000000000000000001/3 1 01111110 01010101010101010101010

Page 47: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 47

EXCEPTION HANDLINGExamples of exceptions:Divide-by-zero causes an error. Rather than aborting we might assign a very large number (IEEE standard floating point has a representation for infinity)Reading a mistyped data entry in a teller transaction during an overnight update of bank accounts should not cause a program to crash. The offending transaction should be flagged and processing of all remaining transactions should proceed.In fight-control software, if some sort of program abnormality is discovered, the code should not abort with a “core dump.” Some back up software should get the program to a point where normal processing can continue.PL/I and Ada and (now) C++ are the best known languages that have exception handling. They have different mechanisms. CLU, ML and also have exception handling built-in.It is useful in Ada. The following is a very clear piece of code, provided you understand that reading past the end of an array raises the exception CONSTRAINT_ERROR:

A : array (1..10) of Integer;...begin

J := 1;while A(J) /= 0 loop J := J + 1; end loop;put (“zero found at position “);put(J);new_line;exception

when CONSTRAINT_ERROR =>put_line(“zero not found”);

end;

Page 48: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 48

although this could have been written in the following form:A : array (1..10) of integer;Found : Boolean := false;...begin

J := 0;while J < 10 and not Found loop

J := J + 1;if A(J) /= 0 then

Found := true;end if;

end loop;if Found then

put (“zero found at position”);put(J);new_line;

elseput_line(“zero not found”);

end if;end;

This version of the code is somewhat harder to read. Thus, exception handling can be included in the programming logic. It is not clear whether using exception handling (as an invisible “goto”) as part of normal program control is going to become popular and, if so, whether it will have a bad effect on maintainability.The following code opens a file if it already exists and creates it if it does not exist

Page 49: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 49

beginopen(filevar, filename)exception

when name_error =>create(filevar, filename);

end ;When an exception occurs during the execution of a particular instruction, that instruction is abandoned and all subsequent instructions are skipped until the next following end. If the end is preceded by exception, and a handler appears for the exception that was raised, then that handler is executed.

begin......instruction that raises exception E;... -- these following instructions are skipped... -- if the exception is raised

exception -- the exception section is optionalwhen E1 | E2 => ....when E3 => ...when E => ...when E4 => ...when others => ... -- the when others is optional

end ;PropagationIf an exception is not named between “exception” and “end” then there is no handler for that exception in the current block. In such a case, the block is abandoned and instructions following the end ; are skipped until the next following end or exception:

Page 50: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 50

begin...begin

...

...instruction that raises exception E;... -- these following instructions are skipped... -- if the exception is raised

exception -- the exception section is optionalwhen E1 | E2 => ....when E3 => ...when E4 => ...

end ;... -- these following instructions are skipped if E is raised... -- and not handled in the nested block

exceptionwhen E => ... -- exception E is handled here

end;We next note that an exception handler may raise an exception. In that case the block is abandoned and the exception propagates.If a subprogram or entry is called and an exception is raised during the call and that exception is not handled within the code of the called subprogram or accepting task, then the exception is propagated. That is, the exception is raised in the calling program at the location of the call.Any exceptions not handled in the block go back to the caller (propagate back). If the exception is not handled there, the exception propagates back to the caller of that caller.

Page 51: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 51

procedure P1 (...) isbegin

...instruction that may raise exception E... -- if E is raised, then following instructions are skipped

end ;procedure P2 (...) isbegin

...P1 (...); -- assume E is raised but not handled in P1, this

-- raises exception E at the point of the call. If E is... -- raised, subsequent instructions are skipped

exceptionwhen E => ... -- exception can be handled here

end ;It is possible to propagate a user-defined exception to a location outside the scope of the exception, then it can only be handled by when others.

procedure Outer isprocedure Inner is

X : exception; -- declaration of a user-defined exceptionbegin

raise X; -- the user may raise an exception explicitlyend; -- exception X is not handled by procedure Inner

beginInner; -- exception X propagates back to here

exception -- the name X is not visible herewhen others => ...-- X can be handled using “others”

end;One strange effect of Ada’s tasking model is that exceptions can occur without stopping the program:

Page 52: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 52

package P1 is...task T1;

end P;package body P1 is

task body T1 isbegin

...some exception occurs andT1 terminates

end T;end P;with P;procedure Proc is... refer to some declarations in P1begin

... processingend;While P is doing its processing, task T1 will be executing and at some point may be abandoned because an exception is raised. The user will not notice.In our debugging of tasks we found it very helpful to writepackage body P1 is

task body T1 isbegin

...some exception occurs andT1 terminatesexception

when Ex => - - the name of an expected exceptionput_line(“exception Ex in P1.T1”);

Page 53: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 53

when others =>put_line(“unknown exception in P1.T1”);

end T;end P;The use of “others” is similar to CLU, that covers all exceptions raised in that block [that are not named by another exception handler].

Page 54: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 54

The Ada Tasking ModelPackagesWe begin with an overview of packages and compilation dependencies. The basic unit of reusable software in Ada is a library unit, usually a package. Packages may be separately compiled. Packages enclose other program entities, e.g. type and variable declarations, subprograms (procedures/functions), tasks.Packages are written in two parts, a package specification and a package body. Specifications indicate what is made available by the package, the details of the definition of a compound type can optionally made visible or hidden in the package specification.Bodies contain (and also hide) implementation details of the subprogramspackage Resources_1 is

type Type_1 is range -4 .. 25;type Type_2 is array (Boolean) of Type_1;type Type_3; -- incomplete type declarationtype Type_4 is access Type_3;type Type_3 is record

Field_1 : integer := 1;Field_2 : Type_2;Field_3 : Type_4; -- a link of a linked list

end record;...

type Type_N is ...type Enum_1 is (Value_1, Value_2);function Fun_1 (Param_1 : Type_1; Param_2 : Type_2)

return Type_3;task type Task_type_1 is

entry E1 (Param : Type_4; ...);entry E2 (Param : Type_3; ...);

Page 55: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 55

end Task_type_1;task type Task_type_2; --has no entriestask T3 is

entry E (Param : Type 3);end T3;

end Resources_1; -- end of package specificationpackage body Resources_1 is-- declarations local to package body they are not visible outside -- the package

function Fun_1 (Param_1 : Type_1;Param_2 : Type_2) return Type_3 is -- declarations local to Fun_1

begin-- executable code of function bodyreturn ... -- return is required for a function

end Fun_1;task body Task_type_1 is -- declarations local to Task_type_1 (optional)begin

... executable code of task bodyend Task_type_1;task body Task_type_2 is

... -- local declarations (optional)begin

... executable code of task bodyend Task_type_2;task body T3 is

... -- local declarations (optional)begin

... executable code of task bodyend T3;

end Resources_1;

Page 56: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 56

Recall that one compilation unit gains visibility to the resources provided by another package using a context clause (also called a with statement). Context clauses appear immediately before the compilation unit that needs access to the units named in that context clause:

with Resources_1, Resources_2, ...;package Resources_i is

...end Resources_i ;with Resources_3, Resources_4, ...;package body Resources_i is

...end Resources_i ;

Any packages named in the context clause of the package specification are automatically visible to the package body. The body may name additional packages in its own context clause. Only those resources in packages named in the context clauses are available to the compilation unit with those context clauses.The package specification is more generally called a library unit and the package body is called a secondary unit. Other instances of library units and secondary units are subprograms (procedures and functions )

procedure Proc_1 (Param_1, Param_2; in Type_1;Param_3 : in out Type_2; Param_4 : out Type_3);

function Fun_1 (Param_1 : Type_1) return Type_2;One subprogram will be identified as the main program when the program is bound (the “bind” operation on a program is the Ada version of “link” but it includes checks on all dependencies for correct time-stamps on specs and bodies to ensure out-of-date bodies are not used. Compare the “link” part of a C “make” file)

Page 57: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 57

Parameter modes:in - the assumed mode if no mode is specified, also known as pass-by-value, the actual value of the parameter can only be read inside the procedure.Variables or constants can be passed as in-parameters. In any case, they are treated as constants inside the subprogram and the compiler checks that no statement tries to assign to them. Only in-parameters are allowed in functionsin out - the actual parameter must be a variable that can be read from or written to.For structured parameters such as arrays, records and strings, the pass-by-reference mechanism is permitted. For scalar parameters (numbers, booleans, characters, other enumeration types) the copy-in, copy-out mechanism is mandatory. A difference in the two mechanisms is noticed if there are exceptions raised in the subprogramout - the actual parameter must be a variable, the subprogram can only assign its value, it cannot be read. The parameter passing mechanisms for in-out parameters apply but the compiler checks that the value is not read.Subprograms as library/secondary units:

with Resources_1, Resources_2;procedure Proc_1 (Param_1 : Resources_1.Enum_1; .. ) is

Var_1 : Resources_2.Type_1;begin ...Resources_1.Proc_1( ... ); ...end Proc_1;

Any Ada program must have a main subprogram which withs some of the library units:

Page 58: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 58

package R1 is ... end R1;with R1;package R2 is ... end R2;with R2;package R3 is ... end R3;with R2;package R4 is ... end R4;

you also need to provide bodies for packages R1, R2, R3, R4 if they contain subprograms or tasks, need initialization code, etc.

with R3, R4;procedure Main is -- local declarations

begin... -- Main program body

end Main;This program generates a graph of dependencies shown in Figure 4. The code and graph say nothing of the dependencies involving the package bodies, e.g. package body R1 might with R2, package body R2 might with R4, package body R3 might with R2 and R4. Note: you “with” package specs. See Figure 5.

Spec of R1

Spec of R2

Spec of R3 Spec of R4

Main

Figure 4

Page 59: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 59

The dependency graphs express compilation dependencies the order in which units must be compiled. Those “withs” may imply dependencies between package bodies but that is a complicated issue. We do not discuss the matter here (see published papers on elaboration by Lander and Mitra, e.g. Software-Practice and Experience, May 1992).The Ada package is the program construct which supports abstract data types and is used to implement the objects of an object-oriented design . The following is a sample program:

package Sensor istype Voltage_type is new float

range 0.0 .. 10.0; -- a derived typeprocedure Line (Measurement : out voltage_type);

-- returns voltageend Sensor;with Sensor;package Recorder isprocedure Post (Data_value : Sensor.Voltage_type);

-- displays the voltage valueend Recorder;

Spec of R1

Spec of R2

Spec of R3 Spec of R4

Main

Body of R1

Body of R2

Body of R3

Body of R4

Figure 5

Page 60: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 60

with Recorder, Sensor;procedure Record_line_conditions is

Voltage : Sensor.Voltage_type;begin

loopSensor.Line (Measurement => Voltage);Recorder.Post(Voltage);

end loop;end Record_line_conditions;

Tasking facilities in AdaTasks are entities for concurrent programming built-into Ada. Tasks operate in parallel with other program units (unlike subprograms, which execute in a sequence determined by the way they are called in the program). We need to be able to map real-world parallel activities to tasks. Each task can be implemented as an independent thread of control.Normally the execution of one task’s body is not expected to impact any other task’s execution, as in the example below.This is unlike the case of subprograms, where the execution of a particular subprogram depends on whether or not it is called by another subprogram.Example:task Oil_monitor;task Water_monitor;

-- both in some package or subprogramtask body Oil_monitor is

Pressure : float;begin

loopRaed (Pressure); -- read from a sensorif Pressure > Max_pressure

Page 61: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 61

then Activate_alarm;end if;

end loop;end Oil_monitor;task body Water_monitor is

Temperature : float;begin

loop Read (Temperature); -- read from a sensorif Temperature > Max_temperature then Activate_alarm;end if;

end loop;end Water_monitor;Problem requirements may however dictate that tasks need to communicate with each other. One task’s execution may need to synchronize with another Tasks may need to exchange data. Ada provides one basic mechanism to effect such communication, it is called the rendezvousHow does a rendezvous take place? In one task the rendezvous has an associated entry. A task specification introduces the task itself, together with any entries visible to users of the tasktask Stack is

entry Pop (Element : out integer);entry Push (Element : in integer);

end Stack;

Page 62: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 62

An entry has, associated with it, parameters to facilitate data exchange (in the same manner as for procedures ). A task body defines the action associated with the task. For each task entry, there must be at least one corresponding (accept ) statement in the task body:

task body Stack isbegin

loop...accept Push (Element : in integer) do

Append (Stack_data, Element);end Push;...accept Pop (Element : out integer) do

Element := Retrieve_head (Stack_data);end Pop;...

end loop;end Stack;

Each accept statement is a potential point for rendezvous. The fact that a task has visible entries means that other task bodies may call these entries.

task body Stack_user isRetrieved_value : integer;

beginloop

...Stack.Push (3); -- entry call...Stack.Pop (Retrieved_value); -- entry call...

end loop;

Page 63: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 63

end Stack_user;Each entry call is also a potential point for a rendezvous. Assuming Stack_user and Stack are executing on separate processors, the scenario in Figure 6 takes place. Suppose there were two tasks that used the Stack, see Figure 7. When “Stack” finally gets to accept Push(...), which entry call does it accept?Associated with each entry declared in a task, there is an entry queue. If a calling task is blocked at an entry call, that task is placed in the appropriate entry queue of the called task. At any particular time, several calling tasks may have been placed in the same queue (e.g. the queue for entry “Push”). The calling tasks are placed in the queue in the order they make their calls.When the called task reaches the accept statement, assuming the corresponding entry queue is not empty (calls to the entry have been made), the called task makes an immediate rendezvous with the calling task at the head of the entry queue (entry queues are managed according to the FIFO rule).

call Stack.Push(3)

rendezvous ends

call Stack.Pop(...)

rendezvous begins

caller blocked

rendezvous ends

rendezvous begins

Stack_user Stack

accept Push (...)....task Stack blocked (notask has called theentry Push)

caller suspended accept Push block exe-cutes during rendezvous

Stack_user continuesStack continues

caller suspended

Stack continues

accept Pop block exe-cutes during rendezvous

Stack_user continues

Figure 6

Page 64: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 64

Other tasks in the entry queue will be handled, in order, when the called task next reaches the accept statement for that entry (if it ever does). Statements inside a task body execute in sequence, including accept statements. Therefore, the task “Stack” first blocks on the accept Push(...) statement and will unblock only when some calling task calls entry “Push”

Stack_Push(3)

Stack_user_1 Stack_user_2 Stack

Stack_Push(4)

accept Push(...)

Figure 7

Page 65: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 65

The accept Pop(...) statement must next be handled similarly. The only possible order of stack operations in this implementation is Push, Pop, Push, Pop, ...which may not be exactly the intended effect, a stack of size 1 would be sufficient! We would prefer to be able to make any sequence of Push/Pop operations, e.g., Push, Push, Push, Pop, Push, Pop, Pop, ...How can this be achieved? Ada provides the “selective wait” statement:

selectaccept ...

{or accept ... } -- as many alternatives as you wishend select;

e.g.task body Stack isbegin

loopselect

accept Push (Element : in integer) doAppend (Stack_data, Element);

end Push;oraccept Pop (Element : out integer) do

Element := Retrieve_head (Stack_data);end Pop;

end select;end loop;

end;

When task “Stack” reaches the select statement, the construct itself is such that any one of the two accept alternatives may be accepted. This suffices to achieve arbitrary interleaving.

Page 66: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 66

What happens if there are two (or more) calling tasks when the selective wait is reached, at least one task calling Push and at least one task calling Pop?Ada semantics do not define what must happen in such a case. In general, a selective wait may have several alternative accepts. When several tasks call a number of the entries accepted by the selective wait, the Ada language leaves undefined the choice of which one of the accepts executes its rendezvous.Many compilers choose a round-robin approach to choosing the accept (see the Lander/Mitra/Piatkowski discussion of such an algorithm in the September 1990 Ada Letters). A task will block at a selective wait if none of the accept alternatives have any calling tasks in their entry queues. If this blocking is undesirable in a particular application, the Ada language provides a “selective wait with else part”e.g. select

accept E1( ... ) do...

end E1;or accept E2( ... ) do

...end E2;

or accept ......

else-- other instructions

end select;A task cannot be interrupted (for a rendezvous) when executing the else part. If a calling task makes a call to one of the entries E1, E2, ... , while the called task is executing its else part, then the calling task will be blocked until the called task reaches

Page 67: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 67

another “accept” for that entry, e.g. when the task has a loop around the selective wait.Guards: When a selective wait is reached, such as those above, any of the “accept” alternatives could be accepted, provided there is a call to the entry of that accept. However, we may wish to close (make unavailable) some of the accept alternatives under certain circumstances, e.g., we may not want a stack to accept a call to Pop, if the stack is empty.We can achieve this effect using a guard:

task body Stack isNum_elements : integer := 0;

beginloop

selectaccept Push (Element : in integer) do

Append (Stack_data, Element);end Push;Num_elements := Num_elements + 1;

or when Num_elements > 0 => accept Pop (Element : out integer) do

Element := Retrieve_head (Stack_data);end Pop;Num_elements := Num_elements - 1;

end select;end loop;

end;The programmer can enforce task suspension for a certain period of time through the use of a delay statement, e.g.

task body Stack isbegin loop

Page 68: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 68

select accept Push (Element : in integer) doAppend (Stack_data, Element);

end Push;oraccept Pop (Element : out integer) do

Element := Retrieve_head (Stack_data);end Pop;

ordelay 10.0; -- delay for 10 seconds-- other instructions

end select;end loop;

end;This delay may be interrupted, for example, if 3 seconds into the delay a calling task calls one of the entries, say “Push.” Such an entry call is accepted and a rendezvous takes place. If the delay runs to completion, then the “other instructions” are executed and the selective wait is completed. Tasks must be enclosed in packages or subprogram. We have seen that there may be an “else” part in a selective wait and there may also be (one or more) “delay” alternatives. Those delays may be guarded. There is also a third possibility, which is the “terminate” alternative:

selectaccept ...or accept ...or accept ...or terminate;

end select;Use of the terminate alternative allows tasks to finish execution, even though the selective wait is inside an infinite loop.Be aware that selective waits can only contain one of an “else,” one or more “delays” or “terminate.”

Page 69: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 69

For tasks within packages, if the task entries should be visible outside the package, the task specification will have to be placed in the package specification, the corresponding task body would then be placed in the package body, e.g.,

package P1 is...task T1 is

entry E1 ( ... );entry E2 ( ... );

end T1;...

end P1;package body P1 is

...task body T1 isbegin

-- code containing accepts for E1, E2end T1;...

end P1;Any task T2 enclosed by a package P2 may call any entry of task T1, provided package P2 (either the specification or the body of P2) “withs” package P1. In this case the name of entry E1 in T1, called from P2 would be P1.T1.E1. If the task will only rendezvous internally within the package itself, both the task specification and body may appear within the package body.Entries of tasks (specifications and bodies) enclosed within a subprogram cannot be called from outside that subprogram A task specification declared as follows:

task T1 is ...

Page 70: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 70

introduces a single task named T1.A task in a package begins to execute when the enclosing package body is elaborated , i.e., when the entities enclosed by the body are loaded into memory before the execution of the main program begins. A task specification may be declared as a task type

task type T1_typ is ... -- the specificationtask body T1_typ is ...-- the corresponding body -- (the word “type” is not used with the body)

Assume this task type is declared in package specification P1 and the body appears in package body P1. Such a task body will not begin to execute upon the elaboration of package body P1. We need a task object declaration, e.g.,

with P1;package P2 is

...T1_obj : P1.T1_typ;..

The body of T1_obj will begin to execute upon elaboration of package body P2! Several similar tasks may be declared using a task type declaration, e.g.,

with P1;package P2 is

type T1_arr_typ is array (1..10) of P1.T1_typ;T1_arr_obj : T1_arr_typ;...

In the case of a single processor, several tasks may compete for the same resource (the processor). Tasks may therefore be prioritized: the priority of a task is indicated through the use of a pragma (a directive to the compiler and /or binder), e.g.,

task T1 is

Page 71: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 71

pragma priority (4);entry E1 ( ... );entry E2 ( ... );

end T1;The larger the integer value indicating the priority, the greater the urgency. The range of integers allowed to indicate priority values is defined by the Ada implementation. On a single processor, tasks begin to execute in the order in which their enclosing package bodies elaborate, e.g.,Assume the main program “Main” requires packages R3 and R2 to be elaborated. Assume R2 (spec., and body) elaborates before R3 (spec., and body)--an order determined by the compiler.Assume R2 encloses tasks R2_T1, with priority 4 and R2_T2 with priority 5.Assume R3 encloses tasks R3_T1, with priority 6 and R3_T2 with priority 7.The following is true for most Ada compilers:Task R2_T2 begins to execute first and continues until it blocks (say at a delay statement)Task R2_T1 then executes, until blockingTask R3_T2 then executes, again until blockedTask R3_T1 then executes, until blockedAt this point in time, both R3_T2 and R2_T2 become unblocked (ready to run), because (say) both delay statements time-out at about the same time.Since R3_T2’s priority is higher, it will execute but R2_T2 will stay in the “ready queue,” maintained by the Ada run-time support.

Page 72: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 72

The following example contains a buffer implemented as a circular queue in an array. Remember that such tasks must be inside packages or procedures:

task Buffer isentry Read (c : out character);entry Write (c : in character);

end Buffer;task Producer;task Consumer;task body Buffer is

Pool_size : constant integer := 100;Pool : array (1..Pool_size) of character;Count: integer range 0..Pool_size:=0;In_idx, Out_idx : integer range 1..Pool_size := 1;

beginloop

selectwhen Count < Pool_size =>accept Write (c : in character) do

Pool(In_idx) := c;end Write;In_idx := In_idx mod Pool_size + 1;Count := Count + 1;

or when Count > 0 =>accept Read (c : out character) do

c := Pool(Out_idx);end Write;Out_idx:=Out_idx mod Pool_size+1;Count := Count - 1;

or terminate;end select;

end loop;

Page 73: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 73

end Buffer;task body Producer is

Char : character;begin

loop -- produce the next CharBuffer.Write (Char);exit when Char = ascii.eot;

end loop;end Producer;task body Consumer is

Char : character;begin

loop Buffer.Read (Char);-- process the Char receivedexit when Char = ascii.eot;

end loop;end;

The following code is implements the logic of a binary semaphore. In the Ada tasking model calls to Seize_Resource and Release_Resource will be accepted atomically by the semaphore task, i.e., Semaphore cannot accept a call to Seize_Resource while it is processing Release_Resource and vice-versa.

task Semaphore isentry Seize_Resource;entry Release_Resource;

end Semaphore;task body Semaphore is

In_use : Boolean := false;begin

Page 74: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 74

loopselect

when not In_use =>accept Seize_Resource do

In_use := true;end Seize_Resource;

or when In_use =>accept Release_Resource do

In_use := false;end Release_Resource;

end select;end loop;

end Semaphore;task body Semaphore_user isbegin

Semaphore.Seize_Resource;-- critical sectionSemaphore.Release_Resource;

end Semaphore_user;Tasks such as “Buffer” and “Semaphore” above, that make no entry calls but have accept statements, are called server tasks. Tasks such as “Semaphore_user,” that make only entry calls but have no accept statements, are called actor or client tasks. A task that has an accept statement in its body and makes entry calls as well is called a transducer task.Finally, there is a “select” statement for entry calls:Conditional entry call:

...select

Task_name.Entry_name(...);... -- optional code if entry call succeeds

Page 75: BASICS OF ADA PROGRAMMINGarchive.adaic.com/ed-train/baa/formalmethods/1stclass/... · Web viewThis number is 0(1000001001011111000 ( 219 in our binary notation. Some languages allow

SLIDES Introduction to Ada 83 Programming Page 75

else... -- code to execute if call cannot be accepted at this time... -- this code could just be “null;”

end select;...

Timed entry call:...select

Task_name.Entry_name(...);... -- optional code if entry call succeedsor delay 1.0;... -- code to execute if call cannot be accepted within the... -- delay, this code could just be “null;”

end select; ...