Case Study ADA

download Case Study ADA

of 26

Transcript of Case Study ADA

  • 7/30/2019 Case Study ADA

    1/26

    Case study: ADA

    ADA was designed in the late 1970s to be a general-purpose imperative andconcurrent programming language, suitable in particular for implementation oflarge-scale and embedded systems. The ADA design team was large, andreceivedinputs from a still larger number of interested persons, but the design effortwas dominated by Jean Ichbiah. (Too many programming languages bear thehallmarks of design by committee: a proliferation of badly-integrated features,attempting to satisfy the conflicting demands of all the committee members.Ichbiahs firm control ensured that ADA largely avoided that fate.)As a consequence of the way it was developed, ADA is a large but reasonablycoherent language. It supports nearly all the concepts described in this book.In particular, unlike classical imperative languages such as C and PASCAL,ADAsupports data abstraction, generic abstraction, and exceptions.ADA was extended in the early 1990s, primarily to support object-oriented

    programming. Where necessary to distinguish between the two versions of thelanguage, we refer to them as ADA83 and ADA95, respectively.This section is an overview of the imperative parts ofADA.We shall turn to theobject-oriented and concurrent parts of ADA in Chapters 12 and 13, respectively.

    Values and typesADA has a full repertoire of primitive types: Boolean, Character, enumerationtypes, and numeric types (integer, floating-point, and fixed-point). Unusually,ADA allows programmers to declare their own numeric types, which is good for

    portability.ADA has an adequate repertoire of composite types: array types, record types,and discriminated record types (disjoint unions).ADA does not support recursive types directly. Instead, programmers mustdeclare recursive types using pointers.ADA complies well with the Type Completeness Principle. Constants, variables,

    parameters, and function results can be of any type. The equality-testoperations = and /=, and the assignment operation :=, can be applied tooperands of any type (unless the programmer chooses otherwise by declaring a

    type to be limited).ADA supports subtypes systematically in the sense that all types can havesubtypes (see Section 8.1.1). However, an ADA subtype is not itself a type. In

    particular, an ADA type declaration creates a new and distinct type, but anADA subtype declaration merely names a subtype of an existing type. A type iscompatible with any of its subtypes.

    ADA types and subtypesNatural is a subtype of Integer:

    subtypeNatural is Integerrange 0 .. Integer'last;

  • 7/30/2019 Case Study ADA

    2/26

    The following functions second parameter is of subtype Natural:functionpower (b: Float; n: Natural) return Float;In a function call to power, the compiler merely checks that the secondargumentstype is compatible with Natural (i.e., its type is Integer or a subtype of Integer).However, a run-time check may be needed to ensure that the arguments value isin thesubtype Natural.Finally, consider the following proper procedure:procedure inc (i: in out Integer);In a procedure call to inc, the compiler merely checks that the arguments type iscompatible with Integer (i.e., its type is Integer or a subtype of Integer). Norun-time check is needed.ADAs expression repertoire includes record and array constructions andfunction calls. It does not include conditional expressions, iterative expressions,or block expressions. Thus programmers are forced to use function calls forcomputations that are too complicated for this rather limited expressionrepertoire.The point is that an ADA functions body is syntactically a command, and somaycontain loops, exception handlers, and so on. By the same token, however,functioncalls potentially have side effects.

    Variables, storage, and controlADA supports global, local, and heap variables. A heap variable of type Tisallocated by an expression of the form new T, or alternatively new T'(. . .)which also initializes the heap variable.ADAs repertoire of commands is conventional for a modern imperativelanguage: a skip command, assignment commands, procedure calls, sequentialcommands, conditional commands (if- and case commands), iterative commands(while- and for-commands, and basic loops), block commands, andexceptionhandlingcommands.ADAs exit and return sequencers allow single-entry multi-exit control flowsto be programmed as easily as single-entry single-exit control flows. ADA alsosupports jumps, although they are redundant.ADA was the first major language to provide a secure form of exceptionhandling. An ADA83 exception could not carry a value. An ADA95 exceptioncancarry a string, enabling the handler to receive additional information about theabnormal situation represented by the exception (but that information has to beencoded as a string before the exception is thrown, and decoded by the handler

    after it is caught).

  • 7/30/2019 Case Study ADA

    3/26

    Bindings and scopeAn ADA program consists of program units: procedures, packages, and genericunits. The programmer specifies which of these procedures is to be treated as themain program.Within a program unit or block command we declare anything: types andsubtypes, constants and variables, exceptions, tasks, and even other programunits.Procedures, packages, and generic units are major program units and arenormally declared either globally or inside other program units. Although it islegal in ADA to declare a program unit inside an inner block, that would allowthe program unit to access variables declared in outer blocks, giving rise totight coupling.

    Procedural abstractionADA supports both proper procedures and function procedures.ADA supports three parametermodes, which emphasize the direction of dataflow (into and/or out of the procedure) rather than the underlying parametermechanisms.In-parameter: the formal parameter is a constant, and is bound to theargument (a first-class value).In-out-parameter: the formal parameter is a variable, and permits bothinspection and updating of the argument (also a variable). Out-parameter: the formal parameter is a variable, and permits only updatingof the argument (also a variable).For primitive types,ADA insists that the above effects are achieved by copy-in,copy-in-copy-out, and copy-out mechanisms, respectively (Section 5.2.1).For composite types, ADA allows the compiler to choose whether the aboveeffects are achieved by copy or reference mechanisms. Reference mechanisms(Section 5.2.2) introduce the risk of aliasing, but are usually more efficient thancopy mechanisms for large records and arrays.AnADA function procedure has in-parameters only. Thus a function procedurecannot update variables supplied as arguments, but this is really only a half-heartedattempt to discourage side effects. The functions body can update globalvariables,a concealed and therefore more dangerous source of side effects.ADA supports context-dependent overloading of procedures. In other words,two or more procedures may share the same identifier in the same scope

    provided only that they differ in their parameter or result types. Also, ADAtreats its operators exactly like functions: we may overload any existing operator

    by providing an additional definition. (But we cannot invent new operatorsymbols.)

  • 7/30/2019 Case Study ADA

    4/26

    ADA procedures are not first-class values. In particular, a procedure P1 cannotbe passed as an argument to another procedureP2. However, we can achieveessentially the same effect by passing apointertoP1 as an argument toP2.

    Data abstractionADA supports data abstraction principally by means of packages, as we saw inSection 6.1. Each package consists of a specification and a body. The packagespecification serves to declare the packages public components, and thus specifythe packages API. Thepackage body serves to provide implementation details:definitions of any public procedures, and declarations of any private components.In general, the components of an ADA package may be anything that can bedeclared in the language: types and subtypes, constants and variables, exceptions,

    procedures, generic units, inner packages, and so on. Moreover, any subset ofthese components may be public. Thus ADA packages support encapsulation.An important special case is a package that defines an abstract type. In thiscase the package specification declares the abstract type itself, and specifies the

    public procedures that operate on the abstract type. The name of the abstract typeis public, but its representation is private. The package body defines the public

    procedures, and declares any private (auxiliary) procedures.ADA abstract typeProgram 11.6(a) shows the specification of a package named Dictionaries. Thisdeclares an abstract type Dictionary, and specifies public procedures that willoperateon that abstract type.Program 11.6(b) outlines the corresponding package body, which defines all the

    publicprocedures. The omitted details depend on the chosen representation for theabstract type(which could be a search tree, for instance).Application code could use the Dictionaries package as follows:use Dictionaries;dict: Dictionary;current_word: Word;. . .

    load(dict);loop

    . . .

    if not contains(dict, current_word) then. . .

    end if;. . .

    end loop;Values of type Dictionary can be manipulated onlyby calling the public

    operationsof the Dictionaries package. The ADA compiler will prevent any attempt by the

  • 7/30/2019 Case Study ADA

    5/26

    application code to access the Dictionary representation. Thus, without having torelyon the application programmers self-discipline, the application code can bemaintainedindependently of the package.All ADA types, including abstract types, are by default equipped with thelanguages assignment and equality test operations, except for types defined aslimited.Assignment of a static data structure (one constructed without pointers)entails copying all its components, which is copy semantics. On the other hand,assignment of a dynamic data structure (one constructed using pointers) entailscopying the pointers but not their referents, which is reference semantics. Thisinconsistency creates a dilemma when we design an abstract type, since thetypesrepresentation is hidden and is not supposed to influence the behavior of theapplication code. Only if we are confident that the abstract type will always berepresented by a static data structure should we declare it as simply private. Ifthe abstract type might conceivably be represented by a dynamic data structure,we should declare it as limited private. (And if the abstract type needsassignment and/or equality test operations, we should make the package provideits own.)Where a package defines an abstract type, the privatepart of the packagespecification defines the abstract types representation. It would be more logicalfor the representation to be defined in the package body, along with the otherimplementation details. The reason for this design illogicality is that the ADAcompiler must decide, using the package specification alone, how much storagespace will be occupied by each variable of the abstract type. (Declarations ofsuchvariables might be compiled before the package body is compiled.) This is anexample of a design compromise motivated by implementation considerations.Generic abstractionAs we saw in Sections 7.1.1 and 7.2.1,ADA allows any package to be madegeneric,and then it can be parameterized with respect to values, variables, types, and

    procedures on which it depends. Here we give one further example.

    ADA generic package with type and function parametersConsider the following generic package specification:generic

    type Row is private;type Key is private;with function row_key (r: Row) return Key;package Tables is

    type Table is limited private;-- A Table value contains a number of rows, subject to the constraint

  • 7/30/2019 Case Study ADA

    6/26

    -- that no two rows have the same key.exception table_error;procedure clear (t: out Table);-- Make table t contain no rows.procedure add (t: in out Table; r: in Row);-- Add row r to table t. Throw table_error if t already contains-- a row with the same key as r.function retrieve (t: Table; k: Key) return Row;-- Return the row in table t whose key is k. Throw table_error if-- t contains no such row.Private

    capacity: constant Positive := . . .;type Table isrecord

    size: Integerrange 0 .. capacity;rows: array (1 .. capacity) ofRow;end record;end Tables;The generic package is parameterized with respect to the type Row, the type Key,and thefunction row_key.The package body will userow_keyto implement the addandretrieve operations:package body Tables isprocedure clear (t: out Table) isbegin

    t.size := 0;end;procedure add (t: in out Table; r: in Row) isk: Key := row_key(r);begin

    for i in 1 .. t.size loopifrow_key(t.rows(i)) = kthenraise table_error;end if;end loop;t.size := t.size + 1;t.rows(t.size) := r;end;function retrieve (t: Table; k: Key) return Row isbegin

    for i in 1 .. t.size loopifrow_key(t.rows(i)) = kthenreturn t.rows(i);end if;

    end loop;raise table_error;

  • 7/30/2019 Case Study ADA

    7/26

    end;end Tables;Since both the type parameters Row and Key are declared as private, they areguaranteedto be equipped with assignment and equality-test operations.Application code could use this generic package as follows:subtype Short_Name is String(1 .. 6);subtype Phone_Numberis String(1 .. 12);type Phone_Book_Entry isrecord

    name: Short_Name; number: Phone_Number;end record;function entry_name (e: Phone_Book_Entry)return Short_Name isbegin

    return e.name;end;package Phone_Books is new Tables(Phone_Book_Entry, Short_Name, entry_name);use Phone_Books;

    phone_book: Table;. . .

    add(phone_book, "David", "+61733652378");The instantiation generates an ordinary package by substitutingPhone_Book_Entry forRow, Short_Name for Key, and entry_name for row_key. The generated packageisnamed Phone_Books.As well as a package, we can often make an ordinary procedure generic. Ageneric procedure gives us an extra level of abstraction.

    ADA generic procedure with a type parameterThe following declares a swapping procedure, parameterized with respect to thetype Itemof the values being swapped:generic

    type Item is private;procedure swap (x, y: in out Item);And here is the corresponding procedure body:procedure swap (x, y: in out Item) isz: constant Item := x;begin

    x := y; y := z;

    end;

  • 7/30/2019 Case Study ADA

    8/26

    We instantiate this generic procedure by supplying an argument type to be boundtothe type parameter Item:procedure swap_characters is new swap(Character);procedure swap_integers is new swap(Integer);Each instantiation of swap generates an ordinary (non-generic) procedure. Thesecondinstantiation generates an ordinary procedure named swap_integers, with twoin-out-parameters of type Integer. The generated procedure can be called in theusual manner:a: array (. . .) ofInteger;. . .

    swap_integers(a(i), a(j));

    Note that an ADA generic procedure must first be instantiated to generatean ordinary procedure, before the latter can be called. ADA does not allow theinstantiation and call to be combined. (But see Exercise 11.5.)

    Separate compilationSeparate compilation is similar to independent compilation (see Section 11.3.5),but with the important difference that type checking across compilation units isnot compromised.We have seen that an ADA package is declared in two parts: a packagespecification and a package body. Similarly, a procedure can be declared in two

    parts: a procedure specification (its heading) and a procedure body. In each case,the package or procedure has aspecification of its interface, and a bodycontainingimplementation details.An ADA compilation unit may be a single procedure specification, procedure

    body, package specification, or package body. Each compilation unit must name(in a with-clause) every separately compiled procedure or package on whichit depends.A procedure or package specification must be compiled before the corresponding

    procedure or package body, and before any compilation unit thatdepends on it. The ADA compiler ensures that compilation units are compiled(and recompiled) in a correct order. It also performs full type checks acrosscompilation units, by the simple expedient of remembering the contents of every

    procedure and package specification.ADA separate compilationConsider an application program that uses the Dictionaries package of Program11.6.Suppose that there are three compilation units: the package specification, the

    packagebody, and the application code. The application code might look like this:

  • 7/30/2019 Case Study ADA

    9/26

    with Dictionaries; use Dictionaries;procedure main isdict: Dictionary;begin

    load(dict);. . .

    end;We compile the Dictionaries package specification first, followed (in any order)

    by the Dictionaries package body and the application code.If we subsequently modify the package specification (an API change), then wemust recompile not only the package specification but also the package body andtheapplication code.If instead we modify the package body only (an implementation change), then weneedrecompile only the package body. Neither the package specification nor theapplicationcode is affected.

    Notice that we derive this benefit onlybecause the package is split intospecificationand body. If the whole package were a single compilation unit, then even a minorimplementation change would force the whole package and the application codeto be recompiled.

    Package libraryThe ADA programming language comes with a modest package library. Thissupports character handling, string handling, dates and times, numerical(includingcomplex) functions, input/output, storage deallocation, low-level programming,and so on.The ADA package library is pre-compiled. The application programscompilationunits must be linked with the library packages on which they depend.

    A simple spellcheckerTo conclude this overview of imperative programming in ADA, let us examineanADA implementation of the simple spellchecker specified in Section 11.2.1. The

    programs architecture is shown in Figure 11.2. The program consists of severalcompilation units, and is outlined in Programs 11.511.7.Program 11.5(a) shows the Words package specification, which declares theabstract type Word together with its operations. Program 11.5(b) outlines theWords package body, which defines these operations. Note that the packagespecification is prefixed by with Ada.Text_IO;, because it depends on that

    library package

  • 7/30/2019 Case Study ADA

    10/26

    with Ada.Text_IO; use Ada.Text_IO;package Words istype Word is private;-- Each Word value is a single word.procedure get_word (in_doc, out_doc: in out File_Type;wd: out Word);-- Read the next word from in_doc into wd, copying any preceding punctuation-- to out_doc. Raise end_error if there is no next word to be read.procedureput_word (out_doc: in out File_Type;wd: in Word);-- Write wd to out_doc.private

    type Word is . . .; -- representationend Words;Program 11.5(a) Specification of the Words package in ADA (in outline).

    package body Words is. . . -- auxiliary proceduresprocedure get_word (in_doc, out_doc: in out File_Type;wd: out Word) isbegin

    . . .

    end;procedureput_word (out_doc: in out File_Type;wd: in Word) isbegin

    . . .

    end;end Words;Program 11.5(b) Body of the Words package in ADA (in outline).

    with Words; use Words;package Dictionaries istype Dictionary is limited private;-- Each Dictionary value is a set of words.

    procedure clear (dict: out Dictionary);-- Make dict empty.

  • 7/30/2019 Case Study ADA

    11/26

    procedure add (dict: in out Dictionary; wd: in Word);-- Make wd a member of dict.function contains (dict: Dictionary; wd: Word)return Boolean;-- Return true if and only if wd is a member of dict.procedure load (dict: out Dictionary;filename: in String);-- Load dict from filename.procedure save (dict: in Dictionary;filename: in String);-- Save dict to filename.private

    type Dictionary is . . .; -- representationend Dictionaries;Program 11.6(a) Specification of the Dictionaries package in ADA (in outline).

    package body Dictionaries is. . . -- auxiliary proceduresprocedure clear (dict: out Dictionary) isbegin

    . . .

    end;procedure add (dict: in out Dictionary; wd: in Word) isbegin

    . . .

    end;function contains (dict: Dictionary; wd: Word)return Boolean isbegin

    . . .

    end;procedure load (dict: out Dictionary;filename: in String) isbegin

    . . .

    end;procedure save (dict: in Dictionary;filename: in String) isbegin

    . . .

    end;end Dictionaries;

    Program 11.6(b) Body of the Dictionaries package in ADA (in outline).

  • 7/30/2019 Case Study ADA

    12/26

    Program 11.6(a) shows the Dictionaries package specification, whichdeclares the abstract type Dictionary together with its operations. Program11.6(b) outlines the Dictionaries package body, which defines these operations.

    Note that the package specification is prefixed by with Words;, becauseit depends on that package.Program 11.7 outlines the high-level procedures consult_user, process_document, and main. The consult_user and process_document

    procedures are nested inside the main procedure. (Instead, they could havebeen compilation units in their own right.) Note that process_documentrepeatedly calls get_word within a loop; if get_word throws end_error, thecorresponding exception handler exits the loop.Compare this ADA program with its C counterpart (Programs 11.111.4).There is no doubt that the ADA program is better-engineered in every respect. Ithas a better architecture, due to its use of abstract types. It is more robust, due toits use of exceptions. It is less concise, but far more easily maintainable.

    with Ada.Text_IO; use Ada.Text_IO;with Words; use Words;with Dictionaries; use Dictionaries;procedure main isprocedure consult_user (current_word: in out Word;main_dict, ignored: in out Dictionary) is-- Ask the user what to do with current_word, which is unknown.-- If the user chooses to acceptthe word, make it a member of main_dict.-- If the user chooses to ignore the word, make it a member of ignored.-- If the user chooses to replace the word, get the user to enter a replacementword,-- and update current_word.begin

    . . .end;procedureprocess_document (main_dict, ignored: in out Dictionary) is-- Copy all words and punctuation from the input document to the output-- document, but ask the user what to do with any words that are unknown (i.e.,-- not in main_dict or ignored).in_doc, out_doc: File_Type;current_word: Word;begin

    open(in_doc, in_file, "indoc.txt");open(out_doc, out_file, "outdoc.txt");

  • 7/30/2019 Case Study ADA

    13/26

    loop

    get_word(in_doc, out_doc, current_word);if not contains(main_dict, current_word) and thennot contains(ignored, current_word) thenconsult_user(current_word, main_dict, ignored);end if;

    put_word(out_doc, current_word);end loop;exception

    when end_error =>close(in_doc); close(out_doc);end;main_dict, ignored: Dictionary;begin

    load(main_dict, "dict.txt");clear(ignored);

    process_document(main_dict, ignored);save(main_dict, "dict.txt");end;Program 11.7 Definitions of the consult_user, process_document, and main

    procedures in ADA (in outline).

    In this chapter: We have identified the key concepts of imperative programming: variables,commands,

    procedural abstraction, and (more recently) data abstraction.

    We have studied the pragmatics of imperative programming, comparing thedisadvantagesof programming with global variables with the advantages of dataabstraction. Wehave studied the design of two major, but very different, imperative

    programminglanguages, C and ADA. We have compared two imperative implementations, in C and ADA, of asimplespellchecker.

  • 7/30/2019 Case Study ADA

    14/26

    Trng hp nghin cu: ADAADA c thit k trong nhng nm 1970 l mt bt buc c mc ch chung vngn ng lp trnh ng thi, ph hp c bit thc hinh thng quy m ln v nhng. i ng thit k ADA l ln, v nhn cu vo t mt s vn cn ln hn ca nhng ngi quan tm, nhng nhng n lc

    thit k gip Jean Ichbiah. (Qu nhiu ngn ng lp trnh chuim ni bt ca thit k ca U ban: mt s gia tng tnh nng b tch hp,c gng p ng nhu cu mu thun nhau ca tt c cc thnh vin y ban.Kim sot cng ty ca Ichbiah m bo rng ADA phn ln trnh c s phn .)

    Nh mt h qu ca cch thc m n c pht trin, ADA l mt ln nhng hp lngn ng mch lc. N h tr gn nh tt c cc khi nim m t trong cun sch ny.c bit, khng ging nh ngn ng bt buc c in nh C v PASCAL, ADAh tr d liu tru tng, tru tng chung chung, v trng hp ngoi l.ADA c m rng trong nhng nm 1990, ch yu h tr hng i tnglp trnh. Khi cn thit phn bit gia hai phin bn ca

    ngn ng, chng ti gi chng l ADA83 v ADA95, tng ng.Phn ny l tng quan v cc phn bt buc ofADA.We s chuyn sang cc

    phn hng i tng v ng thi ca ADA trong chng 12 v 13, tng ng.

    Cc gi tr v cc loiADA c mt tit mc y cc loi nguyn thy: Boolean, nhn vt, iu traloi, v cc loi s (s nguyn, du chm, v im c nh). Bt thng,ADA cho php cc lp trnh vin khai bo cc loi s ring ca h, l tt chotnh di ng.ADA c mt tit mc y ca cc loi hn hp: cc loi mng, cc loi h s,v cc loi h s phn bit i x (phn chia cng on).ADA khng h tr cc loi quy trc tip. Thay vo , cc lp trnh vin phikhai bo cc loi quy s dng con tr.ADA tun th tt vi cc loi y Nguyn tc. Hng, bin,cc thng s, v kt qu chc nng c th ca bt k loi. S bnh ng-kim trahot ng'' ='' v'' / ='', v cc hot ng chuyn nhng'': ='', c th c p dng choton hng ca bt k loi (tr khi cc lp trnh vin la chn khc bng cch tuyn bmtnhp b gii hn).ADA h tr phn nhm h thng theo ngha l tt c cc loi c th c

    phn nhm (xem Phn 8.1.1). Tuy nhin, mt subtype ADA t n khng th loi. Trong

    c bit, mt khai bo kiu ADA to ra mt loi mi v khc bit, nhng mtKhai subtype ADA ch n thun l t tn mt kiu ph ca mt loi hin c. Mt loiltng thch vi bt k kiu ph ca n.

    Loi ADA v phn nhmT nhin l mt subtype ca Integer:subtype t nhin l s nguyn phm vi 0 .. Integer'last;

    Tham s th hai cc chc nng sau y l ca kiu ph t nhin:

    nng lng chc nng (b: ni; n: t nhin) ni tr li;Trong mt cuc gi chc nng quyn lc, trnh bin dch ch n thun l kim tra m

  • 7/30/2019 Case Study ADA

    15/26

    i s th hai lloi tng thch vi t nhin (v d, kiu ca n l s nguyn hoc mt subtype caInteger).Tuy nhin, kim tra thi gian chy c th l cn thit m bo rng gi tr ca i sl trong cc

    subtype t nhin.Cui cng, hy xem xt cc th tc thch hp sau y:th tc inc (i: trong ra Integer);Trong mt cuc gi th tc inc, trnh bin dch ch n thun l kim tra kiu ca is ltng thch vi s nguyn (v d, kiu ca n l s nguyn hoc mt subtype caInteger). Khngkim tra thi gian chy l cn thit.Tit mc biu ADA bao gm h s v cng trnh xy dng mng vcuc gi chc nng. N khng bao gm cc biu thc iu kin, biu thc lp i lp li,hoc biu khi. Do cc lp trnh vin buc phi s dng chc nng cuc gi cho

    tnh ton c qu phc tp cho tit mc ny biu hin kh hn ch.iu quan trng l c th ca mt chc nng ca ADA l c php lnh, v nh vy cthcha vng, x l ngoi l, v nh vy. Tng t nh vy, tuy nhin, chc nngcc cuc gi c kh nng c tc dng ph.

    Bin, lu tr, v kim sotADA h tr ton cu, a phng, v cc bin ng. Mt bin ng kiu T lgiao mt biu hin ca hnh thc mi'' T'', hoc cch khc'' mi T '(...)''m cng khi to cc bin ng.Tit mc ca cc lnh ADA l thng thng cho mt mnh lnh hin ingn ng: mt lnh b qua, lnh chuyn nhng, cuc gi th tc, trnh tlnh, cc lnh iu kin (nu lnh v trng hp), lp i lp li lnh(Trong khi-v-lnh, v vng c bn), cc lnh khi, v exceptionhandlinglnh.Thot ADA v sp xp dy tr li cho php dng iu khin a li ra duy nht nhpcnhc lp trnh d dng nh dng iu khin duy nht-li ra duy nht nhp cnh. ADAcngh tr nhy, mc d chng khng cn thit.

    ADA l ngn ng quan trng u tin cung cp mt hnh thc an ton ca ngoi lx l. ADA83 mt ngoi l khng th thc hin mt gi tr. ADA95 mt ngoi l c ththc hin mt chui, cho php x l nhn c thm thng tin vtnh hnh bt thng i din bi cc ngoi l (nhng thng tin phi cm ha nh l mt chui trc khi ngoi l c nm ra, v gii m bi b x lsau khi n b bt).

    Rng buc v phm viMt chng trnh ADA bao gm cc n v chng trnh: cc th tc, bao b, v chung

    chungn v. Cc lp trnh vin xc nh ca cc th tc ny th c coi nh l

  • 7/30/2019 Case Study ADA

    16/26

    chng trnh chnh.Trong mt chng trnh n v hoc khi lnh chng ta khai bo bt c iu g: cc loiv

    phn nhm, hng s v bin, trng hp ngoi l, nhim v, chng trnh v cc n vthm ch khc.

    Th tc, bao b, v cc n v chung chung l cc n v chng trnh ln vthng tuyn b hoc trn ton cu hoc trong cc n v khc ca chng trnh. Mcd n l

    php l trong ADA tuyn b mt n v chng trnh bn trong mt khi bn trong, ms cho phpcc n v chng trnh truy cp vo cc bin khai bo trong khi bn ngoi, dn nkt hp cht ch.

    Tru tng v th tc

    ADA h tr c cc th tc thch hp v th tc hot ng.ADA h tr ba ch tham s, trong nhn mnh s ch o ca d liudng chy (vo v / hoc ra khi th tc) ch khng phi l thng s c bnc ch. Trong tham s: tham s chnh thc l mt hng s, v c lin kt vii s (mt gi tr hng nht). In-ra-tham s: tham s chnh thc l mt bin, v cho php c haikim tra v cp nht ca cc i s (cng l mt bin). Ngoi tham s: tham s chnh thc l mt bin, v cho php ch cp nhtca cc i s (cng l mt bin).i vi cc loi nguyn thy, ADA nhn mnh rng cc hu qu trn c thc hin

    bng cch sao chp trong,bn sao-trong-bn-out, v cc c ch sao chp ra, tng ng (mc 5.2.1).i vi cc loi tng hp, ADA cho php trnh bin dch chn trnhiu ng ny c thc hin bng cch sao chp hoc cc c ch tham kho. C chtham kho(Mc 5.2.2) gii thiu cc nguy c rng ca, nhng thng hiu qu hnsao chp c ch cho cc h s ln v mng.Th tc chc nng ANADA c trong thng s ch. V vy, mt th tc chc nngkhng th cp nht cc bin i s dng lnh, nhng iu ny thc s ch l mt navi

    c gng ngn cn tc dng ph. Thn ca hm c th cp nht cc bin ton cu,mt ngun giu v do nguy him hn cc tc dng ph.ADA h tr qu ti bi cnh ph thuc vo th tc. Ni cch khc,hai hay nhiu th tc c th chia s cng mt nh danh trong cng mt phm vich vi iu kin l chng khc nhau v thng s ca h hoc cc loi kt qu. Ngoi ra,ADAx l hot ng ca n ging ht nh chc nng: chng ti c th qu ti bt k nhiu hnh hin ti

    bng cch cung cp mt nh ngha thm. (Tuy nhin, chng ta khng th pht minh raiu hnh mik hiu.)

    Th tc ADA khng c gi tr hng u. c bit, mt P1 th tc c th khngc thng qua nh l mt tham s cho mt th tc P2. Tuy nhin, chng ta c th t

  • 7/30/2019 Case Study ADA

    17/26

    cv c bn tc dng tng t bng cch i qua mt con tr n P1 nh mt i s choP2.

    Tru tng d liuADA h tr d liu tru tng ch yu bng phng tin ca cc gi, nh chng ta thy trongPhn 6.1. Mi gi bao gm mt c im k thut v c th. Gic im k thut phc v khai bo thnh phn cng khai ca gi phn mm, v do ch nh API ca gi. C th gi phc v cung cp chi tit thc hin:nh ngha ca bt k th tc no, v t khai ca cc thnh phn t nhn.

    Nhn chung, cc thnh phn ca mt gi ADA c th l bt c iu g c th ctuyn b trong cc ngn ng: cc loi v phn nhm, hng s v bin, trng hp ngoil,th tc, n v chung chung, gi bn trong, v nh vy. Hn na, bt k tp hp con

    cacc thnh phn ny c th c cng khai. Do cc gi ADA h tr ng gi.Mt trng hp c bit quan trng l mt gi phn mm xc nh mt loi tru tng.Trong nytrng hp c im k thut gi tuyn b cc loi tru tng chnh n, v xc nhth tc cng khai hot ng trn cc loi tru tng. Tn ca cc loi tru tngl cng khai, nhng i din ca mnh l t nhn. C th gi xc nh cngth tc, v tuyn b bt k th tc t nhn (ph tr).ADA loi tru tngChng trnh 11.6 (a) cho thy cc c im k thut ca mt gi c tn T in. Nytuyn b mt loi t in tru tng, v quy nh c th th tc no s hot ng

    Nhng kiu tru tng.Chng trnh 11.6 (b) phc tho c th gi tng ng, trong xc nh tt c cc cngth tc. B qua cc chi tit ph thuc vo cc i din c la chn cho cc loi trutng(M c th l mt cy tm kim, v d).M ng dng c th s dng gi phn mm t in nh sau:s dng t in;dict: t in;current_word: Word;. . .

    ti (dict);vng lp. . .nu khng c (dict, current_word) sau . . .kt thc nu;. . .kt thc vng lp;Gi tr kiu t in c th c thao tc ch bng cch gi cc hot ng cng cngca gi in. Trnh bin dch ADA s ngn chn bt k n lc cam ng dng truy cp cc i din t in. Do , m khng cn phi da

    v k lut ca ngi lp trnh, m ng dng c th c duy trc lp ca gi.

  • 7/30/2019 Case Study ADA

    18/26

    Tt c cc loi ADA, bao gm c cc loi tru tng, theo mc nh trang bchuyn nhng ngn ng v cc hot ng kim tra bnh ng, tr cc loi c xcnh nhlimited.Assignment ca mt cu trc d liu tnh (mt trong xy dng m khng c contr)

    i hi phi sao chp tt c cc thnh phn ca n, l bn sao ng ngha. Mt khc,phn cng mt cu trc d liu ng (mt trong xy dng s dng con tr) i hisao chp cc con tr nhng khng referents ca h, l ng ngha tham kho. Khngthng nht ny to ra mt tnh th kh x khi chng ti thit k mt loi tru tng, tnhng nm loii din c n i v khng phi nh hng n hnh vi ca ccm ng dng. Ch khi chng ta tin tng rng cc loi tru tng s lun lun ci din bi mt cu trc d liu tnh chng ta nn khai bo n nh ch n gin l tnhn. Nucc loi tru tng c th hnh dung c i din bi mt cu trc d liu ng,chng ta nn khai bo n l hn ch t nhn. (V nu cc loi tru tng cn

    phn cng v / hoc cc hot ng kim tra bnh ng, chng ta nn lm cho cc gicung cpring ca mnh.)

    Ni mt gi xc nh mt loi tru tng, mt phn ca gi tinc im k thut xc nh i din cc loi tru tng ca. N s l hp l hncho i din phi c xc nh trong c th gi, cng vi khcchi tit thc hin. L do cho phi l thit k ny l ADAtrnh bin dch phi quyt nh, s dng cc c im k thut gi mt mnh, bao nhiulu trkhng gian s c chim bi mi bin ca cc loi tru tng. (Tuyn b nh vy

    bin c th c bin dch trc khi c th gi c bin dch.) y l mtv d v mt s tha hip thit k c thc y bi nhng cn nhc thc hin.Chung chung tru tng

    Nh chng ta thy ti mc 7.1.1 v 7.2.1, ADA cho php bt k gi c thc hinchung chung,v sau n c th c tham s lin quan n cc gi tr, cc bin, cc loi vi, vth tc m n ph thuc. y chng ti cung cp cho mt v d khc.

    ADA gi chung vi cc loi v chc nng cc thng s

    Xem xt cc c im k thut sau gi chung chung:chungloi hng l t nhn;loi chnh l t nhn;vi chc nng row_key (r: Row) tr li chnh;Bn giloi bng c gii hn t nhn;- Mt gi tr bng c cha mt s lng hng, chu s rng buc- M khng c hai hng c cng mt phm.table_error ngoi l;th tc r rng (t: ra bng);

    - Thc hin bng t khng cha hng.thm th tc (t: trong ra Bng; r: trong Row);

  • 7/30/2019 Case Study ADA

    19/26

    - Thm hng r bn t. Nm table_error nu t c cha- Mt hng vi cng mt phm vi r.chc nng ly (t: Bng; l: Key) tr li hng;- Tr li hng trong bng t m quan trng l k. Nm table_error nu- T khng cha hng nh vy.

    Ring tcng sut: khng i tch cc: =. . .;loi Bnghikch thc: s nguyn phm vi 0 .. nng lc;hng: mng (1 .. nng lc) ca hng;kt thc h s;Bn kt thc;Gi chung c tham s ha i vi cc loi hng, cc loi Key, vchc nng row_key.C th gi s userow_keyto thc hin cc hot ng addandretrieve:

    gi Bn c thth tc r rng (t: ra Bng) l

    bt ut.size: = 0;kt thc;thm th tc (t: trong ra Bng; r: trong Row) lk: Key: = row_key (r);

    bt ucho ti trong 1 .. t.size vng lpnu row_key (t.rows (i)) = k thtng table_error;kt thc nu;kt thc vng lp;t.size: = t.size 1;t.rows (t.size): = r;kt thc;chc nng ly (t: Bng; l: Key) tr li Row c

    bt ucho ti trong 1 .. t.size vng lpnu row_key (t.rows (i)) = k thtr t.rows (i);

    kt thc nu;kt thc vng lp;tng table_error;kt thc;Bn kt thc;K t khi c hai tham s kiu Row v chnh c khai bo l t nhn, chng c bomc trang b vi nhim v v hot ng bnh ng-kim tra.M ng dng c th s dng gi chung ny nh sau:subtype SHORT_NAME l String (1 .. 6);subtype PHONE_NUMBER l String (1 .. 12);

    loi Phone_Book_Entry lghi

  • 7/30/2019 Case Study ADA

    20/26

    tn: SHORT_NAME; s: PHONE_NUMBER;kt thc h s;chc nng entry_name (e: Phone_Book_Entry)SHORT_NAME tr li l

    bt u

    tr e.name;kt thc;Phone_Books gi l bng mi (Phone_Book_Entry, SHORT_NAME, entry_name);s dng Phone_Books;

    phone_book: Bng;. . .thm (phone_book, "David", "61733652378");Instantiation to ra mt gi phn mm bnh thng bng cch thay th choPhone_Book_EntryHng, SHORT_NAME cho Key, v entry_name cho row_key. Cc gi phn mm c

    to ra ltn Phone_Books.Cng nh mt gi phn mm, chng ta thng c th lm cho mt th tc thng thngchung chung. Mtth tc chung cho chng ta mt thm mc tru tng.

    ADA th tc chung vi mt tham s kiuSau y tuyn b mt th tc trao i, tham s lin quan n cc loi hng vica cc gi tr c hon i:chungloi hng l t nhn;th tc hon i (x, y: trong ra mc);V y l c th tc tng ng:th tc hon i (x, y: trong ra mc) lz: khng i Item: = x;

    bt ux: = y, y = z;kt thc;Chng ti khi to th tc chung chung ny bng cch cung cp mt kiu i s clin kt vi

    tham s kiu Item:swap_characters th tc hon i mi (nhn vt);swap_integers th tc hon i mi (Integer);Mi instantiation ca trao i to ra mt th tc thng thng (khng chung chung).Th haiinstantiation to ra mt th tc bnh thng tn l swap_integers, vi haitrong-ra-cc thng s ca kiu Integer. Cc th tc c to ra c th c gi trongtheo cch thng thng:a: array (...) ca s nguyn;. . .swap_integers (a (i), mt (j));

  • 7/30/2019 Case Study ADA

    21/26

    Lu rng mt th tc chung ADA u tin phi c khi to to ramt th tc thng thng, trc khi sau ny c th c gi. ADA khng cho phpinstantiation v cuc gi c kt hp. (Nhng xem bi tp 11.5.)

    Bin dch ring bitBin dch ring bit tng t nh trnh bin dch c lp (xem phn 11.3.5),nhng vi s khc bit quan trng l kim tra kiu trn n v bin dchkhng b nh hng.Chng ta thy mt gi ADA c khai bo trong hai phn: mt gic im k thut v mt c th gi. Tng t nh vy, mt th tc c th c tuyn

    b trong haiphn: mt c im k thut th tc (tiu ca n) v mt c th th tc. Trong mitrng hp,gi hoc th tc c mt c im k thut ca giao din ca n, v mt c th chachi tit thc hin.

    Mt n v bin dch ADA c th l mt c im k thut quy trnh n l, th tcc th, c im k thut gi, hoc c th gi. Mi n v bin son phi t tn(Trong mt vi mnh ) mi th tc bin son ring hoc gi mn ph thuc.Mt c im k thut quy trnh hoc gi phi c bin dch trc tng ngth tc hoc c th gi, v trc bt c n v bin dch m

    ph thuc vo n. Trnh bin dch ADA m bo rng n v bin dch c bin dch(V bin dch li) theo mt th t chnh xc. N cng thc hin kim tra kiu y trnn v bin dch, bi th on n gin ca vic ghi nh ni dung ca mith tc v c im k thut gi.ADA bin dch ring bitHy xem xt mt chng trnh ng dng s dng cc gi t in ca Chng trnh11.6.Gi s c ba n v bin dch: cc c im k thut gi, gic th, v cc m ng dng. Cc m ng dng c th trng nh th ny:vi T in, s dng t in;th tc chnh ldict: t in;

    bt uti (dict);

    . . .kt thc;Chng ti bin son cc c im k thut gi T in u tin, theo sau (theo th t)

    bi T in c th gi v m ng dng.Nu sau ny chng ta sa i cc c im k thut gi (mt s thay i API), sau chng ti

    phi bin dch li khng ch l c im k thut gi m cn l c th gi vm ng dng.

    Nu thay vo chng ta sa i ch c th gi (mt s thay i thc hin), sau chng ta cn

    bin dch li ch c c th gi. Khng c t gi cng khng phi ng dng

    ang b nh hng.Ch rng chng ta c li ch ny ch bi v cc gi c chia thnh c im k

  • 7/30/2019 Case Study ADA

    22/26

    thutv c th. Nu ton b gi l mt n v bin dch duy nht, sau ngay c tr v thnhninthay i thc hin s buc ton b gi v cc m ng dng c bin dch li.

    Th vin giNgn ng lp trnh ADA i km vi mt th vin gi khim tn. Nyh tr x l nhn vt, x l chui, ngy thng v thi gian, s (bao gm c

    phc tp) chc nng, u vo / u ra, deallocation lu tr, lp trnh mc thp,v nh vy.Th vin gi ADA c bin dch trc. Bin son cc chng trnh ng dngn v phi c lin kt vi cc gi th vin m chng ph thuc.

    Mt kim tra chnh t n gin kt lun tng quan ny ca chng trnh bt buc trong ADA, chng ta hy xem xtmt

    Thc hin ADA ca kim tra chnh t n gin quy nh ti mc 11.2.1. Cckin trc chng trnh c th hin trong hnh 11.2. Chng trnh bao gm mt sn v bin son, v c trnh by trong chng trnh 11,5-11,7.Chng trnh 11.5 (a) cho thy cc c im k thut gi t, m tuyn btru tng loi Li cng vi hot ng ca n. Chng trnh 11.5 (b) hng dnT gi c th, trong xc nh cc hot ng ny. Lu rng cc gic im k thut c bt u bng'' vi Ada.Text_IO;'', bi v n ph thuc vo gi th vin

    vi Ada.Text_IO, s dng Ada.Text_IO;gi t lloi Word l t nhn;- Mi gi tr Word l mt t duy nht.th tc get_word (in_doc, out_doc: trong ra FILE_TYPE;wd: ra Word);- c t tip theo t in_doc vo wd, sao chp bt k du chm cu trc- out_doc. Tng end_error nu khng c t tip theo c c.

    th tc put_word (out_doc: trong ra FILE_TYPE;wd: trong Word);- Vit wd out_doc.ring tloi Word. . .; - i dincui t;Chng trnh 11.5 (a) c im k thut ca gi t trong ADA (trong cng).

    gi c th l t

    . . . - Th tc ph trth tc get_word (in_doc, out_doc: trong ra FILE_TYPE;

  • 7/30/2019 Case Study ADA

    23/26

    wd: ra Word) lbt u. . .kt thc;th tc put_word (out_doc: trong ra FILE_TYPE;

    wd: trong Word) lbt u. . .kt thc;cui t;Chng trnh 11.5 (b) C th ca gi t trong ADA (trong cng).

    vi Words, s dng t;

    T in giloi t in c gii hn t nhn;- Mi gi tr t in l mt tp cc t.th tc r rng (dict: ra khi t in);- Hy dict trng.thm th tc (dict: trong t in ra; wd: trong Word);- Hy wd thnh vin ca dict.chc nng cha (dict: t in; wd: Word)tr Boolean;- Quay tr li ng nu v ch nu wd l thnh vin ca dict.th tc ti (dict: ra khi t in;tn tp tin: trong String);- Ti dict t tn tp tin.cu th tc (dict: trong t in;tn tp tin: trong String);- Lu dict vo tn tp tin.ring tloi t in l. . .; - i dinT in kt thc;Chng trnh 11.6 (a) c im k thut ca gi T in trong ADA (trong cng).

    gi T in c th. . . - Th tc ph trth tc r rng (dict: ra khi t in) l

    bt u. . .kt thc;thm th tc (dict: trong t in ra; wd: trong Word) l

    bt u. . .

    kt thc;chc nng cha (dict: t in; wd: Word)

  • 7/30/2019 Case Study ADA

    24/26

    Boolean tr li lbt u. . .kt thc;th tc ti (dict: ra khi t in;

    tn tp tin: trong String) lbt u. . .kt thc;cu th tc (dict: trong t in;tn tp tin: trong String) l

    bt u. . .kt thc;T in kt thc;Chng trnh 11.6 (b) C th ca gi T in trong ADA (trong cng).

    Chng trnh 11.6 (a) cho thy cc c im k thut gi T in, mtuyn b kiu tru tng t in cng vi hot ng ca n. Chng trnh11.6 (b) a ra cc in gi c th, trong xc nh cc hot ng ny.Lu rng cc c im k thut gi c bt u bng'' vi Words,'', bi vn ph thuc vo gi.Chng trnh 11,7 phc tho cc th tc consult_user cp cao, process_ti liu, v chnh. Cc consult_user v process_documentth tc c lng vo bn trong th tc chnh. (Thay vo , h c th cn v bin dch c trong quyn ring ca h.) Lu rng process_documentnhiu ln gi get_word trong mt vng lp, nu get_word nm end_error, cctng ng vi ngoi l x l thot ra khi vng lp.So snh cc chng trnh ADA ny vi ngi ng cp C ca n (Chng trnh 11,1-11,4).Khng c nghi ng rng chng trnh ADA l tt hn-thit k trong mi phng din.

    Nc kin trc tt hn, do vic s dng cc loi tru tng. N l mnh m hn, dovic s dng cc trng hp ngoi l. l cha chnh xc, nhng d dng hn nhiuduy tr.

    vi Ada.Text_IO, s dng Ada.Text_IO;vi Words, s dng t;vi T in, s dng t in;th tc chnh lth tc consult_user (current_word: trong ra Word;main_dict, b qua: trong t in ra) l- Yu cu ngi s dng phi lm g vi current_word, l khng r.

    - Nu ngi dng chn chp nhn li, lm cho n mt thnh vin ca main_dict.- Nu ngi dng chn b qua cc t, lm cho n mt thnh vin ca b qua.

  • 7/30/2019 Case Study ADA

    25/26

    - Nu ngi dng chn thay th ch, c c ngi dng nhp vo mt t thay th,- V cp nht current_word.

    bt u. . .kt thc;

    th tc process_document (main_dict, b qua: trong t in ra) l- Sao chp tt c cc t v du chm cu t ti liu u vo n u ra- Ti liu, nhng yu cu ngi dng phi lm g vi bt k t no cha c bit (vd,- Khng trong main_dict hoc b qua).in_doc, out_doc: FILE_TYPE;current_word: Word;

    bt um (in_doc, in_file, "indoc.txt");m (out_doc, out_file, "outdoc.txt");

    vng lpget_word (in_doc, out_doc, current_word);nu khng c (main_dict, current_word) v sau khng c (b qua, current_word) sau consult_user (current_word, main_dict, b qua);kt thc nu;

    put_word (out_doc, current_word);kt thc vng lp;ngoi lkhi end_error =>ng (in_doc); gn (out_doc);kt thc;main_dict, b qua: t in;

    bt uti (main_dict, "dict.txt");r rng (b qua);

    process_document (main_dict, b qua);tit kim (main_dict, "dict.txt");kt thc;Chng trnh 11,7 nh ngha ca consult_user, process_document, v chnhth tc trong ADA (trong cng).

    Trong chng ny: Chng ti xc nh c cc khi nim c bn ca lp trnh bt buc: bin, lnh,tru tng v th tc, v (gn y) d liu tru tng.

    Chng ti nghin cu ng dng ca lp trnh bt buc, so snh bt lilp trnh vi cc bin ton cu vi nhng li th ca d liutru tng. Wehave nghin cu thit k ca hai ln, nhng rt khc nhau, lp trnh bt bucngn ng, C v ADA.

    Chng ti so snh hai trin khai bt buc, trong C v ADA, mt n ginkim tra chnh t.

  • 7/30/2019 Case Study ADA

    26/26