Presentation is loading. Please wait.

Presentation is loading. Please wait.

History of Computing – Ada

Similar presentations


Presentation on theme: "History of Computing – Ada"— Presentation transcript:

1 History of Computing – Ada
Prof. Steven A. Demurjian Computer Science & Engineering Department The University of Connecticut 371 Fairfield Way, Box U-255 Storrs, CT (860) 486–4818 (Office) (860) (CSE Office)

2 Ada Compilers Ada and Ada 2012 – Focus on Changes for 2012 Ada IDE
Other Links Three Presentations Ada Seminar: An Introduction (jump to PDF) An Introduction to Ada Ada and Ada 2012 – Focus on Changes for 2012 Two PDFs

3 Programming Languages Fall 2002
An Introduction to Ada Programming Languages Fall 2002

4 Basic Structure of a Program
A program is a collection of units Packages Functions Procedures Bound together to form a program Typically a unit is stored in a file Units reference other units

5 Procedure procedure H (M : Integer) is declarations begin statements return; end H; Typical use is procedure Main is … which defines the main program

6 Function function Max (A : Integer; B : Integer) return Integer is Result : Integer; begin if A > B then Result := A; else Result := B; end if; return Result; end Max;

7 Packages Packages define a related collection of types, and subprograms (procedure and functions) A package provides a set of services to a client A package may be a client of another package

8 Package Spec (Declaration)
package X is declarations types subprogram specs (but not subprogram bodies) end X;

9 Subprogram Specs procedure Print_In_Hex (X : Integer);
function Max (A, B : Integer) return Integer; Note the semicolon instead of is A subprogram spec has everything you need to know to use the subprogram A client needs only the spec

10 Package Bodies package body X is declarations subprograms local to body variables/constants local to body subprogram bodies for subprogram specs appearing in the package spec begin initialization statements end X;

11 How to be A Client To access a package, use a WITH: with Calendar; procedure Main is Today : Calendar.Time; … end Main;

12 The Use Clause Accessing Stuff in Calendar without dots
with Calendar; use Calendar; procedure Main is Today : Time; … end Main;

13 Package Bodies as Clients
with Calendar; package body Julian_Calendar_Stuff is … end Julian_Calendar_Stuff; Here we have the implementation of a package done using stuff in another package

14 Package Specs as Clients
A package spec can build on another spec with Calendar; use Calendar package To_Do_List is … procedure Enter (T : Time; M : String); Enter new item in todo list. Time is deadline. M is description. end To_Do_List;

15 The Idea of a Package Spec
Write the package spec It is like a contract between client and body of the spec Write the body Write the client Last two activities are completely independent (and should not talk to one another except “via” the spec)

16 Integer Type Declarations
Type Integer is built in But you don’t want to use it Because its range is implementation defined Because it is defined to match the machine not your problem Because it does not take advantage of strong typing to prevent errors

17 Defining Integer Types
Define type according to use type Day_In_Year is range ; type Age is range ; type Temperature is range ; Now we can define variables of the type Today_Day : Day_In_Year; Employee_Age : Age; Machine_Room_Temp : Temperature;

18 Why Define Integer Types
No dependence on implementation Unlike type int in C Range of types matches problem Get an error or warning at compile time Age := 200; Or an exception at runtime Age := Age ;

19 Strong Typing Cannot mix integer types:
Current_Temp : Temperature; Current_Pressure : Pressure; Current_Temp := Current_Pressure + 1; Error, cannot assign pressure to temperature Current_Temp := Current_Temp + Current_Pressure Error, cannot add temperature to pressure

20 Integer Subtypes A subtype creates a limited range
But is still the same type subtype OK_Operating_Range is Temperature range ; Room_Temp : Temperature; Machine_Room_Temp : OK_Operating_Range … Machine_Room_Temp := Room_Temp; Raises exception if Room_Temp out of range

21 Catching Exceptions You can catch an exception at run time
begin … Machine_Room_Temp := Room_Temp … exception when Constraint_Error => recovery stuff end;

22 Unsigned (Modular) Types
Modular types have wrap around: type M is mod 7; -- values are 0,1,2,3,4,5,6 q : m := 6; -- initialization … q := q + 2; -- result is 1 Most common use, conventional unsigned type Uns_32 is mod 2 ** 32; Remember that twos complement arithmetic is equivalent to arithmetic mod 2**wordsize

23 Real Types Float types (control relative accuracy)
type My_Float is digits 7; type Xfloat is digits 7 range ; subtype F1 is My_Float range ; Digits is decimal digits of relative precision There is a formal model for fpt in Ada Target independent (parametrized) Guarantees minimal accuracy Operations defined in terms of model numbers Results fall in defined model interval

24 Fixed-Point Types Fixed-point types are real types where you control the absolute accuracy. Typically implemented as scaled integers type Velocity is delta range ; Decimal fixed-point types Decimal small Typical use in financial programming type Money is digits delta 0.01 range _999_999.00;

25 Character Types Built in types
Character (8-bit Latin-1) Wide_Character (16-bit Unicode/ISO 10646) Good enough for most purposes, but you can define your own types: type My_Character is (‘A’, ‘B’, ‘C’, ….); Note on standard types Standard types are in package Standard that is automatically visible in every unit.

26 Enumeration Types An enumeration type is a sequence of ordered enumeration literals: type State is (Off, Powering_Up, On); No arithmetic defined S1, S2 : State; S1 := S1 + S2; -- Illegal Can add/subtract one State’Pred (S1) State’Succ (S2) These are examples of attributes

27 Boolean Types Predefined enumeration type
type Boolean is (False, True); Expressions of type boolean used in if statements while loops exit statements Etc.

28 Access Types Access types function like pointers
But are not necessarily implemented that way type r is access integer; type s is access all integer; The all allows the access value to reference any item at all. Without all, you can only reference objects specifically allocated for the pool in question.

29 Using Access Types Allocate an object using new
type AI is access all integer; Ptr : AI; … Ptr := new Integer; -- uninitialized Ptr := new Integer’(12); -- initialized To obtain value dereference: V : Integer; … V := Ptr.all;

30 Array Types Arrays can have 1 or more subscripts type Vector is
array (Integer range ) of Integer; type Matrix is array (Integer range , Character range ‘A’ .. ‘Z’) of Vector; VV : Vector := (others => 10); -- aggregate MM : Matrix; … MM (5, ‘C’) := VV; VV (1 .. 5) := VV (2 .. 6); -- slicing (one dim only)

31 Array Bounds and Types Are the bounds of an array answer part of the properties of the array type? Things are much cleaner if we answer yes, as in Pascal, but this is very limiting For example, a sort routine cannot take a vector of any size to sort. Instead we consider the bounds to be like the range of an integer type

32 Unconstrained Arrays Unconstrained array type has no bounds
type UA is array (Int range <>) of Int; -- cannot use UA to declare a variable -- instead must build a subtype subtype UA5 is UA (1 .. 5); UAV5 : UA5 := (6,5,4,3,2); -- can also set bounds for a variable UAV2 : UA (1 .. 2);

33 String Types A string type is an array whose elements are a character type. Two standard built in string types type String is array (Natural range <>) of Character; type Wide_String is array (Natural range <>) of Wide_Character; S : String (1 .. 5) := “Hello”; Note: Natural is a predefined subtype of Integer with bounds 0 .. Integer’Last;

34 Record Types Like struct in C
type Date is record Year : Year_Number := 2002; -- default Month : Month_Number; Day : Day_Number; end record; DD : Date; EE : Date := (2001, 8, Day => 27); … DD.Month := EE.Month – 1;

35 Arrays/Records and Access Types
Access types and records/arrays type A is array (Int range ) of Int; type AP is access A; AV : AP; … AV.all (3) := AV (4); -- can omit .all here Similarly do not need .all for fields of records DP.Month := DP.all.Month + 1;

36 What about Union Types? The union type in C is fundamentally unsafe, and therefore unacceptable union (int, float) puzzle; Now puzzle has either an int or a float But at runtime, cannot tell which So we have to trust the programer In Ada we are short on trust 

37 Instead, Discriminated Types
A record can have discriminants: type IF is (Int, Float); type Int_Float (V : IF := Int) is record case V is when Int => Int_Val : Integer; when Float => Float_Val : Float; end case; end record; Now the value of the discriminant V shows what type is currently present

38 More on Discriminated Records
Referencing a discriminanted type Puzzle : Int_Float; … Puzzle := (Float, 1.0); F := Puzzle.Float_Val; -- OK I := Puzzle.Int_Val; raise exception … Puzzle.V := Int; -- not allowed!

39 More on Discriminated Records
Can make subtypes subtype PuzzleI is puzzle (Int); -- this type only holds int values Can dimension arrays from discriminant: Subtype Vlen is Integer range ; type Vstr (Vlen : Integer := 0) is record Data : String (1 .. Vlen); end record; VV : Vstr := (5, “hello”);

40 Other Types Derived types (copying a type)
Extended types (object oriented stuff) Task types (active threads) Protected types (passive synchronization) More on all these later!

41 Statement Forms Assignment statement (is not an expression)
Variable := expression; If statements if condition then statements elsif condition then statements … else statements end if;

42 Statement Forms (cont)
Loops for J in Integer range loop statements end loop; while condition loop statements end loop; loop statements end loop;

43 Statements (cont) Exit statement exit; exit when condition;
Can only be used in a loop Can use labels: Outer : loop Inner : loop … exit Inner when Done; end loop Inner; end loop Outer;

44 Statements (cont) Case statements
case expression is when 0 => statements when 1 | 10 => statements when => statements end case; All values in when branches must be static All possible values of expression must be included exactly once Can use when others => to cover rest

45 Statements (cont) Return statement Raise statement
return; procedure return expression; -- function Only in procedure/function Function must have at least one return Raise statement raise exception-name;

46 Declaring and Handling Exceptions
Declaring an exception Error, Disaster : exception; Raising an exception raise Disaster; -- strips stack frames till a handler is found Handling an exception exception when Disaster => statements

47 More on Exception Handling
Anywhere we have begin end, we can do: begin statements exception when handler => statements; when handler => statements; end;

48 Block Statement Block statement can be used anywhere
declare declare section optional declarations begin statements exception exception section optional handlers end;

49 Summary That’s enough to get you on your way!
First assignment will be to do one of the ACM programming competition problems You do the program and make test data Your choice of examples See website for URL

50 Ada and Ada 2012 – Overview and rationale
Quentin Ochem Technical Account Manager

51 Driving Design Principles
Be explicit as much as possible Put as much (formal) information as possible in the code Put as much (formal) information as possible in the specification Avoid pointers as much as possible Avoid shortcuts Avoid ambiguous constructs as much as possible Make dubious constructs possible but visible int * i = malloc (sizeof (int)); i++; type I_Acc is access all Integer; I : I_Acc := new Integer; function Acc_To_Int is new Ada.Unchecked_Conversion (I_Acc, Integer); function Int_To_Acc is new Ada.Unchecked_Conversion (Integer, I_Acc); I := Int_To_Acc (Acc_To_Int (I) + I_Acc’Size);

52 Ada eases manual and automatic analysis at various levels:
Driving Rationale Ada eases manual and automatic analysis at various levels: Developer review Peer review Compiler errors and warnings Static analysis tools Proof tools Maintenance Simplify code and readability when dealing with high-level programming concepts int [] a = new int [10]; a [0] = 1; a [1] = 1; for (int i = 2; i < 10; i++) a [i] = 0; A : Integer_Array ( ) := (0 => 1, 1 => 1, others => 0)

53 A type is a semantic entity, independent from its implementation
Strong Typing A type is a semantic entity, independent from its implementation Strong typing forbids implicit conversions Values are checked at run-time (can be deactivated) type Kilometers is new Float; type Miles is new Float; Length_1 : Miles := 5.0; Length_2 : Kilometers := 10.0; D : Kilometers := Length_1 + Length_2; type Ratio is new Float range ; Qty : Integer := 10; Total : Integer := 1000; R : Ratio := Ratio (Total / Qty) * 100.0;

54 Strong typing (continued)
Enumerations have a dedicated semantic type Color is (Red, Blue, White, Green, Black, Yellow); type Direction is (North, South, East, West); type Light is (Green, Yellow, Red); C : Color := Red; This is the red from Color L : Light := Red; This is the red from Light C := L; -- This is not permitted C := North; -- This is not permitted enum Color {Red, Blue, White, Green, Black, Yellow}; enum Direction {North, South, East, West); Color C = Red; C = West; // Ok, but what does it mean? C = 666; // Ok, but what does it mean?

55 Arrays can be indexed by any discrete types (integers, enumeration)
First and Last index can be specified at declaration time Buffer overflows are checked at run-time There is an array literal (aggregate) type Some_Array is array (Integer range <>) of Integer; type Color_Array is array (Color range <>) of Integer; Arr1 : Some_Array ( ) := (666, 777); Arr2 : Color_Array (Red .. Green) := (Red => 0, others => 1); Arr1 (9) := 0; -- Exception raised, Index out of range

56 Array Copy, Slicing and Sliding
Arrays provide a high-level copy sematic Arrays provide a high level slicing/sliding sematic type Integer_Array is array (Integer range <>) of Integer; V1 : Integer_Array ( ) := (others => 0); V2 : Integer_Array ( ) := (others => 1); begin V1 := V2; type Integer_Array is array (Integer range <>) of Integer; V1 : Integer_Array ( ) := (others => 0); V2 : Integer_Array ( ) := (others => 1); begin V1 (1 .. 2) := V2 ( );

57 The correct parameter usage is done at compile-time
Parameter Modes Three parameter modes : in (input), out (output) and in-out (input/output) The correct parameter usage is done at compile-time The compiler decides if it has to be passed by reference or copy This is a case of explicit pointer avoidance procedure Do_Something (P1 : in Integer; -- P1 can’t be changed P2 : out Integer; -- No initial value on P2 P3 : in out Integer) -- P3 can be changed procedure Do_Something (P1 : in Huge_Structure) –- Passed by reference if too big

58 Pre, Post Conditions and Invariants
Generalized contracts are available through pre- and post-conditions New type invariants will ensure properties of an object Subtype predicates procedure P (V : in out Integer) with Pre => V >= 10, Post => V’Old /= V; type T is private with Type_Invariant => Check (T); type Even is range with Dynamic_Predicate => Even mod 2 = 0;

59 All entities are subject to encapsulation
Package Architecture All entities are subject to encapsulation Not only OOP constructions Specification and Implementation details are separated from the package, addresses any kind of semantic entity package Stack is procedure Push (V : Integer); ... end Stack; package body Stack is procedure Push (V : Integer) is begin ... end Stack;

60 A package contains well identified public and private parts
Privacy A package contains well identified public and private parts The user can concentrate on only one part of the file package Stack is procedure Push (V : Integer); procedure Pop (V : out Integer); private type Stack_Array is array ( ) of Integer; Current_Pos : Integer := 0; end Stack;

61 A private type can be implemented by any data structure
Private Types A private type can be implemented by any data structure User code does not rely on the actual representation package Stack is procedure Push (V : Integer); procedure Pop (V : out Integer); private type Stack_Array is array ( ) of Integer; Current_Pos : Integer := 0; end Stack; Quand il faudra passer d’un type tableau à un type record, le code utilisateur ne changera [as

62 Allows to optimize memory usage Allows to precisely map data
Data Representation Allows to optimize memory usage Allows to precisely map data type Size_T is range ; type Header is record Size : Size_T; Has_Next : Boolean; end record; for Header use record Size at 0 range ; Has_Next at 1 range ;

63 Instanciation has to be explicit
Genericity Instanciation has to be explicit generic type T is private; package P is V : T; end P; package I1 is new P (Integer); package I2 is new P (Integer); I1.V := 5; I2.V := 6; template <class T> class P { public static T V; }; P <int>::V = 5; P <int>::V = 6;

64 Ada implements full OOP principles
Object Orientation Ada implements full OOP principles Encapsulation Inheritance Dispatching Safe OOP paradigm is implemented A unique concrete inheritance tree Multiple interface inheritance “Overriding” methods can be checked OOP can be comfortably used without (explicit) pointers

65 Object Orientation Example
type Root is tagged record F1 : Integer; end record; not overriding function Get (Self : Root) return Integer; type Child is new Root with record F2 : Integer; overriding function Get (Self : Child) return Integer; List : Root_List; L.Add (Root’(F1 => 0)); L.Add (Root’(F1 => 1)); L.Add (Child’(F1 => 2, F2 => 0)); Total := 0; for Item of List loop Total := Total + Item.Get; end loop;

66 If pointers are needed…
Pointers are typed, associated with accessibility checks Objects that can be pointed are explicitly identified In the absence of de-allocation, pointers are guaranteed to never dangle Pointers’ constraints can be specified Is null value expected? Is the pointer constant? Is the object pointed by the pointer constant? type My_Pointer is access all Integer; Global_Int : aliased Integer; function Get_Pointer (Local : Boolean) return My_Pointer is Local_Int : aliased Integer; Tmp : My_Pointer; begin if Local then Tmp := Local_Int’Access; else Tmp := Global_Int’Access; end if; return Tmp; end Get_Pointer; Tmp := Local_Int’Unchecked_Access;

67 Concurrent Programing
Threads and semaphore are first class citizens task Some_Task is begin loop Do something select accept Some_Event do Do something end Some_Event; or accept Some_Other_Event do Do something end Some_Other_Event; end select; end loop; end; ... Some_Task.Some_Event;

68 Why is all of this of any use?
For readability Specification contains formally expressed properties on the code For testability Constraints on subprograms & code can lead to dynamic checks enabled during testing For static analysis The compiler checks the consistency of the properties Static analysis tools (CodePeer) uses these properties as part of its analysis For formal proof Formal proof technologies can formally prove certain properties of the code (High-Lite project)

69 … but safety features have to be re-invented
Yes But… It is possible to reach similar levels of safety with other technologies (MISRA-C, RT-Java) … but safety features have to be re-invented Requires additional guidelines Requires additional tools Limited by the original language features Examples of “circle fits in a square” features Types management in MISRA-C Stack emulation in RT-Java When long term reliability is a goal, using the correct paradigm to start with will reach higher levels at lower cost

70 Key Messages

71 Ada 2012 Ada 2005 Ada 95 Ada 83 Object Orientation Better Access Types
Ada Evolution Ada 83 Ada 95 Object Orientation Better Access Types Protected Types Child Packages Ada 2005 Interfaces Containers Better Limited Types Ravenscar Ada 2012 Pre / Post / Invariants Iterators New expressions Process Affinities

72 In out parameters for functions
Ada 83 to 2005 forbids the use of in out for function Since Ada 95, it’s possible to workaround that with the access mode (but requires the explicit use of an access) Ada 2012 allows ‘in out’ parameters for functions function Increment (V : in out Integer) return Integer is begin V := V + 1; return V; end F;

73 Ada 2012 detects “obvious” aliasing problems
Aliasing detection Ada 2012 detects “obvious” aliasing problems function Change (X, Y : in out Integer) return Integer is begin X := X * 2; Y := Y * 4; return X + Y; end; One, Two : Integer := 1; begin Two := Change (One, One); -- warning: writable actual for "X" overlaps with actual for "Y“ Two := Change (One, Two) + Change (One, Two); -- warning: result may differ if evaluated after other actual in expression

74 Pre, Post conditions and Invariants
The Ada 2012 standard normalizes pre-conditions, post-conditions New type invariants will ensure properties of an object Subtype predicates procedure P (V : in out Integer) with Pre => V >= 10, Post => V’Old /= V; type T is private with Type_Invariant => Check (T); type Even is range with Dynamic_Predicate => Even mod 2 = 0;

75 Conditional expressions
It will be possible to write expressions with a result depending on a condition procedure P (V : Integer) is X : Integer := (if V = 10 then 15 else 0); Y : Integer := (case V is when => 0, when others => 10); begin null; end;

76 Iterators Given a container, it will be possible to write a simple loop iterating over the elements Custom iterators will be possible Ada 2005 Ada 2012 for X in C.Iterate loop -- work on X Y := Container.Element (X); -- work on Y end loop; X : Container.Iterator := First (C); Y : Element_Type; declare while X /= Container.No_Element loop -- work on X Y := Container.Element (X); -- work on Y X := Next (X); end loop; for Y of C loop -- work on Y end loop;

77 Quantifier expressions
Checks that a property is true on all components of a collection (container, array…) type A is array (Integer range <>) of Integer; V : A := (10, 20, 30); B1 : Boolean := (for all J in V’Range => V (J) >= 10); -- True B2 : Boolean := (for some J in V’Range => V (J) >= 20); -- True

78 Generalized memberships tests
Memberships operations are now available for all kind of Boolean expressions Ada 2005 Ada 2012 if C = ‘a’ or else C = ‘e’ or else C = ‘i’ or else C = ‘o’ or else C = ‘u’ or else C = ‘y’ then if C in ‘a’ | ‘e’ | ‘i’ | ‘o’ | ‘u’ | ‘y’ then case C is when ‘a’ | ‘e’ | ‘i’ | ‘o’ | ‘u’ | ‘y’ =>

79 Expression functions Function implementation can be directly given at specification time if it represents only an “expression” function Even (V : Integer) return Boolean is (V mod 2 = 0);

80 Ada 2005 containers are unsuitable for HIE application
Rely a lot of the runtime Not bounded Ada 2012 introduces a new form of container, “bounded” used for HIE product Statically memory managed Static analysis and proof

81 Task can be assigned to specific processors
Processor affinities Task can be assigned to specific processors Enhances control over program behavior Enables Ravenscar on multi-core task body T1 is pragma CPU (1); begin […] end T1; task body T2 is pragma CPU (2); begin […] end T2;

82 Ada 2012 safety improvements
Improve readability Specification contains formally expressed properties on the code Improve testability Constraints on subprograms & code can lead to dynamic checks enabled during testing Allow more static analysis The compiler checks the consistency of the properties Static analysis tools (CodePeer) uses these properties as part of its analysis Allow more formal proof Formal proof technologies can prove formally certain properties of the code (High-Lite project)


Download ppt "History of Computing – Ada"

Similar presentations


Ads by Google