A CO:?FUTEfl SYSTEM FOR CHECKING PROOFS Scott D. Johnson Fh.D. Thesis January 1981 TR 80--H444 Department of C?rnputer Scienc? Cornell University Ithaca, New Yor'?, 14853 A CO?PUTER SYST? FOR C?iICLl?C PROOFS A Thenis ?raaanted to tbe Faculty of tbe Graduate School of Cornell t'niveraity in Partial Fulfillment for tbe Degree of Doctor of Philos?phy by Scott David Johnaon January 1981 BIOCWHIC&L SXETCH Scott David Jobnson Yes born on October 16. 19S3 in Joliet. Illinois. I. ?raduated from Joliet Township High School. West Campus. in 1971. Is received the Bachelor of Science degree in computer science fro: the 11Ii- nois Institute of Technology in 1975. graduating with high honora. In 1919 he received the degree of Heater of Science in conputer science from Cor- nell University. During the 1979-80 academic year. he van an instru?or at Cornell University. lie has accepted a position with the the Western Development Laboratories of the Ford Aerospace Corporation. ACVll(AiIy.I?.'Sl?NTI o+And I want to thank tIe Ac?dtmy. my family. Harry who fed my dog during rthearssls ...? I once thought the long-winded speeches those peo- plo g?ve were rath-r contrived. But faced with the task of writing this section. 1 think I know just how they feel. riret of all. I must thank my adviaor Bob Constable. If it were not for all the csrr?ts?and sticks (muntly carruts) he has used on so ovor the past few years. this thesis would have never been completed. Bob has a wonderful ?enae of optimism. and together we have embarked on projects I would have never attem?ted on my own. I am also ceeply grateful to Dean Krafft and Dan Ziatin. The algo- rit??s I prJ in CI'at&ra ?. 6. ad 7 w.r., d?'v?.l?pt.J in collaboratio?? with Dean &?d Dan. each of whom worked on the implementation of the V-code Inter?rcter. They careully read drafts of the thesis and found countless errors. I want to especially thank Dean for performing the Herculean task of wading through an exceedingly rough draft of Chapter 6. I would aleo like to aention the other peuplc who have worked on ths PL?CT project. Mi? O'Dnnnell was the principle designer of PL/CVl. and gave hel#'ful aJvice during the design of PL/CV2. Carl Hauser helped writs the canual for PL/CVI. Mike O?Donnell and Tat-Hung Chan developed the arithaetic ?5C'Kage used in ?L/CV2; Carl Eichenlaub later added some exten- eio:s this package. Ryan Stansifer is currently translating the arith- metic package and V-code Interpreter into the C programming language so that it can be used by AVID. an interactive version of pL?CV being uvelope? Dy Dean Krar.ft. While I was?working on the pL?CV project I was supported by the --H iii --H Natlcn.,I F.cirnce F Istien. t??ant ?CS--HJ6--Hl:..")? gt?t th p,?jct atsated. and grant NCS-78-OO953 helped get it finished. Uhila sup?orted by grant S?D-79-l8966. 1 taueht am experi?ental course tisat used ?LICY. Th?re is mo way I cam think back through all the seminars amd dis cussions im which I participated and remember everyone w.?o gave me ideas that evemtually made it into my theais. But I do rec?ll fruitful di?cua- sioms with Barry Bakalor. Alan Demers. Corky Csrtwri&ht. Carl Eicbsnlaub. Carl lisuser. Ralph Juhnsom. auJ `;ary Levin. This document was pr?pared on the UNIX system at Cornell University. I want to thank everyone at Cornell responsible for obtaining and moin- taining that computer system. especially Alan numers. I si?ply c3nnot conceive of writing this thesis without the aid of a word procc?sing aye- tem. Because I didn't quite finish my thesis on schedule. my stay in Ithaca was a little longer than I expected it to be. I want to express my appreciation to everyone who gave me support durin? those l?st two wonthe of fren?y. I would like to thank Lynn Xivell for giving ma a floor to sleep on. ?sula Zebrowski for helping me with typing. and ?ean Krafft for helping me produce the final version. 1 am especially ?rateful to my new employers at Ford Aerospace showing patience and understaiding during this period. It was inevitable by Lhe Law of the InlaLe Perversity of 1nanira?e Objects. that during the final week the disk drie on which my thesis was stored would break. I am indebted to Alan Demers. Ann Kratxer. `Lana floehm. and Deaa Krafft. who. armed witb oscilloscopes and logic probes. valiantly rescued Chapter 4 from limbo. And finally. I must mention Steve Jackson and Howard Thompson. - iv - Without the materials they provide?. ny ?tay in Ithaca `aould have been =ucb shorter but not nearly so enjoyable. wL'? OF CONTIDITS 1. IntroductionI 1.1 Tn. PL'Cv ProjectI 1.2 The PL?CS Progrnaing Language3 1.3 An Overvieii of the Thesis13 1.4 A Few Words about Notation16 2. Representations for Bound Variables20 2.1 The Problem of Capture20 2.2 Representations of Parse Graphs24 2.3 Creating Quantifier Count Representations32 2.4 Representations for Second-Order Logic38 3. The Predicate Calculus47 3.1 Introduction47 3.2 Natural Deduction47 3.3 APL?CV50 3.4. Converting Natural Deduction proofs to APL?CV57 3.5 Converting APL/CV proofs to Natural Deduction62 3.6 PLICY versus APLICY68 3.7 Nacros71 3.8 Proof Blocks14 3.9 Qualifiers and Scope Rules77 3.10 SONE Elimination80 3.11 Arithrn?tic l?f?rtn?ca8) 3.12 V-code Generation83 3.13 Autuuatic Xulcs end AI'brt?letiunsb6 3.14 S?4:g.'stions for l???rnv nt92 4. Progr?s94 4.1 Proofs of Prorsiss94 4.2 Shie1din?'99 4.3 Accc?aibi1ity101 4.4 Checking Progrin Proof106 4.5 The NEW instruction107 4.6 T?plates108 4.7 Dosain Checking110 4? The Assig?ent Stateaent116 4.9 Array Assigosent120 ?.10 Procedure Definitions and Calls130 4.11 Aliasing138 4.12 Functions and Function Calls142 4.13 A Theoren about Accessibility146 4.14 Conditional StatanentsIsi 4.15 %?lLr Loops156 ?.16 UhTlL loops161 4.17 Indexed Loops165 4.18 Jwnp Stat?ents169 4.19 The Plethora Proble?i183 4.20 ?nibu? Stat?ents186 3. A Deciajun Proced?re for Tran?formationa196 5.1 Transformations and Replacement Systems196 5.2 The rtplacement systen T??S201 5.3 Tte Confluence of Replacement System TRANS207 5.4 A Nwaber of Cases216 5.5 The Computation of Normal Forms219 - vLl 5.6 The Tfansforeation Axicina225 6. A Decision Procedure for Lhe Theory of Equality236 6.1 Introjuction36 6.2 A Yo?jel OttiniLion of LI? Prob1?ia23? 6.3 An Overview of AlRoriLhn Eq239 6.4 The Details of Algorithe Eq243 6.5 An Overview of tbe Correctneaa Proof 6.6 Some Simple Inveriants end an EaMy Theorem 6.7 Some Lemmes About Relatiora253 6.8 Definitions254 6.9 Invariante257 6.10 Critical Region I257 6.11 The Correctneas of Eqlnsert263 6.12 Critical Region II263 6.13 Critical Region III269 6.14 The Correctneee of EqQu?ry272 6.15 The Running Time of Algorithm Eq273 7. The V-code Interpreter271 7.1 V-code Instructions277 7.2 The PROCLAIN end REQUIRE instructions278 7.3 trausforeations293 7.4 The NEW inatruction300 7.5 The OPEN. CLOSE. and CLOSE-NEW Inatructions308 7.6 The coat of OPEN. CLOSE and CLOSE-NEW Instructions315 S. Soee linel Remarks318 8.1 A Sumeary of the Nejor Results318 8.2 The Utility of PL?CV320 --H viii --H 8.3 Tbe4?zL Step323 2efercnces 328 CHAPTEl I lNThOlUaION 1.1 zha1Ws1? In 1975. a project wee begun at Cornell Umivereity to produce a pro--H gramming logic in which formal proofs of programs could be written and nechsnicsl)y checked. The result of this project is the programmirg logic PL?CY; this thesis concerns the computer system used to check proofs writ--H ten in PL?CV. Actually. there have been two proof checkers written for FlJCV. Tne PL?CV1 Proof Checker (22). compitted in 1976. provided no autonatic sasis- tance whatsoever. The purpose this first Veraion was to get some esperi- ence with formal proofs spelled out in complete detail. Proofs written in PL/CVl are rather unwieldy. However. the valuable experience gained with PLICYl was used to guide the design of the PLICV2 language and Proof Checker. the subject of this thesis. A third version of PL,CV is currently being designed by Constable and Zlatin (23). Im this thesis. the name "PLICY" will ho used to refer to PLICV2. The usual approach to program verification is typified by the Stan- ford Pascal Verifier (?). From a program annotated with a specification and loop invarianta a collection of formulas called verification condi- tions are generated. The verification conditions bave the property that they are valid if and only if the program is correct. Typically the verifi?ation conditions are large and messy. Before they are presented to the user. they are processed hy a program called a simplifjer. The simplifier is an automatic theoren prover that perforna transformations on the verific?tion conditions that produce equivalent but --H2- simpler for.ulas. Any verification conditions that cannot be simplifjed to etruem are presented to the user. To prove his program. the user must prove these formulas. either informally or with some automated assistance. If the formulas output by the vurifjer are not valid. there is an error in the program. A problem with this approach to of verification is thst the proersa- nin? lot-ic is buried within tIe verification condition gencrator. As a result. the program and its proof become uncoupled. A user can understand how his program works but not unde?stand where a particular verification condition he must prove has come from. The PL/CJ ayste? does not have this problem. The programming logic is explicit. end the program and its proof are integrated into a single object. The logic is sirple enough that it has been used in undergraduate com?uter science courses. The PL?Cv system does not contain an autossetic theoren prover; it is not a SySten designed to automatically construct proofa. Instead. an atteopt was ?ade to design the PL?cv logic so that a rrcgra:mer?s intuition about w1y his progrem workn could easily be expressed. The programmer. not the o+?erification system. produces the proof. In PL?cv. the role of the simplifier is fulfilled by abbreviation rules that allows parts or the formal proof to omitted in well-defined ways. flecause a thecrem prover is not required. it should be possible to check pL,CV proofs efficiently. The original goal was to make the Proof Checker as efficient as an optimizing compiler. Although the sigorithus used in the Proof Check?r. which are presented in this thesis. are all fairly efficient. the implemented system uses more time and memory than 1 would prefer. it is not clear whether I have simply underestimated the .3--H sagaitude of the probles or the inefficiencies are due to the overhead incurred with the PL?I system with which the Proof Checker was inpie- mented. As of this writing. the V-code Interpreter (which is the bottleneck in the system) is being tranalated to the C programming language so that it can be run on a VAX computer. the r?u'.ts ought to be interesting. 1.2 ? nJ? P?n.ra--Hmine lan.uag? the PL?CV project was ne?er intended to be a projec? in progranaing language design. Therefore an existjn? progra?ming language had to be chosen on which to base the verification system. It seened natural to bane the system on PL?C. a dinloct of PJ.?I ucd in most of the corputer science courses st Cornell. Basing the system on a PL?I dialect made it essier to use PL?CV for teaching at Cornell. Of course. a progranning logic based on full pL?C. ? large subset of FL/I. was out of the qu?stion. Instead. PL/CV is based on PL,CS. a fldisciplineda subae ?f FL/I that was designed by Richard Conway. with the help of various other meab?rs of the Computer Science Department at Cornell. The Pt/CS language was sn stte?pt to delete most of the notorious features of FL/I. leaving a subset with clean semantics. acceptable for teaching structured ?r0gt5mmin?. Con?ay and Constable (24) discuss the factors that influenced the d?aign of PL/CS. The PL/CV logic can be vit?ed as providing axiomatic semantics for PL/CS; for the logic to be correct. these semantics must match the offi- cial definition of PL?CS. Unfortunately. the 1official definition of PL/CS" is spread over three document.. PL/CS is defined by a Cornell technical report (11). in terms of how it differs from PL/C. rL?C. in turn. is defined (72) in terms of how it differs from PL/I-F. And PL'i-? -4- is defined by an IBM ?ocumen: (43). The situtation is not Ca bad as it sp:esrs. The ?L/Cs lansuase is si:ple enoush that its semantics are for the moe part obvious to anyone acquainted with an ALCOL-like language. When it is necessary to resolve a question about a fine point. recourse to the definition of FL/I-F is usu- ally ntcessary. The ret cf this section is an overview of the PL/CS language as defined by ?ishop and Conway (111. The diff?rences between FL/Ch' and IL/CY. and the reasons for those differences. will be noted. The FL/CS lan?usge contains the following data types: integers. floating point nunbers. c??3racter strings. Booleans. and arrays thereof. To :aintflin compltibility with FL/I. short names were chosen for tho data types that would be interpreted in a reasonable fashion by the rules for default attributes in PL/I. For example. the name FIXED is used for integers. because FL/I interprets: DECLARE J F?ED; as: DECLARE J DECIMAL FIXEi)t (1.1) One might suggest the name DECIMAL as being ?lightly more suggestive of the concept of integer. And while FL/I will interpret: DECLARE 3 DECLMAL; a. tie jn?1atsti?n (1.1). it 1nts?:rstsl DLCLA?L X 1)EC1?ALt sal lOOTS PROCEDmLE(X) g?TtmNs(FLuAT); DECLARE X FLOAT; ASSUME X >-- 0; ATTATh ROOT(X)sROOT(x) I; DECLARE (LO. HI. MID) FLOAT; LO 0; HI DO wHILE(LO HI); ?* LO <-- ROOT(X) <-- `il */ MiD (LO + HI) ? 2; ?? test if MID <-- ?O0T(X) a? IF (MW?LiD <-- X) ThEN LO a- MD; ELSE HI MW; END; XTuRN(LO); END ROOT; lisure 1.1 A program that computes square roots using bisection DECLARE X DECIlAL FLOAT; The first letter of the identificr name is used to deter.ina a default type. (This convention is a holdover from FOITILAN C7).) The PL?CS name. for integer. floating point. floolean. sod character strings are FIXED. FLOAT. BIT. and CHAaACThR. respectively. The types FLOAT and CHARACTER were omitted from PLICY because it is difficul? to give axioms that can be used to reason about then. When working with programs that use floating point sritbmetic. one typically proves the correctoess of the program assuming real arithzetic is being used. and the? (when possible) proves soce bound on roundoff error.. This method allows one to provo that the pro?rsss yields results that are close to the actual solution. which is as strong a statement as can be expected. This method is far less acceptable when proving. for example. that the probram halts. As an exau'?le. conslJ??r the pro?ram in Fig?'r. I.!. If rael arl1hm?tlc is nsea. th? (r'grsm n.'v?r halis. ?.t ?iven (Ins Ina --H6- roant agjthmetjc as tt in im?l.mnstad on m?at snachisna the ?.u?ram will always halt ?hen X ?a 0 and will return a value very close to the square rcot of X. But to prove that the ?rogras halts. it is necessary to know some intimate details concerning the syste. of floating point arithmetic used by the machine on which it is to be run. BoIm ?421 has investigaged the problem of formally reasoning about programs that use floating point arithmetic. gessoning about character strings ought to be a more tractable prob- lam. Injeed. the charecter strings of SNOBOL4 (?8J. for example. have a rsaaonabla axIomatixation f21). But PL?I strings do not obey simple pro- parties such as: z 5 y i?pliee (x II a) a (y II a) where II dentes concatenation. There are two problems with PL?i atringas (I) There is a nasioum length asaoci?ted with each string variable. if a lo??er string is assigned to the variable. it is truncated. (2) When two strings are heir4 compared. trailing blanks are ignored. A reasonable vay of dealing with the first problem would be to add the restriction that strings can only be assigned to variables large enough to hold tr.em. TI,is restriction would be enforced in Lbe way that array sunscripta are required to be in bounds. in a situation in which the pro- granner desired the truncation. he be required to explicitly perform the truncation with the aubatring function. The second problem could be solved by considering a string com- parison of the form x ? v appearing in the programming language to be so- called syntactic sugar for: sTulr(x) p aTiir(v) whore STRIP(x) is define to be X with any trailins blanks stripped off. flw following programming conetructs are included in rL?cS: declarations. assignment statemt'nts. procedure end fuactiom definitions and calls. the conditionaL statements IF and SILECT. WlllL2 loops. UtTIL Loops. indexed loops. loop exits. the RETURN statement. the COTO state- lent. and some simple input and output statements. The SEI?ECT. LEAV and UNTIL statements do not appear in PLIC. These statements were included in PL?CS after they were included in Release 3 of lii?". ?L?I-X L4?). Input and output statem?nts w?re omitted fr?m Pi?CV. trum a techni- cal standpoint. they are no more difficult than array5. However. to include them. it would be nccesaary to have a uny of refurring to the input and output of thc pro?ram in (hn assertiun l?n????c. Thtre Is no block structure in PL?CS. All variables and parameters must be declared at the be?inning of each ruutine. and procedure and func- tions detinitions cannot be nested. The PL?CS coupiler c'.?ecka that v?r- ebbs and parameters declared in a routine with the REJi)ONtlr attribute are not modified by that routine. Variables declared with the EXTSRNAL attri- bute are global to every routine in the program. All other variable. are Local. and are reallocated each time the routine is entered. FL?CS also allows variables to be declared STATIC. A static variable is allocated in the same manner as an external variable. The diffetence the two kinds of variables is if the same identifier is declared to be STATIC in two different routines. two different variables are 1located. Static variables are used by a routine to keep its own private history con- cerning calls to that routine. To prove a program that uses static vari- ables. assertions about the vaLues of the static variables wouLd have to be -8- written in the calling routine. Since the calling routine aust have a ne:e for these variables. he simplest solution is to omit static vari- ables from PL?CV. and use external variables instead. It is `isusily poor programming practice to use a construct that has teen excised from a language to rnake program verification easier. Static variables appear to be an exception to this rule. When one is resding a pro?ran tnat contains a static varisble. one knows that the variable will not be changed between calls to the routine. Wl?n the static variable is replaced by an external variable. this information is lost. The reader Oust now inspect all the other routines in the program to convince himself that the variable is left unchanged. The coroutine construct provides the same localizing function as static variables. but in a more general fssl?ion. For example. instead of writir.g a random nu?ber generator that maintains a state in static vari- able. it can be written as a coroutine. The coroutine is written as a loop that outputs a series of random numbers. each call to the routine causes anotbtr iteration of the loop to be perfor?ed and the next number in the sequence to be output. Clarke (15) has inveetigated the problem of prov- ing programs that use coroutines. In PL?C the distinction between between procedures and functions is semewbat nebulous. The usual practice among PLIC programmers is to supply a RETURNS option. which indicates the type of the value to be returned. on procedures if and only if the procedure is expected to return a value. Howcvt.r. if no RLThRNS options je present. a default one is supplied; the default type depends on the first letter of the procedure name. It is the re?ponsibility of the programmer to ensure that if a routine is called vith th CAll, .r?te??nt it r?? a a v?lne. end i? the rontine 1. eell?d --HI EITHER: pROCEDlJRE(X); DECLARE X FIXED; IF Xl ThEN RETURN(l.O): ELSE RETURN: END EIThER: BObi: FROCEDURE; DECLARE Y FLOAT; Y :--H--H E1???LR(l); CALL LLTIILR(2); Pigure 1.2 A rout?ne that can be callcd as either a?procedure or functioc as a function it does not. (There is no notion 0 voiding. as in ALCDL 68 (70).) The program in Figure 1.2. for example, is perfectly legal in PL?C. The situation has been rectif jed in PL?CS. Routines are classified as procedures or functions on the basis of whether or not they are defined with a RETURNS options. Procedures are called using the CALL statenent. and functions are called from within expressione. Also. wten a routine is called. the types of the formal and actual parameters must match exactly so that no data conversion is necessary. Functions are not allowed to have aide effects. All function para? eters implicitly have the READOILY attribute? as do external vaNiables declared in a function. Input and output statemcnts may not be used in functlontt. In PLICS. functions are nut allowed to call proctdure&. This restriction has been relaxed in FL/CV: a function cannot initiate a sequence of procedure calls that can ultimately lead to the modificstioa of a function parameter or cxttrnal variable. or to the execution of an input or output stateaent. (The latter condition is trivial to enforce. because there are no input or output stater.cnts in PL?Cy.) Th ?ynt Ax for tt? r?.t of I r,,?r?'e i?s (.,,?.f Pl.,cg AT - 10 - V :-- I; A :: C; A1 A2; A(E1. E1n? :: En.i; CALL I(E1. 12. ... 1n?.o+ lETUEN; REThENCE); L: DO WNILE(B); END L; L.- DO UNTlL(fl); END L; Ls DO J : 11 TO 12 fly END L; LEAVE L; COTO L; IF (b) TIlEN DO; END; ELSE DO; END; L: SELECT; WHEN DO; END; WHEN (B2) DO; END; WHEN (Bn) DO; END; OThERWISE DO; END; END L; Tigure 1.3 PL?CS proaran..iog constructs ahavn in Fi&ure 1.3. In the figure. V stands for a scalar variable. A arands for an array variable. C stands for a constant. 1 standa for an expression. fi staods for a floolean expression. 3 atands for a scalar FIrED variable. and L atands for a statement label. Although the aymbol ia uaed for aasignment i? ?L?CS and PL?CV. the symbol :- will be consistently used to denote asaisnient in this thesia. for reasona explained in ascrion --H II 4.2. The labels required in PL?CS after END and before DO and SELECT and the parenthesia required in the IF and SELECT statements are opt?onal in PL?CV. The ?ETUXN sLatement is used to exit a procedure; jtflTUg?() is?used La exit a function and pasa the value E back to the calling program. Con--H trol is not allowed to flow "off the end" of a routine. In PLICS. this restriction is enforced by requiring every routine to end with an explicit METURN statement. even if that statement can never be executed. In PIdCV. the user must prove that control never flows off the end of a routine. For example. a routine in which the leat atatement is an IF atatement whose ThEN and ELSE clauses both end with a RETUL? statenent is allowed in PL?CV but not PLICS. The assignment statement evaluates the the expression on the right. and assigns that value to the variable on the left. The statement A : C sets every element of the array A to C. Although PL?CS allows type conversion on assignment. in PL?CV no type conversion of any kind is allowed. Because the only simple types in PL/C? are FIXEL) and BIT. this additional restriction is not very harsh. The CALL statement is used to invoke a procedure. In PL?CS. ar&u- ments are not allowed to be readonly variables. This restriction has been relaxed in PL?CV; readonly variables may be passed to procedures if the corresponding formal parameter is readonly. The CALL statement has also been restricted in PL?CV so that alissing cannot be introduced. For exam- ple. the procedure call: CALL P(X x); is not aLlowed unless both for,mal parameters of P are IWONLY. Aliasing is discussed more fully in section 4.11. -:2--H To execute a S?LEtT statement. the floolean e:pressions ?l? ?2 are evaluated until one is found to be true or this list is exhausted. Zf one of the Boolean expressions is found to be true. the corresponding WHEN clause is executed. If none of the Boolean expressions are true. the 0Th- ERWISE clause is executed. The IF statement Is equivalent to a SEJ.ECT statenent with one WH?? clause. The WIjILE and UNTIL loops execute their bodies until the Boolean expression evaluates to false or true. respectively. In the WHILE loop. a teat ia made to see if the execution of the loop is complete before the loop body is executed the tirat time. This initial test is omitted in an fl?TIL loop; its body is guaranteed to be executed at leest once. When an indexed loop is executed. the index variable J is initialixed to ?l Alternately. the loop body is executad and the index variable is incremented by E3, until the index variable passes E2 (The semantics of the indexed loop are described more precisely in section 4.17.) In PL/CS. the the variables in E1. E2 and E3 are given the READONLY attribute inside the loop body. and a run time check is used to ensure E3 is not zero. These restrictions are enforced by ?L/cv. as are two other restrictions: the expressLons E1 and cannot depend on the index variable J. and E3 is required to be I or -I. So that E1 and E2 cannot depend implicitly on 3 by cal lin; a function tb?t depend. on J. the variable J is not allowed to have the t1TERi?AL attribute. The reasons for all these restrictions are discuss:d in section 4.17. After an indexed loop completes execution. the value of the index variable 3 not defined. In PLICS run time checking simila? to that per- forced for ne?ly declared variables is performed to ensure the variable 3 a i?en a v?lu? by an a..l?.nt .tat?.,'nt u' po'uJure cal I L?Lu?o it is 13 - uced again. In PL,CV1 the variable nay be used before it is given a value? but the the program must be proved to work no matter what value J has when the loop completes. The LEAVE L statement must be contained in a loop labeled L. The statement is used to exit that loop. The COTO statement in PLICS is required to branch to a labeled null statement. The label must lexically follow the COTO so that all loops must be writLen using explicit loop constructs. If the label L is in a loop body or one of the clauses of an I? or SELECT statenent. every COTO L statement must also be contained therein. This restriction was included in PL/CS to enforce good programming style. However. as will be seen in Chapter 4. the restriction also eases the task of checking proofs. 1.3 An Ove??iew ? rhp Th?sla The thesis is a detailed discussion of the design of the PL'CV language and Proof Checker. The correctness of the overall design of ?he Proof Checker and several of the algorithms employed are argued. The PL?CV logic contains rules for the first order predicate cal- culus. Peano arithmetic. the theory of equality. and the PL?CS programming language. A complete discussion of PLlCV language is beyond the scope of this thesisi interested readers are referred to the PtlCV2 keference Manuel (17). It is my intent that. except for a few examples in Chapter 4. unfamiliarity with PL/CV will not hinder the reader's comprehension of the material presented. The thesis was written afteL the implenentation of the Proof Checker was complete. ln the course of writing the thesis. I discovered some arr?.,a 111 thn r?-??f Ch??ker a.,d im.??v?.?.st. tf th I.,?u( ?lcs. 14 - flecause the resaon for building the Proof Checker and writing thin thesis was to gain knowledge about program verification. not to write and docu--H Lent a nroduction software system. I have occasionally taken the liberty of describing parts of the PL?CV system as they ought to be. instead of as they are. It is my hope that these inprovenents will eventually find their way into the implemented system. T?e Proof Checker is divided into two phnses. Ti? first phase of the Proof Checker is the Local Context Checker (LCC). which inputs a proof and processes it in much the sane f-as,Jon as a compiler. But instead of pro- ducing nachine code. the LCC produces a series of instructions called V- code. The LCC performs checking that only requires looking at a small window in the proof. The global aspects of the proof are represented by the V-code. The global checking is performed during the second phase. the V--Hcode interpreter. which reads and processes the V-code produced by the LCC. iecau?e the LCC is so similar to a compiler. it could be designed ?aing well-understood principles (6. 33). However. unlike a typical com- piler. the LCC nut ssanipulate formulas containin& quantifiers and bound ?erisblea. in Chapter 2. a method of re?resenting quantified formulas is presented that eliminates some technical problems often associated with bound variables and substitution. Bound variables are represented by stor--H ing in lieu of a variable name the number of quantifiera along the path from the variable to the bindina quantifier. Operations that must com- monly be performed on quantified formulas by the LCC can be efficiently applied using this representation. An extension to the representation is proponed for use with higher-order quantification. Chapter 3 deale with the predicate calculus. PL?CV predicate cal- - 15 - culus La proved equivalent to ?entzen's Natural Deduction (64) by giving constructions for translating proofs written in esch system to the other system. Next. the syntax of PL?cV predicate calculus and its macto feature are discussed froa the standpoint of huuam engineering. Them the relationship between ALGOL scope rules and the logic is shown. Pinally. the way that V-code is used to check predicate calculus proofs is explained. Chapter 4 is con?erned with proofs of programs. It begins witb a discussion of what is neant by a proof of a progran. Then each of the language constructs of PLICS is examined. For each construct. the proof rule used in VLlCV is presented and its stren?ths and weaknesses arc dis- cussed. Then tho V-code generated for that construct is presented. A sen--H eral theoren is proved that is used to derive the V-code ?enerated for each of the control constructs. Finally. a generalized control construct called the omnibus ataterent is proposed as a replacement for all but one of the controL constructs in pL?CS. A method is preeented by ?hich V-code can be used to check proofs about a restricted version of the o?nibua statement. The V-code interpreter is based on algorithis presented in CLaptera 5 and 6. Solutions to two similar problems are given in these chapters. In each case. we are given a set 6 of pairs of formulas that are knoun to be equivalent. An equivalence relation butween formulas is defined as follows. P1 P2 is defined to hold whenever it is possible to transform to P2 by applying to P1 a sequence of substitutions res?lting in P2. where each substitution replaces an occurrence of some Q1 by a Q2 such that (Q1. Q2) or (Q2. Q1) is a pair in 6. The problei is to coipute the relation 16 In Chapter ?. a solution is given for a particular infinite set 8 The ,roblem of computing the equivalence relation defined by this set will be called testing for equivalence by ?transforintion." Two formulas P1 and P2 era tested for this type of equivalence by applying a normalizing fu?cticn N to each fornula; P1 P2 if and only if N?P1J N((P21. If t?e eet S is finite. the problem of conputing the equivalence relation defined by s will be cslled testing for equivalence by "substitu- tion." A solution to this problem is given in Chapter 6. A graph is naintained in ?hich each node repre?enta a act of fornulas. Two formulas are tested for equivalence by deterwinin& whether are represented by the asme node. A? algorithm is presented for making the necessary updates the graph to reflect the addition of a new pair of formulas to S. ?ow the al&orithms presented in Chapters 5 and 6 are combined to form the V?ccde Interpreter is discussed in Chapter 7. Automatic deduc- tions pcrfer?cd by the Proof Checker are expcessed in terms of equivalence?. A formula is considered to be proved if it is determined to be equivalent to "true." Transformational reasoning is included by main- taining a hash table that is used to associate normal forms obtained from the normalizing function N with nodes in the graph. In Chapter 8. the major results of the thesis are summsrized. The thesis is concluded with a short essay on the direction I feel future research in pregra? verification should take. 1.4 A Pew Words kwL Nnrarion wi v.?r ?.s.61v. LI.e St nJ?rd .t?.tstLun uf Lumputer seisuca aid maihesat ??a to+ `sSaJ. ??.t?st su?,? I tu'I51 ton Lii sal who+a 51than (1) iita,?'l .1 nntaI I ?n ?51 I a c?r --H 1? --H (2) the typewriter used to produce this document cannot produce the standard notation. when one of these cases arises. the syntax of ?L,CV, which was designed to cope with even more stringent typographical limitations. is used if possi- ble. Iteaders who are unfamiliar with PL/cv are requested not to form an opinion of ita syntax on the basia of thia "sneak preview." but rather to wait until after they have read aection 3.6. The universal quantifjer will be written: ALL x. P(x) (untyped) ALL x type. P(x) (typed) and the existential quantifier will be written: SOHE x. P(x) (untyped) 60MW x type. P(x) (typed) The following symbols will be used for logical connecti?es and cons?antsS --H a `0'fl `1.1 not and or implication equivalence false true. The logical connectives have been listed in order of precedence, with the quantifiers and --H binding tightest. and binding loosest. For example the formulas p a? --HALL x. Q(x) I 1(x) is equivalent tol P -) ((--HALL x. Q(x)) I 1(x)) su that tI? occurrcncu of x tn 1(x) is fros. Th??a o+y?Lujs us.d ih rL?t;v f?r tuaj?rlsuns ars --Ho+ < and ??. Tho?n symbols arc us?d wh?n writin? Pi.,CV sampics and pronf ri'ir.. flut - Ia - 51.--H mW. st.wI.rd ay?6ula 6. ?. o+.: ar--H us?J a?s.wI.?r.. The notation P?tliv) etanis for the formula P with every free occurrence of the variable v replaced by tie expression t. renamtnn bound variabl?s as nacess?ry to avoid capture. Capture is diacuseed in Chapter 2. If a and y are inteaers. the notation ix ... y) is used to denote the aet of all inte:tera ?reetcr or equal to x and less than or equal to y. Ilote that if 1 > y tben ix ... yI La empty. If A and' I are acts. let A - I denote the set of all x such that x La in A but a is not in II. The Kleene star a will be used to denote zero or more repetitions. If p is a r'la(ion. pa denotes the re?lcxivo transitive closure of p. That is. p5 is tlie smallest rtflexivo and treositive r?lation that La a sunur--H eat of ?. The progranmin? lan?uage that will be used to present alsorithms is a mixture of AICOL 68. PASCAL. and ?nglish. The three control constructs used: IL II t?en S1 LliL' 12 then 82 o+.. "ij? 8n then Sn tIlL 85+1 Ii vh?'1e I ? 8 ? `t,pe?t 8 uetil I correspond exactly to the 8ELECT statement. WIlILE loop. and UNTIL loop of PL,CS. The A1?oL?PAsCAL syntax is used rather than pL,C8 syntax to en?basize that the alsorithms are being presented for their content and not as examples of PL?C8. and because I feel the A1?oL?pA8cAL syntax is eastoetically eore pleasing. Com?nts in algorithns are encloaed in cent signs. The statement: 10 - v 41' a ie used to increment the variable v by e. and the statement: v -I. 0 is used to decrement the variable v by e. I suspect that many renders will be surpriaed by o+y use of semi- colona. and that some will even be annoyed. When used in PL?l. the semi- colon terminates statements. and is put at the ends of lines. When used in ALGOL or PASCAL. the semicolon separates statements and is put at the beginning of lines. If for example. the sequence ??i ? t 53) doea not fit on one line. it will be written: o+ 63 with matching parentheses (or keywords) vertically aligned. The notation r.f will be used to indicate field f of the record r. If p is a pointer variable. the statement: p.f :-- x will executed by replacing the f field of the record to which p points is with the value of z. If p.f appears anywhere else. it denotes the contents of the f field of the record to which p points. CHAPTER 2 ?IPIESEN?ATIONS FOB BOD?D VABIABLES 2.1 The ?? Cpnt,?re Because the Local Context Checker is similar to a coupilor. it could be conatructed using techniquea that are well-documented in the literature (6. 33J. But unlike typical compilers. the Proof Checker must create and nsnip'?late repreaentationa cf qusntified formulas. The problems aasoci- ated with representations for bound variablea are discussed in tbis chapter. Implicit renaming of bound variables ia allowed in PL?CV. For exass- pIe. if one provea the fornula: ALL I FIXED. X*X >-- 0; (2.1) and later in the proof. one needs: ALL ? FIXED. y*y >-- 0; (2.2) as a hypothesis to a rule. formula (2.1) will suffice. Because (2.1) and (2.2) are considered to be essentially the same formuls, they ought to have the sare representation. Purists might argue :he point. preferring the user to cite rules to derive (2.2) from (2.1). But consider the following example. I think it safe to say th?t no computer scientist would claim that the following: (xt2) . 3 ? 3 (2.3) xa2 3 > , (2.4) are different formulas. and insist on rules to insert or delete psrtnthc?es. We make a distinction betwcct? the marks we put on paper. and tho+ ?m?&1a. w'ti?h ?a resi ly th? jat??a (hat c.?(c?.:.5 to th.?.ts 21 - J?gura 2.1 Parse graph for ALL v FIXED. TaT ? 0 sarks. Since formulas (2.3) and (2.4) have the same parac tree. they are conaiderod to be the same formula. I proPose that the aituation is the same for quantified for.ulae. The only difference ia that inatead of a parse tree. a quantified fornula ha. a paree graph. Figure 2.1 contains the parse graph for fornulas (2.1) and (2.2). In a parse graph. all bound variablee are represented by a ape- cial Cymbol. BY. Every occurrence of BY in the graph is connected by an edge to the quantif:er to which the repreaented variable is bound. The name ot the bound variable is completely abstracted away. Since (2.1) and (2.2) both have the sane parse graph. they are considered to be the aane formula. All of this may seem like a lo? of?trouble to go throu?h just to allow a user to change the nares of his bound variables at will. But there is a reason (other than ?aking proofs hard to underatand) for rena? ing bound variables. Suppose a user cre?tes a global lenma file. contain- ing a number of useful theorena. such the following: ALL X FIXED. (pRlHE(X) --> SONE Y FIXED. (pitIxE(v) & v>x)) (2.5) ?hich atates that given any prime number. there ia always a larger one. The ALL elimination rule allows one to instantiste thia theorem. substi toting any FIXL'D value for X. such as: --H 22 raIx?(2) -? SOKE T ?ltU. (rgl?(v) & v?2) But coneider what happens when we attempt to instantiata formula (2.5) with the free variable v: FIlME(v) --> SGiZ v lIXED. (P&I?(v) & v?v) `enaming the bound version of v for the sake of clarity. we get: PgI?(v) --? SGi? Z FIXED. (PRlME(z) & z>z) Since there can be no Z such that Z>Z. we can conclude from the above that T ia not prime. But this argument is clearly absurd; something has gone avry. Tne problem is that when we substituted v for I within the scope of the quantifiCr SOME v ?IXED. the meaning of v was changed. Logicians call this phenonenon "capture." The way to avoid capture is by renaming bound variables when their names would conflict with free variables being sub- stituted. Before we can substitute the free variable v for I in (2.5). we aust first rename the bound variable v. The resulting formula is then: PIIME(v) --? SO? 1 FIXED. (FRIME(z) & z>v) (2.7) which is perfectly fine. Capt?re can only occur wh?n the ?a? idtntifiCr is being used as both a bound and free variable. A sledgehammer approach to avoiding cap- ture is to disallow the reuse of variables. Although this approach has the advanta?e of being conceptually sinple. in practice it would be quite u?pleasant for the user. Be?ore undertaking the writing of a large proof. he would be required to inspect his lemma file. find all the lemmas he expected to use in the proot. and make a list of variables bound in those len:as. which he therefore could not use in his proof. If one is design- ing logic for the purpose of proving metamathematical results. one can --H 23 --H k 2? Jiure 2.2 Foreula graph for (2.?) PRIML' Sotti Fig?re 2.3 An instantiated parae graph uake such harsh restrictions. but not if one is designing a logic in `rhich people are expected to Urite proofs. There is a cleaner way of avoiding the problea of capture. If we take the point of view that substitution is an operation perfor?ed on 24 parse trees and pane graphs. and not text. the problen of capturo eva- porates. When one substitutes 1+2 for v in vt2?Z? the proper result is (X+2)*2?Z. not X+2*2>Z. even though simple textual substitution would yield the latter iormula. Likewise. if one substitutes 1+2 for v in vicv. the proper result is vi <1+2. not 1+21<1+2. One is actually performing tbe substitution on trees. not formulas. and creating a new tree T. What is written as the "result" of the substitution is any formula whose parse tree is T. The process of instantiating a parse graph is quite similar. the first step is to delete the quantifier being instentiated. which will always be the root of the graph. The deletion will leave edges extending frum the formerly boun? variables den?ling. These variables are replaced in the graph by whatever term is being used to instantiate the quantifier. yielding a new graph C. The "result" of the substitution is any formula whose parse graph is G. For example. Figure 2.2 contains the parse graph for formula (2.5). and Figure 2.3 contains the result of instantiating that graph with v. Formula (2.?) has Figure 2.3 as its graph. but formula (2.6) dots not. Thus. for?ula (2.7). and not formula (2.6) is considered to be the result of instantiating formula (2.5) with Y. Since the names of bound variables do not appear in the parse graphs. there is no possibil- ity cf a free variable being c?ptured. 2.2 r?nrc.nrgrInns ? ALgl crupha Let us?now Lurn to the problem of representing parse graphs in the menory of a co?puter. Two different methods for representing formulas are used in the Proof Checker Loth extensions of methods for representing tr.es Je.ct&bej by KuLI' (?41. The iirsL methul uses a Llbr-liks data structure. and the second uses e string representation. so-called Polish notation A preorder traversal is used in conjunction with the string representation. but the following discussion applies equally well to a poatorder traversal. The problem of extending parae tree representations to parae graph representations is this: How are the back edges connectin3 boucd variables to their corresponding quantifjers to be represented? In the case of the LISP-like representation. an obvious tuggeation is to put in the node representing the bound variable a pointer back to the node repr?senting the quentifjer. This is. in fact. the method used in the Proof Checker. though we shall later see there is a better method. For now. let us concentrate on rhe string representation. The prefix string representation for parse trees (less some grubby details) is as follows. If the isin connective of an expression or formula is a function or operator p with n operanda P1. P2. Pn then the espresaion is represented in consecutive bytes of computer memory by the following string: P n 5j 12 ... 1n where for each i in (I ... n). is the prefi? string representation of Pi. Variables and constants are reprefiented as operstora with zero operanda. For example. the expression AsneC would be represented: plus 2 times 2 free-var-A 0 free-var-fl 0 free-var-C 0 In the implementation. suitable byte encodinga replace the names "plus.' "times." "free-var-A." etc. This representation has the following deairable properties. which the extended repre?entetlun shuuld have as well: 26 - (I) Location independence. If a prefix string is copied from one area of recory to another area of memory. the copy is a valid represen- tation of the expre?sicn represented by the original. (2) Base of instantiatiun. The operation "substitute the expreesion f for every occurrence of the variable v in the expression e? can be carried out efficiently. using a simple pattern matching algorith.. (3) Base of combination and decomposition. The expression f(x y) for example. is repreecoted by f 2 Ra Ry if and only if the expressions 1 and y are repre?tnted by ? and Ry. respecti?ely. One difficulty in finding a representation of quantified formulas is ensuring the extended representation have property (2). Because PL?CV allows a limited form of second-order aub?titution. it is necessary to properly handle the case in which a quantifjed formula is substituted for lone variable of another quantified formula. For example. when the ALL elimination rule is applied to the the formula' ALL ? BIT. ALL Q BIT. (F ? Q ? P may be instantiated by any term of type BIT. including a quantified for- mula. The basic strategy used to represent quantified formulas is to treat quant,fiers as unary operators. and bound variables as nullary operators. B'? encoded in the name of the operators used for bound variables will be infor,,atioa sufficient to locate the representation of the quantifier to which the variable is bound. By the discussion in section 2.1. the name of the bound variable need not. and should not. appear anywhere in the representation. liowever. the t7pe of the bound variable must appear as part of the corresponding quantifier name. If type information were not included in the representa- tion. one could prove the formula: SOME (T. F) BIT. ALL 8 BiT. (B--T and later use it as: SOME (J. x) FIXED. ALL X FIXED. (X--J I since both these formulas would have the same representation. In a language whe:e each operand of each operator is required to have a specific type. and there are no empty types. all type inform?tion could be discarded in the representetion of quantifjed formulas. since the type of any bound varisble. and henco the corresponding quantifier. c?uld?he deduc?d if necessary. (In PL/cv. equality is the only operator that does not have this strong-typing property.) But the type of a quantifjer can be deduced from the type of its bound v?riable only if the bound v?riable appears somewhere in the formula. Mormally a quantifier for which there are no corresponding hound variables. such as the quantifier in: ALL X FIXED. 2+2 4 (2.8) adds nothing subatantial to the meaning of the formula. There is no harm done if formula (2.8) and: ALL 8 BIT. 2+2 4 (2.9) have the sane representation. since formulas (2.8) and (2.9) are both equivalent to the formula 2+2 4. However. in a the language that has a type EMPTY containing no elements. one could prove the assertion: ALL E EMPTY. `O'B which is vacuously true. since it is impossible to inatantiste. One could then Listake the formula for: 2s ALL J ??zfl. ?O'? vbicb could be instantiated to set a contradictio?. Therefore. the bptiu ization of o?itting type information from representations cannot be used in languages with enpty types. Let us consider various proposals for what can be put in the representation of bound variables that will determine to which quantifier tte variable is bound. and still ?aintain the above three properties. The sinplest su?gestion is to use what was proposed for the LlS?-like repre?entation nethod: pct in the representation of bound variables the address of the the correepondin quantifier. Ilowever. since this method does not have property (I). we ?ight try to ernend it by using a relative offset instead of a pointer. That is. put in the representation of the b?nd varij?le the nu?ber of bytes by which it follows the binding quen- tifier. But this :nethod does not have property (2). Any time a free variable that occurs betwetn a quancifier end one if its bound variables is instantiated. the offset stored in the bo?nd variable would have to be changed. Thus. the instantiation process would involve locating and chans- irg other bound variables. There is another class of solutions that use the structure of the parse graph. which is a tree with back pointers. Since all the variables bound to a quantifier nust occur in the subtree whose root is the quantif- icr. if the lcvcl et which the binding quantifjer appears in the tree is stored with the bound variable. the quantificr to which the variable is bound is uniquely determined. But "I?vel? must be JtL ined. T??re are two ways in which level nunb?rs can be e.?1-?nrJ tu Lhc nojta of tT".sI tnp--H?wn and butto?--Hnp. in top--Hdnwn nuwhtrin?. `.h--H r?nt nI thp trcc is sssj??i?d lev.?i 0. snj ths i/O\i (a) Figure 2.4 Top-down (s) and bottom-up (b) level numbering level assigned to a nonroot node is one plus the level of its parent. In bottom-up numbering. each leaf node is assigned level 0. and the level assigned to a nonleaf node is one plus the largest level assigned to any of its offspring. Figure 2.4 contains examples of these two kinds of level numberings. Unfortunately. putting the level number cf a quantifier in a bound variable is not satisfactory. for either definition of o+level." Tbe prob- lem with using top-down numbering is that the resulting representation does not have property (3). For example. when the formula that is represented by f 2 Rx Ry is broken down into the two fornulas Rx and sy. if either Rx or Ry contains any quantifiers. all the level numbers change. Although a representation using bottom-up numbering has property (3). it does not have property (2). ?or exanple. consider the formula: ALL Q BIT. (p ? q --> p) uhih. usite bottom-up numbcrto?. would be rcpreacntcj: si i-bit I I .?i tea 2 and 2 ir?'e?var-? I hounj-var-J 0 tre?-var?? I Thc. 3 in boond?v'tr--H3 rtfcrn to List level of tic qunntii i?r. Tir problem is lint win a formila is siib?t itt pi (?r frtp?vnr-P. the level nnm?er nf 30 - the left nffsp?ina of the & is incr?sse'I. which can dense Ihfi l?vol nunb?r of the the ? node and the quantifi?r node. Tharcforc. the number atorcl with the bound variable `Lust be chan??d. There is an acceptable variation on top-duwn level numbering. lather than storing in the bound variable representation the level of the corresponding quantLfitr. one stores the difierence between tie lev?l of the variable and the level of the quantificr. Since this diffcrence is is the distance in the tree between the bound variable and the quantificr. the quantificr to which the variable is bound can be uniquely determined by counting. This represcotation has all three of the desired properties. 3ecause no machine addresses are used. property (I) obtains. All of the nodes on the path in the tree from the variable node to the corresponding quantificr node lust be function nodes and quantificr nodes. When a for- mula-or expression is substituted for a free variable. the distance from any bound v.?risble to its corresponding quantifier does not change. since there are no vaciables 0? the path from the bound variable to the quantif--H icr. Therefore. property (2) obtai?s. Likewise. when trees are combined and broken apart. distances in the subtrees between bound variables and correspo?ding qoantifiers do not?change. so that property (3) obtains. A modification of the above representation system is used by the Proof Checker. lather than storing in the hound variable representation the len6-th of the path from the variable to its binding quantificr. the number of quantificre (not counting the binding quantificr) on that path is stored. The correspoodence between bound variables and quantifiers can still deter?ined by counting quantificr nodes. This system. which will henceforth be referred to as flquantifier count" representation. has all three of the desired properties. but it also has one more. - 31 - /\ /\ AflC A I I C (a) (b) Figure 2.5 Unuormalizad (a). (b) and norializcd (c) parso trees Another operation that is pertarmed on formulas is normalization. For example. the expression (Atn)+c is parsed as in Figure 2.5a. whereas the expression A+(Btc) is parsed as in Figure 2.5b. As is discussed in Chapter 5. theue two expre?sions are d?duced by the ?r??f L'hecker to bs equal by normalizing them both to the tree shown in Figure 2.5c. But now consider what hsppens when the formula: SO?E A FIXED. (A+B)+C 0 is normalized. The normalization operation ch?nges the length of the p.th from the bound variable A to iLs qujutifjar. but not Lhe numb?r of quan- tifisrs (zero) alone the path. Since none of the normalizations perforned by the proof checker alter the quantificr structure of a formula. these operations can be performed on quantificr count representations without having to update the bound variable representattons. Quantifier count representation can also be profitably used with the LiSP-like representation. There is a certain elegance in representing a bound variable by a pointer to the corresponding quantificr. but it com- plicates some programming tasks. The problem with this representation is that it creates circular list structures. which can be annoying. especially in programming environments that employ garbage collection. To copy a circular structure. one needs to use `.liat?markingm algorithas (66). which 32 - are core complicated than the straightforward recuraive algoritbm used to copy trees. For these reasons. to represent the link between bound vari- able. and quantifiers. quantifier counta are prefereble to pointer.. 2.3 uu?nr??1er ?j? It is easy to create a parser that builds quantificr count represen- tations. Because of the nature of prof b?ocks in tbe PL,CV language. a block-structured symbol table of the type deacribed by Cries (36) is required. T?e synbol table routines have the following entry points2 (I) Blockrpen. Increase the current block level by one. creating a new block (2) Declare(I). Create a new variable record in the current block. and associate it with the identifier I. (3) fllockclose. Decreases the current block level by one. discarding any variables and associations created in the block being closed. When parsing a formula. the number of quantifiers along the path from the clc?ent currently being processed aid the root of the parse tree is maintained in a global variable called QuantifierLevel. This variable is initialized to zero. increased by one when the scope of quantificr is entered. and decreased by one when the scopa is left. Here is how a quantified formula of the form: ALL V1. V2 Vn type . formula is parsed. A recursive desc--Hnt mu?1el of paraing (35J is assumed. When the ALL is encountered. ? new block is created by calling Blockopen. Them Declare is called for each identifier V?. creating variables local to the newly crcat?d block. Tic varibles nre markcd in the symbol tahle as - 33 - being bound variables5 and QuantifierLevel+i is stored in tbe variable record for each Vj. Then QuantifierLevel in increased by n. the formula is recursively parsed. Quantifiertevel is decreased by n. and BlockClose is called. When an identifier is encountered during paraing. it is looked up in the symbol table to get the variable with which it is currently associ- ated. in the case of a bound variable. the nunber of quantifjers on the path from the variable to the quantifjer Q to which it is bound should be put into whatever representation the parser is building. The synbol table record for the bound variable contains the number N of quantifjers on the path from the root to Q (including Q). The variable QuantifierLeval con- tains the number of quantifjera on the path from the root to the bound variable. therefore. the number that goes in the representation of the bound variables is QuantifierLevel - A similar algorithm is used for instantisting quantified formulas. Actually. instentiation is a two-step process. Suppose. for example. in the formulq: ALL P Bit. ALL Q Bit. (P & Q --? 5) one wished to inatantiate the variable 5 wirli the fornula X ? 0. The first step is to delete the quantifier: ALL Q BIT. (5 & Q --) 5) transforming 5 from a bound variable to a free variable. The second step is to substitute X ? 0 for every occurrence of 5. ?otice that these o?ra- tiona must be petformed on internal representations. By property (2). the second step can be performed easily. When working with external representations5 the first stsp sprears inte?er Quantif?erLevel ;- 0 i :-- beginning 0 the eubLree to be searched S ??n?.d?,? nfind(): k?aiaL??? --I `phile n ? 0 li 1(iJ.op?r is a quantifier then i s:-- I ; QuantifierLevel +:: I Bfind() QuantifierLevel --Ha- I lili R(i).optr is a bound variable then li QuantifjerLevel ? the level nuMber encoded in the name of the variable then the variable is dangling li i +:-- I ; n-:-l el. n +:-- &(ii.order --H 1 ; i o+:--H- 1 li ad ad Bfind() Figure 2.6 Algoritba Da The location of dangling variables completely trivial. But nerforming the operation on a formula in quentif--H ler count representation requires a bit of processing. After deleting the leadin? quantificr from the representation. all the bound variables which forserly reterred to the quantificr must be located and changed. One could cha?e each locatcd bound variable to a new free variable that dose not occur anywhere in the formula. and then substitute the representation of X ? 0 for each occurrenco of that free variable. but it is simpler to coibine these two operations. and substitute I ? 0 for each bound variable a. it is located. Thus. the proble:s of instentiation is reduced to Lhat of locating each bound variable associated with a particular quantificr. Algorithi fl. shown in sigure 2.6. will accomplish this task. secall that the string representation of a formula consists of a sequence of pairs. We will assuic that the array a contains such a sequ?nce. Each element 1(i) has two fields: "optr." the name of the represented ooerator. and `.order.M the number or operands the operator takes. Let T be a subtree of the representation in R to be searched. Some bound variables in T will be bound to quantifiers within T; others will be bound to quantifjars outside of T. These latter variables will be called "dangling" variables. be?ause when viewing just the subtree T. these variables are not bound to anything. Algorithi D locates all the dangling variable. in T. Given a formula of the form: ALL X FixEl). T in which the main connective is a quantifier. if algorithn D is applied to the subformula T. the dangling variables located will be precisely all the occurrences of the bound varisole I in T. Routine flfind assumes on entry that i points to the beginning of a subtree 5 of T. Ifind moves i just past 5. locating all the dangling variables in 5. An invariant of the while loop in flfind is that the index i must be moved past n operands before the end of 5 is reached. There are three casca. depending on what R(i).optr is. If the operator is a quantifier. I is moved past the quantificr. and ?find is called recuraively to move I 36 - past itS operand. be result of these two onarations is to move i past one complete operand. so that is decreased by one. Likewise. if B(i).optr is a bound variable. i is moved past it. and n is decreased by one. Finally. consider the case in which R(i).optr is some other opera--H tor. Then i points to the beginning of n operands. the first of which is an o?erstor with a (where ni ? 0) operands: Pj P2 o+.. ?m q2 q3 where is an optr-order pair. and through ?a make up Q1. Once i i? moved pa?t . then there are m+n-l operands left to be moved past. so that to mai:tain the loop invariant. n must be increased by M(i).order--Hl. The function of the variable QuantifjerLevel is the same in thin algoritha as in the parsing algorithm. QuantifierLevel contains the unber of quantifiers that are on the path from the root of the tree to R(i) and also contained in the subtree T. Whenever we encounter a bound variable whose level number is greater to or equal QuantifierLevel. the qus:itifiCr to which it is bound must occur outside the subtree T, and hence that variable is dangling. Algorith. 1) lust be recursive to locate the ends of the operands of each quantifier. so that the variable QuantifierLevel can be decremented in the appropriate place. If the representation of formulas is modified slightly. a nonrecursive slgorithm can be used. Recall that in the stan--H darn string rCprtJnnt?tion. th? ?ur?jls M.L X FlXEfl. P(x) Is r?j.r?s.ntud1 all-fixed I Rp where Rp is the representation of 1(X). In the motified system. the for--H out. we lJ bc rcpr?s.?ntoJ: 37 ?nrrs?r QuantifierLevel 0 i :: the beginning of tbe subtre.e to be searched Xhi1 QuantifierLevel ? 0 ila IL It(i).optr is a quantifier th?n QuantifjerLevel +:- I liiL R(i).optr is "end--Hscope" ?hpn QuantitierLevel -:-- I allIL R(i].optr is a bound variable then IL QoantifjerLevel ? the level number encoded in the na,se of the variable Liidi the variable is dangling li li s i +:-- I sill rigure 2.7 Algoriths D': a simpLified algoritb? all-fixed I Rp end-scope 0 appending. a special marker to delimit the end of the scope of the quantif--H Aer. the 0 after the `merker has no significancel it is present only to preserve the rule that a string representation consists of an alternating sequence of operators and numbers. A string in the modified represents- tion can be converted to the standard representation sinply by deleting all the "end-scope 0" markers. Likewise a string ?n the standard representation can be converted to the modified representation using an algoritha similar to Algorithm D. The advantage of the modified represem- tation is that the simple "parenthesis counting" algorithm D'. shown in Yiguro 2.7. can be used to locate dan?Iing variables. For alLut1th. fl? to work. the subtree bejuM searcht'J must be fol l?w,d by an end-scope marker. The oper?nd of quantificr will always will always be followcd by an end- scoi,c ?wrker. but an ?r:,?tbtr.'? cL b scar 1..J. An.,tl.cr d??ad--H - 38 - vantage is tbat the modified repreaentation takes more apace than standard quantifier count representation. 2.A l???????? LaL ??el-??ut Lu? The PL?cfl ?23) system will be extended to include second-order and higher-order formulas. The new complexity introduced in higher-order log- ice is quzntification over functions and predicates. For example. integer induction can be expree?ed by the following second-order foriulal ALL P(FIXED) BIT. ( r(o) I ALL X FIXED. (X>--O I P(X) ;> P(x.1)) (2.10) => ALL X FIXED. (X>--O --> Formula (2.10) can be inatantiated with any predicate that takes a FIXED value and yields a BIT. Fredicates may be written using lembde notation. ?or- e?:ple. the predicate "is greater than 5" would be written: LAItlIDA T FIXED. v 5 (2.11) Formula (2.10) can be instantiatcd with predicate (2.11) to yield: ( ( (IJ?DA v FIXED. v>5)(o) I ALL I FIXED. ( 1>0 I (LAxBDA v FIXED. v>5)(X) --> (?NBDA v FIXED. v>5)(x+1) ALL I FIXED. (1>0 :> (LM(BDA v FIXED. v>5)(i)) which. in turn can be simplified to: ( 0>5 I ALL X FIXED. (1>0 & 1>5 --> Xtl>5) ALL I FIXED. (1>0 --> 1>5) Of course. lambda expressions may themselves contain quantifiera and other lambda expressions. For example. the predicate o+is even" cam be written: - 39 - v FIXED. SOME M FIXED. 2s? The capture situation is more complicated in higher-order logica than in first-order logic. For example. consider the following valid o+ccond-ordor form?.la: ALL F(FlXED) BIT. ((ALL X FIXED. P(x)) :? ALL X FIXED. P(XtC)) (2.12) which states tnet if a predicate holds for all integers. the predicate can be ?ehifted?? by a constant factor C and still remain valid. `jars is an example of capture that is analogous to the capture that occurs in first- order logic. The predicate: LAMEDA v FIXED. (X--H--O 1 v--H--c) (2.13) has two free variables. X and C. and is true for all v if X 0. But when formula (2.12). is instentisted by predicate (2.13).' the result. uhen sim- plified. is: A1?L X FIXED. (X--H--0 X--H--C) --? ALL X FIXED. (X--H--O 1 X.c--H--c) - which is not valid if C --H? 0. The problem here is that the variable X which is free in (2.13). is being captured (twice) by quantifiera in (2.12). Once we begin instantiating second-order formul?a with lambda expressions containing quantifiera. new types of capture emere. For example. if (2.12) is instantiated with the formula: LAlIBDA v FIXED. SOME C FIXED. ccv (2.14) the result. when simplified. is: ALL X FIXED. SC?B C FIXED. C Q 5 :> Q (5) ?015 --HP ALL x. 5 (7.8) 5 --HP (9.10) `0'I ALL?.P (11.12) PEtllx) (5Evll?)) SOME x. 5 Q 5(t??xJ __________________--H (13.14) SOlE x. 5 I `0'5 `0'5 (15.16) 5 Fi?ure 3.1 Centzen's ruler of inference rule (14). An tn.tanco of this rule will be a formula q whose offspring are the formulas SOME x. 5 and I. the formula 5(vllx) above the hypothesis Q indicates that cvery?here 5(vllx) appears as an assumption in the aubtree whose root is q. the assumption is discharged. To et't of the essueptions in a subtrt-e T of the proof that are not discbar??d by instefirCA fir rt'l?. in T its?lf is r?f?rreI to a. Ihp d aaaua?tju..a of T.? A cu?i?l?ta prut.( is llot allowed to l.a?e any unjiachjrged assumptions. P?tl.?. (I I4) ar--H ur??aIIz?.l as o+.Intr?ad...?I I?.nll and nEliiainatton" tulee for the conlectives ?. I. ->. --H. ALL. and Lo??. in li?nro 3.1. the Intro- duction rules appear on the left. and the Elimination rules appear on the ri?1.t. In an Introduction rule for a connectivo p. the main connoctive of the conclusion is p. Conversely. one of the hypotheses to an Elimination rule for a connective ? has 0 as its main connective. Rule (1?). the Rule of Contradiction. is a more powerful version of rule (IS). The reason for having both rules is that in intuitionistic logic. rule (16) ja diaallo?ed but rule (15) may be used. In classical logic. all the rules nay be used. and rule (15) is redundant. There sr? soos important re?trictj?ns on the use of two of the rules. In rule (11). ALL Introduction. v must not occur in any undiachar?ed assouption of the aubtree whose root is P. In rule (14). SoltE Elimination. v must not occur in SO?*? x. P in Q. or in any undiacharged assumption of the subtree whose root is the hypothesis q. An example of a Natural Deduction proof appears in Figure 3.2. Each of the nodes is followed by so?e annotation in braces. Aasunptions are annotat?d with small letters. Nonleaf nodes are annotated with the nuiber of the rule used. and any assumptions discharged. 3.3 ?:J? The presentation of ApL?Cy given here has been adapted from ? `-?--H??-` o? (19). The logic has been modified slightly to simplify the equivilence proof. The most significant change is t.L?at Constable and O1lonnell's logic has typed quantifisre. end the logic presented here has --H 51 --H ((PIQ).?M)"?((P.>x)a(Q.?)t) (JbJi (?-?a)(Q-?M) (1) Pa?M (?`) Qa?ft (ic) I I a (8) ?Iq (4) P)Q??a (b) PIQ (5) PIQa?g (d) p [) Q Figure 3.2 A Natural Deduction proof tree untyped quanLii?rs. An APL!cv proof is a sequence of lines. each o? which must be one of the followings (I) A conclusion of a rule of inference. written P. where P is a for- mula (2) The special symbol PROOF (3) The special symbol QED (4) An assumption of the form ASSUNE P. where P is a formula (5) A qualifier of the form ARBITRARY v or CuOOSE v. where v is a vari- able There are some constraints on the ordering of the linea in a proof. The symbols PROOF and QED must occur in pairs. prop?rly nested in the same fashion that hep,'n and afli are nested in ALGOL. and that parentheses are nested in formulsa. A PROOF. its matching QED. and the text between th?m is collectively referred to as a "proof bloc?.5 Qualifier lines may occur only immediately after PROOF lines. and ASSUME lines may occur only after PROOF or CHOOSE lines. PROOF PROOF IROOF ASSUME ? CItOOSE v ARBITRARY v ASSUMS P Q . Q QED Q QED QED Figure 3.3 ?otation for proof blocks used in rules T?e last line of Ibe proof must be a conclusion 1ine? il conlaine tbe formula being proved. Central to APL?CV is the notion of "accessibility.5 A formula P is said to be accessible to a conclusion line q whenever P appears on an aaaurption or conclusion line p. and tho following three conditions hold: (1) Line p precedes line q in the proof. `2) Every proof block containing line p also contsins line q. (3) No proof block that contains line q but not line p qualifies a free variable of P. A proof block is said to qualify a variable v when- ever it. PROOF line is immediately followed by an ARBITRARY v or CuOOSE v line. A proof block p is accessible to a conclusion line q whenever the followins tvo conditions hold: (1) Every line of p precedes line q in the proof. (2) Every uroof block containing p also contai?s line q. Figures 3.4 and 3.? contain the rules of inference of APL/CV. Every conclusion line of an APLICY proof must be the concluajon of one of the rules of in???nce. and tho corr?'sponding hypothesos must be accessible to the conclusion line. Tho ArL?CV rules have bet? dorivud from Contzen'a rules. Correspond:ng rules in the Centren sys?em and APl.!Cv have been labeled P Q P?Q P&Q P&Q p q PROOF PsOOF AsSU?1E P ASSUXE Q a R ?ED qED (1.2.3) P Q PIq PIq PIq a PROOF AsSUMK P Q QED p -? q PROOF ASSUME P loin ?ED --HP P P --> Q (JA) Q P --HP (?.10) e015 Figure 3.A AP?/CV rulei of infeentice (Part I) with the 5510 nuober. Rxcspt for rule (1)). the rules that do not involve diecherging sss?LLptions are identical in both systems. The other rules have been modified in APLICY to have proof blocks as hypotheses. Figure 3.3 aI?u?a tlie nutatiun ?ae? tu inJi..at? ?r?u! 6luck. it. LI? ts?1tr?tttt rules. The letter Q denotes the formula appearing on the line preceding the QL'D. either alone on the line ?r as part of an a6aun?tLon. ln the latter case. the vertical ellipais is cmp?y. and the letters F and Q flOOF AILSlmAI? v ML z. P - 54 - ALL a. P (11.12) FEtllx) PROOF CHOOSE v ASSUME P(vlla) Q QED PEtllA) SOME a. P (13.14) SOME a. ? Q ?0?3 P PROOF ASSUME --HP `o'n QED P (l5.l?) Figure 3.5 APLICY rules of inference (Part 2) denote tbe sauc for:ula. An i?port.nt rtstriction on tht u.e of rule (14). S?E Elimination. is tbat Q may not contain any free occurrences of v. Figure 3.6 contains an example of an APL?CV proof. The proof corresponds to the Natural Deduction proof in Figure 3.2. Each line of the proof t?s betn labeled with a letter. The conclusion lines have been anno- tated by the nunber of the rule used and references to its hypotheses. contained in braces. It is easier to reason about APLICY proofs if they are presented as trees rather than sequences of lines. A tree is obtained from a sequence a) PROOF b) ASlutit' PIQ?>I c) Pk'OOF d) A9SUNE ? e) rlq f) R ?) QEl) h) P-->R i) PROOF j) AS?U?LL' Q k) PiQ 1) R m) QED n) Q-->R o) (??>x)&(Q?>a) p) QED q) (PiQ-->R)-->(P--?R&Q-->R) jic) (5j) (akb) (li) (lhn) (7a) Figure 3.6 An example APLICY proof of APL?CV lines as follows. If the sequence of lines contains no pi-oof blocks. the resulting tree is a vertical chain of nodes. one for each proof line. This vertical chain will be called the "main branch.5 The formula at the bottom of the main branch is called the ?terminus." If the sequence contains one or nore proof blocks. for each block. a branch tat a.ngles off to the risht and then down is hung on the main branch at the point corresponding to the block. This branch coW,?cta to a subtrt' ti,nt is obtait,?J recursively from the sequence of lines between the matching PROOF and QED. Back on the main chain. a square iC inserted just below the branch point; thia square represents the proof block when determining accessibility. Note that the formula being proved is the terminus of the main branch of the proof. The main branch of a proof never contains soy qual- ifiers or assumptions. and the main branch of a proof block only has qual- ifiers or assumptions at the top. as indicated by the appropriate proof rule. 0 (PiQ--)I):>( (r-->a)&(?-->i)) ASSUME rIq--?r L 0 P-->R AsS))tE q PIQ R ?igure 3.7 An APL?CV proof tree ASSUME P P!Q a ?isur--H 3.7 Contains an APLIcv proof tree for the proof in ?isurs 3.6 The advantage of using APL?cv proof trees is that the accessibility rules are simpler for trees than for the sequential system. A formula 5 is accessible to a node q if and only if a node p containing the conclusion P or ASStXE 5 ia accessible to the node q. A proof block is accessible to the no?e q if sod only if the square representing the proof block is acces- sible from the node q. A nodt p (whether assuwption. conclusion. or proof block square) is accessible from a node q in an APL?CV tree if and only if: (1) There is a (unique) path in the tree from n to p that goes only upward and leftward. Hereafter. this path will be referred to as an ?accesn path." (2) If p contains a formula 5. the access path from q to p does not pass through any CttOO?E or A?BlTRARY node that quslifies a free vari?blc In r. --H 57 --H The reason the square representing the proof block must appear helo? the branch point is t? prevent a proof block from being accessible to uodea. within Itself. Ue are nov equipped to see the correspondence between Natural Deduc- tion and APL/CV. Two constructions will be given. The first construction will be used to convert a valid Natural Deduction tree (hereafter call?d an ND tree) into a valid ApL?CV tree. Then. the reverse construction will be given. establishing the equivalence of the two systems. 3.4 Conve?ring Np??rn1 ?,?jw? oronfe La The sleorithm for converting an ND tree to an APLJCv tree bas these steps: (I) areak the tree apart at the root. forming from one to three sub--H trees. (2) kecursively apply the the algorithm to the subtrees to form A?L?CV trees. (3) Combine the resulting APL?Cy subtrees to an APL?Cv tree correspond- ing to the original ND tree. ?owever. there is a slight problem. Although we begin with a coiplete Natural Deduction proof. with all its assumptions dischsrged. after step (I) is performed. the resulting suhtrees will. in general. contain some undiscbsrged assumptions. These subtrees are not proofs. and therefore cannot be converted into APl,Cv proofs in step (2). In this caae. the output of the algoriths will be an APL?Cv proof tree wiLh soue extra assumptiuns. the undischj'r6ed assumptions ?f the ?D tree. attached to the root. These assumptions will be accessed fro: within the tree. W1?n the .aIs?rith? ti s?j,l t?d tu a cua?lete f?? tree. -58. F'q A N1 A1 A2 P Q A1UA2 Q Figure 3A The conversion of an And Elimination ?ifl tree `ahich baa all its assumptions diacharsed. the reaulting APL?cv rree viii not have any extra asumptiona. For the base case of the recursion. we must convert a leaf of an MD tree. a single undiacharged asaumption. to an APL?cv tree. it is con- vtrted to a null trte with the assumption attached. The actual work of the construction is performed in step (3). ilow the APL?cv trees are combined varies. depending on the rule applied at tha root of the h.D true. Separate constructions will not be given for each of tLt sixtten rules. It should be sufficient to examine in detail only fo?ur exe?plary rules; the construction for each of the rest of the rules ia ainilar to one of the four. Each of the four cases is illustrated with a three-part diagram (Figures 3A-lI). containing (a) the ND tree. (b) the APL?cy trees obtained fros atep (2). and (c) the APL?cv tree obtained from step (3). ftule (1). And Elimination. is one of the simplest. and is a good place to start. The construction is illustrated in Figure 3A. The ND trees L1 and N2 are recursively convarted to the APL/cv trees V1 and V2. 59 --H (a) A1 A2 A3 PIQ R 11u(&2-(P))u(A3-(Q)) rIQ yi1?Assu?tE ? II a a ?iaure 3.9 The converajon of an Or E1i?ina?ion ?D Lree A1 and A2 are set. of undiacher?ed aaa6epLiona fron Lhe MD Lrees. The APL'cv tree for p&q ja conaLrucLed by aLacking V1 on top of V2. The eat A2 of sasumptiona is rembved fro. the top of V2. and ja united 60 ALL :. P A1 Pvllx) N1 P(vllx) OffliltuiT v ALL x. P P(vftx) (a) (b) Figure 3.10 The co?version of an ALL introduction ND tree ?eliminsting duplicates) w?th A1. The formula P&Q is appended to the hot tom of the tree. We must verify the validity of the resulting ApL?CV tree. The main branch of V1 and V2 will not contain any qualifjera; those viii be off to the rig"t in the proof blocks. Therefore. formulas ? and Q are accessible to the formula P&Q. All the rules used in V1 and V2 are still properly applied. The only change is that any access paths from nodes in V2 to aasunptions in A2 must be extended through the main branch of V1. which is allowed. Constructions similar to the one for And introduction are used for rules (2. 3. `b. 5. 8, 10. 12. 13, 15). Let us next consider a rule in which assumptions ste discharged. The most complicated of them is rule (6). Or Elimination. Fisure 3.9 illustrat's the construction uscd fur Or Elim?nstion. lecall thst the set of assumptions nt the top of the tree in (c) are allowed to consist only of undiacharged assumptions of the tree In (a). Since the usc uf tile Or Elimijutiun rule disch'rges tie assumptions r and q i i'? s'?d Nj ( r??sl???? t iv. I?) tI?..s., 5,I.t i `115 way u.?t be?`d to the t( tIe tree in (?) . TI ?. v1 an. V2. srp I.. I liii.. .i.i...r q / MQ SOME x. 5 M N I 2 61 - A1 A2 SOME x. 5 Q A1U(A2-P(vlla)) SOME x. 5 Th 0 CLIOOSE v ASSU? Ptvllxi Q Q (a) (b) Figure 3.11 The conversion of a SOME Elimination L'fl tree blocks. and the assuiptiona 5 and Q are left behind to head the proof blocks. As vas the case vith And Elimination. access paths from nodes in V2 and V3 to assumptions in A1-(P) and A2-(Q) must he extended up the main branch of V1. Similar constructions are used for rules (1.9.16). leaving only rule (11). ALL introduction. and rule (13). SOlE Elimination. for considers- tiun. The ALL Introduction construction is illustrated in Figure 3.10. The access paths from nodes in V1 to assumptions in A1 must he extended in (c) to pass through the AUlTRARY v node. The APL?CV accessibility rules allov such a path only if the assumptions in A1 do not contain the v?riable v. flut recall rhat A1 is the aLt of unJiach.rg?J asaumptions fr.'m NI No s(?.umptL?.n in A1 can c,ntain v. by tbc'triction plactI on Ctntstn's ALL Tntro?In??t I??n rute. - 62 - Fi?--HIly l.t u--H un. .1 g o+I. c?..v.rsi.?.. f?.r fl(?H? ri mlnati.?.?. wi.ith is illustrat.'d in Fieur? 3.11. Of all the rules. this one has thn most conplicated c?nstruction. because an assunptjun is being discharged and a qualitier is being introduced. As with the ALL introduction rule. we must Nke aure that acceas oaths from nodea in V2 to aasumptiona in A2-(P(v#x)J. ?j.ich muat be eatended through the ?llOOSE v node. do not accesa assumptions containing a free occurrence of v. But aince Gent:en's SOXE Elimination rule cannot be used if v occurs in SOlE 1. P Q. or any of the undiacharged aasunptions in A2. no access path is blocked. Nore- over. this restriction enaures that the tree (c) will obey the APL?CV res- triction on S()?? Elinination. that v is not in Q. The above construction conpietes the proof of the following theorem: for every laturel Deduction proof of a theorem ?. there Is a corresponding L2L?cv proof of P. To complete the proof of the equivalence of the two systems. the converse of the above theorem will be shown by giving the reverse con- struction. 1.1 Cnnvtrtin? ?flJ? proofs ? tatural Deduction The firat atep of this construction involves renaming some of the variablee ustd in the APL/CV tree. if there o+?re n qualifiers in the proof. a distinct variables that do not appear anywhere in the proof tree are chosen. Then. in each subtree whose root is a qualifier of the form CBOOS ? or AR3lTg?Y v. every occurrence of v is replaced with one of the new variables. To see that this renaning preaerves the correctnesa of an APL?Cv proof. it is onlY necessary to inspect each rule of inference. and verify that I? a new variable (..ne that d??a not alresay sI.I'car in th--H proot) is consistently substituted for another in the hypotheses and conclusion of an instance of a rule. the reault is still an inst.?nce of the rule. flte only way we can get into trouble is if one or more of the hypothesca of the rule are not in the subtree being modified. and there- fore do not have the substitution performed on them. Becauae the accesa path to the hypotheaja must paaa through the qualifier for v. by the APL?cv accesaibility rules. the hypothesis cannot contain v, and effec- tively the substitution has been performed. If the same variable is qualified in more than one place in the proof. care must be taken in choosing the order in which the renanings are performed. If proof block B1 containa proof block b2. end both qualify the same variable. must be renam?J b?fore B1 . If this or?crin? r?s- triction is observed. the resulting proof tree will have have the following property: any variable that is qualified at the root of a subtree does cot appear anywhere in the proof except in that subrree. After the renaming operation has been performed. the ApL?cv tree is traversed by starting at the root and hending d?wn the main branch. visit- ing each node. As each proof block is encountered. it is traversed recur- sively. This traversal is exactly the order in which the lines appear in a sequential proof. The order has been choaen an that a node V is not visited before every node accessible to V has been visited. Uhen each conclusion or assumption node conteinin? a formula ? is visited. an MD tree with F as its root will be constructed and associated with that node. Not every node in an AFL?CV tree contains a valid for- mula; therefore the MD trees constructed must in general have some undiacharged assumptions. The MD tree constructed for a node V will have 64 the following property: if the access path from V to the roo of the APL?CV tree is traced5 the set of assumptions through which this path passes will contain the set of ?ssumptions that are undiacharged in the constructed ND tree. Since the access path from the formula P proved by the APL/CV tree to its root is the main branch of the proof. the path cam--H u?t pass through any assumptions. Therefore. the ND tree constructed for 5 will have all its assunptions discharged. The tD tree constructed for a node v depends on whether the node is an assunption or conclusion. and if it is a conclusion. which rule has bee? us?d. As before. it is not necessary to consider all the rules. the sare set of representative exauples is used, If the node V is an assunption. the hD tree constructed consists of just the assumption as a leaf. Since V is on the access path from itself to the root. it is allowed to be undiacharged. Next. c&asider the case when V is a conclusion node? then V consists of just a fornula. As in the previous cons'Lruction. we consider four rep?esentative cases. First. suppose V Is of the form P&?. and is the conclusion of rule (1). And Eliaination. Then there must be formulas of the form 5 and Q accessible to v. The nodes containing these formulas will have already been visited and ND trees Np and N? will have ben constructed for them. The ?D tree for V has P?Q as its root. and N5 and NQ as its two subtrees. Call this new tree We must verify that the undiacharged assumptions of Npq are all on the path from V to the root of the APL?CV tree. Becn'?se 5 and Q are accessible to V in the APL?CV tree. the access path from V to the root of the APL/CV tree passes throu?h both 5 and Q. Th.?rcfore. Lh? path frus. V PIq Hm AeSU? ? 0 AsSu?E Q RI R3 ?isure 3.12 An Or Iliminatioc code to the root contains both the path from P to the root end the path from ? 0 the root. The set of undiacharged assumptions of ? is tbe union of the undiacharsed assumptions in Nr and NQ By construction. the undiecharsed assumptions in Np and Nq are the path from P and Q (respectively) to the root of the ARL?Cv tree. Similar constructiona are used if the AFLICY node is the conclusion of any of rules (2. 3. ?. 3. 8. 10. 12. ?3. 13). Next. let us consider the case in which the node ia the conclusion of rule (6). Or Elimination. Figure 3.12 contains a diagram of the situa- tion. (Alth?ugh a n??e containing ?IQ and the proof blocks h?vn mUsr be on the psth from R1 to the root. they need not appear in the or?er .?own in Figure 3.12.) Node R1 is currently bejn? visited; noles containing riq. and R3 have already been visited and I?) trees constructed for the?. - 66 - The NO tree M1 is formed by joining these three trees. We lust verify that all the undiacharged assumptions in N1 are Cm the path fiom B1 to the root of the APt?cV tree. By the same reasoning used for the And Introduction rule. all the undiacharged assumptiona in the ND tree for ?IQ are on the path from Rj to the root. The same is true for all the undischarged assumptions. except ?. in the ND tree for 12 and all the uadischar?ed assumptions. except Q. in the ND tree for 13. The exceptions ? and ? are not a problem. however. because Geitzenis Or Elimi- nation rule discharges all the assumptions of F in the proof tree for 52 and all assunprions of Q in the proof tree for 53. 50 that I and Q are not undischarged sasumptiors of Ms. Similar constructions are used for rules (7. 9. 16). leaving rule (11). ALL Introduction. and rule (14). SONE Elimination for consideration. T?e ALL Introduction case is pictured in ?igure 3.13. The ND tree Mp that was constructed for node I is used as the single offspring of ALL I. P(x//v) in the ND tree constructed for the formula. Checking that the undischarged assumptions in N1 are on the path fro: ALL x. I to the root is no different for this rule than for the pre- v1?ua rules. What ?akes this rule special is that we must verify that the restriction on the use of Centzen?s ALL Elimination rule. that none of the undischarged assueptions in N1 contiin v. is met. By construction. all of the these assuu?tions are on the path from PEv/Ix) to the root. But all of the assu?ptiona must be outside the subtree whose root is ANBITRARY v since there can be no assumptions on the main branch of the subtree. And the reta?ing operation guarantees that none of the assumptions oitside the s?btraa contain any occurrences of v. Finally. consider the SOME Elimination rule. pictured in Figure 3.14 6? - AILBITWY v ALL x. P P(v#x) Figure 3.13 An ALL Elimination node SOME x. ? 0 CHOOSE v ASSUME P(vllxJ Qi Figure 3.14 A SOME Elimination node (Once again. the order of the hyp?Lbesea need not be as shown). The ND trees already constructed for SOME z. ? and Q2 are used to build the ND tree for Qj We must verify that the three restrictions on Centzen?a SOME Elimination rule. that: (I) the variable v must not occur in SOME x. P. (2) the variable v must not occur in Q1. and (3) the variable v muat not occur in an undiacharged assumption in the proof tree for Q2 are met. Restriction (2) will be met by the ND tree because it is also a restriction on the APL?Cv r?l?. The other two restrictions are guaranteed to be met by the renaming operation. 68 The proof of the equivalence of Ge,. t1em?s Natural Deduction and aPL'cv is now complete. There are obvious similarities between the comstruction?thst traneletes an APL?CV proof to a Natural Deduction proof and the one that goes the other way. but the constructions are not inverses. APL?Cy ia more econozical than Natural Deduction in the sense that if a proof writ--H ten in AlL?Cv is trsnslatcd into a Natural Deduction proof and then translated back into APLICV. it will typically get larger. The reason for the exr"ansinn is that in ApL?cv. once a formula is proved it may be used repeat?dly as a hypothesis in subsequent lines. When the proof is translated into a Natural fleduction tree. one copy of the pro?f tree for a furmuls is added to the tree for each time the formula Is used as a hypotnesis. A common technique for shortening proofa in APL!CV is to prove a universally quantified lanes and then apply it several times using the ALL limination rule. When applied to Natural Deduction proofs. this technique only makes them longer. 3.6 ?? v?r?'s The language APLICY defined in section 3.3 is vary close to the language processed by the PLIC'i1 Proof Checker. Several modifications were made to APL/Cv to get PLICY. the language processed by the Proof Checker described in this thesis. The modifications made to APL?CV were aimed at achieving the followin0 goals: (I) Mre Ity. Th hit'.te?t J awI?n k of ri/t:vi is tha great lan?th of the is. ?urh uf thn .I??siri `i I'I?CV was Jrlvt'u by LItr goal of allowing the user to get sway with writing as little as possible. (2) Lcnihility. Pijcv ,? `Isigord to mimic as cloa?iy as possihle the 69 --H style o? inforual sathematical proofs. (3) Consistency. PLICY predicate calculus is the core of a program verification syste. for PLICS. a PLIl subset. The syntax of PLICT was designed to be consistent with that of PLICS (4) 1fficiency. The PLICY language and Proof Checker were designed hand-in-hand so that the language could be efficiently checked. The goal was to sake tht Proof Checker a. efficient as an opti.iing coupiler. The changes made to APLICY. as motivated by the above goals. will now be discussed. There is no reason to present the entire PLICV syntax in detail here. The interested reader is referred to the PLICY Reference Manual (171. A syntax hsd to be chosen for quantifiers and qualifiers. As we shall soon see. the purpose served by these constructs is the same as the purpose served by declarations in the programming language. Therefore. a similar syntax is used for all threu con?tructs. as shown by these exam- pIes; DECLARE (A. 5) FIXED; ALL (A. 5) FIXED. (A*t2 + 5*52) ?-- 0; ARBITRARY (A. 5) FIXED; So that every variable in PL/CV has a apecific type associated with it. information must be included on quantifiers and qualifiers to indicate the Lylo of Lisa vsrlsl,fa belnv. lntroJuc?d. The v;xv.u (Ss?tav.?r) Ly?r. f. u.--Hd in 511 (In ax?#s??I as ILL tILts cILLLI(ar. The most common complaint heard from the ?casuLl observer" of the PI./CV I?np,unp,c- concnrns Lhr `s.' cf fiXFfl. nit. L1L?, sad `C'S jn.t.'sd of - 70 - I)rrECEI. BOOLEAN. TgUE. and FALSE (the former being the nanes used in IL?CS for the latter). An actual user of PL?Cv is going to have to learn the PL?CS names anyway. and it would only confuse matters if ilgoodfl names were used in juet the prvdicate calculus part of the language. Then. not only wou?d the user have to learn two different names for each concept5 but he would have to keep straight when to use which name. One concession was uade on the consistency issue. In rL?CV. a string of operanda connected by ralational operatora. for cumple: A <-- B < C is considered to be an abbreviation for what is obviously meants (A <: B) & (1 < Unfortunately. the expression A <- 1 < C has another meaning in PL?CSa co:pare A and 1 yielding a BIT value. convert (using the legendary PLIX conversion ulex) the BIT value to FIXED. and compare the result to C. Because Boolean expressions of this nsture are used so frequently in proofs. cons?derati?ns of legibiltty an? brevity outweighel those of con- sistency. I an bewildered by the fact that this feature has not found its way inn any of the na?or nodern programming languages. For consistency with PL?CS. rhe syntax of PL/CV is sprinkled liberally with senicolons. The keywords PROOF and QED are followed by se:icolons because DO and END are followed by senicolons in PL?CS. The syntax chosen for a conclusion line. inherited from PLICVl. isa P BY . Some critics of PL/CVl complained about the large number of rule names that bad to be remembered. For this reason. in PL?CV. all the lines using Introduction rules use the rule name INTRO. The Proof Checker can deter--H --H 71 --H Mine which introduction rule is being used from the main connective of the conclusion. In retrospect, it is not clear bow wise this decision was. The overloading 0 the name INTRO decreases the legibility of the kind of proofs discussed in section 3.13. The exact nature of depends on which rule is being used. It consists of some hints to the Proof Checker about how the rule is being applied. and what its hypotheses are. The goals of legibility and efficiency demanded that some justification be present. but the goal of brevity required that it be kept to 5 bare minimum. The justification for each rule includes the minimum amount of infornation needed to deduce the hypotheses of the rule from the cdnclu- sion. For example. the SOME Introduction rule has the fornat: SOME x FIXED. P BY INTRO. t; The proof checker substitutes t for x in P to deduce the hypothesis of this rule. In PL?CVl. the justification included a reference to the line St which each of the hypotheses could be found. This situtation was intoler- able. For some PL?CV rules. the user must include one or more hypotheses 55 part of the justification. but he need never indicate where Lbose lines cen be found. ilow the Proof Checker locates the hypotheses is explained in section 3.12. 3.7 b(?rrp If a hypothesis of a rule is lengthy. it can be aunoying to be required to write it several times: once when the formula is assumed or proved. and then each time it is used as a hypothesis to a later rule. To ease this burden. a macro facility is provided. At various points in the - 72 syntax. a user can put a label on a formula. as in' L: JLLt X FIXD. X?2 >-- 0 flY INTRO. Subsequently. whenever the idcntifier L is used. it is expanded to the quantified formula. The 13icr use of label-mac:os ?a the shortening of justifications. but they may appear anywhere a formula can appear0 a. in: L --> K*a2+l > I fly INTRO. A psraw?tcrized macro facility is also provided, For example. one can write: FOR (X. Y) FiXED DElINE DivlDEs(x. Y) SOHL' M FlXED. N'X If one later writes. for exanplc. DIYiDES(A. BaA). it is expanded to the fornula: SONE Ii FIXED. NeA BaA Experience has shown this feature to be vital for the ?ericua user of lL!cv. Unlike 11.11 (?) or PL/C (72) macrca. which 5TC add-cns implemented with a preprocessor0 the macro facility cf PL?cv in built into the l0n?.a?v. Nacro ?slls sr? par? f tha ayntsX of the lnnguasn. fley are allowed only where formulas or expressions are allowed. and they are type-checked, Yacro substitution. are performed on parae trees. not input text. For example. in the expansion of DlVlOES(A+lO, lOsA). parenthesee are implicitly sdd?dI ?t?Lt). fl?(A It)) IU'A and in th? c?Ianslun of DlVII)ES(N, 2aN). bun varishles are lmpIicitly ronsm.fli - 73 --H ?OR (I. y) FIXED DEFINE DIVIDES(?. T) SONE M FIXED. M*X FOR P FIXED DEFINE PRIlE(P) P>l & ALL D FIXED. (D>l ? DIvIflES(D. F? --? FOR (F. x) FIXED DEFINE PRlN&ACTog(F. x) PRIME(P) ? DlVIDES(P. x); FOR (p X) FIXED DEFINE c?F?TESTPglMZJACTOR(?. I) PRlNI?'AcT'?R(?. x) ` ALL PI FIXED. (?RlNE?AcToE(Pl. X) --? ? Q BY 1NT?o; But this cyntal sesIe backwards. In o+atheaatics books. the theoree aiwayc co.es first and je followed by the proof. The following cyntax suggested iteelfs I -? Q BY INTMO. PROOF: ASSUME I; The above syntax ic uced in lL?cv. In this syntax. the proof block is con- sidered to be pert of the justification. Experience has.shown this synLal to be iore natural to use than the proof-Lhen-theorc? style of A?L?cv. Another edvantage of this syntax is Lhnt if tho ASSUNE line is onitted. u1?at Li?e o+iasing li??c, should ho can b? tcduccd by the l?r??f Chc?Lcr. Therefore. all of the ASSUME lines that begin proof blocks are opLional in rL?cv. The theorem-before-proof syntax requires that the definition of eccessibility be nodified so that the for.ula I --> Q cannot be acceased fro. within its proof. Another consequence of thia syntax is that proof blocks cannot be shared. fl?is restriction Is not a harsh ou?. because the first tiwo the proof block is written. it can be used to prove I > Q. If the proof bloc? is needed again. the second block can contain a aingle instance of the r6 - or P Q R rigure 3.16 The parse tree for PIQIa lmplica?tion Elimination rule rather tha'a a copy of the first block. The Or Elimination rule baa two proof block. as hynotheses. eatber than requiring two adjacent proof blocks as in: I BY OREL. PIQ. ?O( F ASSL? P? ?OOF AS?U?? Q. ? BY the syntax ?as cleaned up and th-. name of the rule changed to more closely corresnond to informal msthematical use. The following syn?ex is used in PL?CV: I lY CASES. PIQ PPOOP; CASE P; I BY ... CASE Q a BY Unlike the ASSUM? line. the CASE line is not optional. for reasons explained in section 3.13. Another extension of the CASES rule involves the way the disjunction 7A' --H (mom) operator is parsed. In mos computer lanaunacs. every operator 18 assigned an "associativity.' For example. in PLIl. addition is "left associative." meaning that A+B+C is parsed as (A+B)+C whereas exponentia- tion is "right associative." meaning that AtaBsaC is parsed a. Ata(BasC). In PLICY. diajunction is neither left nor right associstive; it is called a "multiary" operator. The expreasion PIqIR is not paraed as (PIq)Ift or as Pj(QjR); the parse tree built for this expression is shown in Figure 3.16. When using the Or Elimination rule. one proof block is given for each operand of the diajunction. as shown in the following example: ? BY CASES. Q I (RIB) PPOOE; CASE Q; P BY CASE I I si P BY ... CASE T; P BY ... QED; 3.9 Opliflera ?????? Every variabla in a PLICS program must o+?e declare?. This rentric- tion was included in PLICY. and fits into the language quite nicely. There are three kinds of variables in PLICY: program variables. bound variables. and logic variables. Program variablea are declared by the PLICS DECLARE sLatemeL?t. bouud variables ar de?tared by t?.: q??nti1 Ltr to wi?icb t?ey are bound. and logic variables are declared by an AIBITRARY or CHOOSE lice. PLICY uses ALCOL scope rules t6i i. w1?tr? the block? ued to dt?t'rmi??e variable acop?s are proof bloc?s and ?uantifj?d ?xprC??io?s. - 78 From the point of view of the implcmentation. here is how variable scope. are bandIed. Every time a declaration is processed. a new variable is created. associated with the current block. and stored in a symbol table. Given ALGOL scope rules. it is permissible to have different vari- ables with the same name; the implementation keeps track the. by assignina them different internal names. When an identifier is parsed. snd there is more than one variable with that name. the identifier is taken to denots the variable declared in the innermost block. None of the above is particularly interesting; block-structured sym- bols tables (36) have,been used in compilers for years. What is interest- ing is that the AILOL scope rules automatically enforce one of the acces- sibility conditions of APL?Cv. Suppose a line L in a proof block beaded by an 5A??ITRA&Y v" needs a hypothesis PI that contains the variable v. The line L cannot possibly use a formula from outside the proof block for a hypothesis. The reason it cannot is that the assignation of internal name. to lo?'ic variables perforned by the symbol table routines is precisely the renaming step of the construction that converts APL?cv tree. to Natural Deduction trees. Even if there is an assertion P2 outside the block that has the same external appearance as P1. the identifier v in P2 will be associated with a variable that is different from the variable associated with the identifier v in ?1 Because the two variables will have different internal names. the internal representation of P2 will be different from that of P1. and 52 will not be usable as a hypothesis. Nere is the PL?cv ALL Introduction rule; - 79 AlL I FIXI?. P BY inflO. lXoOfr; ARBITWY v FIXED; P(vllx) BY a. it has been o+odified so far. The user La free to use any variable be Likes on the AILBITIARY line. But no power is lost in the logic if I and v are roquirad to have the same name. Any PL?Cv proof that docs not obey thia reatriction can be converted to one that doe. by following these atepsa (1) Rename every bound sod logic vsriable in the proof so that no vari- able ia ever uaed twice. (2) Find every ALL Introduction proof block and renane the logic vari- able to agree with the corresponJin?' quantificr. Each logic variable introduced by the And Introduction rule is required to have the same as it. corresponding buund variable so that the Proof Checker can always deduce what the ARBITRARY line should be. The AnITRAR? line ia an optional part of the syntax; if one is pre.cnt. the Proof Checker simply makes sure what is given matches what should be there. The restriction i. a bit confusing to novice.. who have tr?uble keeping track of the difference between the logic variable and the bound variable. In retrospect it probably u?uld have been better to h?e ttc name of the logic variable default to the name of the bound variable if the ARBITRARY line is omitted. but if an ARBITRARY line is given. allow it to declare any name. liowever. each degree of freedom allowed in the syn- tax increase. the complexity of the Proof Checker. so - SOME x. ? CHO'O?E(vV11x1 0 ASSUME Q Q SOME x. P CHOOSB v ASSUME P(vlli? Q (a) (b) lisure 3.17 ?emovins a proof block fros the SOME slisination rule 3.10 so?? F1?in?tion The ?ont substantial difference between PL?cy and APL?cv in in the SOME eliminstion rule. Here ia the rule as modified so far: Q BY SOMEL P::OoF; Ci:OOS? v FIXED; ASSItE p(v#i); Q BY ... where the formula: SOME 1 FIXED. P is a hypothesis. Experience with PL?cv1 indicate? that thin rule wee annoying to use. becaune the formula q must be written twice. The SOME Elimin?tjon r?ie d'cidcd upon for PL?cv does not us? a proof block. and the luslifjer and assumption are combined into a single line. It in sin- ply: 81 - CHOOSE v FIXED uHHIZ P(vllx)? The formula 5011K I FIXED. P lust be accessible to the CHOOSE line. be scope of the variable v begins at the CHOOSE line and ends at the end of the innermost block containing the CHOOSE line. To show that this abbreviated rule is equivalent to the rule that uses a proof block. a construction will be given to convert proofs using each rule to proofs using the other rule. Figure 3.l?a shows a proof tree using the block rule. and Figure 3.l7b shows how it is changed to use the abbreviated rule. Assume without loss of generality that the free variables in the tree in (a) have been r?nsmed so that there are no occurrences of the variable v outside of V1. It should be clear that all the accessibility paths in (a) have correspond--H ins paths in (b). The only possible problem is a path routed up the rain branch of (a) being stopped by the "CHOOSE v" node inserted on that branch in (b). But only paths to formulas containing v are stopped. and the only such formulas are in VI. Figure 3.lSa shows a proof tree that uses the abbreviated rule. The rule will be used somewhere on the main branch of the entire proof. or of some proof block. Let Q be the terminus of that branch. The corresponding proof using a proof block is in Figure 3.lSb. Every accessibility path in (a) has a corrtspondin? path n (b). Since the terminus of the main branch of the subproof is still Q. whatever rule is being used in (a) is still being used properly in (b). But recall Lherc is a restriction on the use of the APL?CV 011K Elimination tulel tb? formula Q cennut contain v. We must vcrify that this reatriction is enforced in (b). There is no problem as lon? as the maIn br,?ch alown ii. (a) I.t of a proof blork. Tim Q I. eith?r o+O?5 - 82 - SOnE I. P SOM? x. P ?siuc??ospsv,v,?j O\'?sCuli?O'Sp(Kvv,xJ Q q Q (a) (b) Figure 3?lS Addin a proof block to the SOflE Elisination rule or a subforsuls of the conclusion of the rule being used. which. by the scope rules. cannot contain any occurrences of v. T?ere is a slight proble. in the inplenented ay?tea if Q La the final conclusion of the proof. For example. one could prove the forsula A>0 by: i > G BY Axim; SO. X F?xD. Z > 0 Sit lNTgO. I; CU.OO?E A ?IXtD WHERE A ? 0; A > 0; This fornula could not be proved in APL?Cv. Realize that FL?cv formulas with free variables are not implicitly universally quantifLed; the above is not a proof of ALL A FIXED. A>O. However. it is somewhat anomalous. One way of solving the problem would be to require that the conclusion of a proof be free of CHOOSE variablee. A cleaner solution would be to enclose the entire proof in a proof block. by making the syntax for a proof of P be: - 83 - P BY rRooPt P BY ... QED. 3.11 Ar.rb?pr?c TnF The pure predicate calculus and rules for proarammins constructs are not sufficient to prove very many interenting facts about programag it is also nL'cesUry to be able to reason about the data domain. The aRITI rule is used for this purpose in PL?Cy. The simplest form of the rule is: P BY Axini. Q1. ??n3 where P can be derived from Q1. ?2?? Qo usina a specified set of arith- metic axioms. Further discussion of the ARIflI rule is beyond the scope ot this thesis. The interested reader is referred to the PL?cv Reference Ilanual (171 for a complete description of this rule. Chan (141 discusses bow this rule is implemented. 3.12 i-?at6 C. in the previous sections. we saw how the use of ALGOL scope rults in PL?cv frees us from worrying about the annoying little restrictions in &PL?cv. that are usually (erroneously) ignored anyway. To completely validate a proof. it is only necessary to check that: (I) the hypotheses and conclusion of the rules properly math each other. and (2) every proof block containing the hypothesis of a rule also contains the conclusion. Proof Local Context V-code V-code Checker Interpreter $ T Error Error Nsss?ges Nessages Figure 3.19 The organization of t?e Proof Checker These conditions are checked with the help of an automaton called a ?V-:schice.1 In the memory of the V-machine is a set of formulae. which is called the 1Assertion Tehle.? Initially the Assertion Table is empty. The input to the V-machine is a sequence of commands. called V-code. which are instructions to the V-machine for the manipulation of the Assertion Tahie. Here is a list of the V-code instructions used to check predicate calculus prooLs. and the actions they specify: PPOCLAI?? P Add P to the Assertion Table. REQUIltE P If P is not in the Assertion Table. report and error. OPEN Push a copy of the Assertion Table onto a stack. CLOSE iteplace the Assertion Table by the top of the stack and pop the stack. It is assumed that OPEN and CLOSE instructions will he properly nested so that the stack will not underfiow. An interpreter for V-machine described shove can o+?e implemented using the same ts?Int?ues us?d tu 1m?i.?s???t sywbut tables in ian?uages witi block atructurs (36J An nh"wn in ris??r? ?.l?. ha Pr.,?f Chackar Is ai?I,I? l?il 1w - 5? reversal or?er ?igure 3.20 V-code generation for a proof bloc? ?odules. Th? Local Context Checker (LCC) in?uts the proof and generaten V-code. in much the o+ame way a compiler wuuld input a progrsi sod generate machine language. The generated V-code is sent to the V-ccde Interpreter. which is a software implementation of a V-machine. To simplify the dis- cuasion. we will for the time being assume that as soon as a V-code instruction is generated by the LCC it is executed by the V-code Inter preter. (In actuality. all the V-code is generated. and then it is sent to the V-code Interpreter. The reason for this two-pass operation will be explained in Chnpter A.) Appropriate V-code is generated by the LCC so that the following invarlant is maintained: when the LCC is at rine p of the proof. the Assertion Table consists of exactly the set of fornulas accessible to line The invariant is quite easy to maintain. P?call that the sequential processing of a PL?CV proof is equivalent to the traversal of the APL?CV tree. The LCC can be described as a recursive procedure whuse input is an APL?CV tree. The nodes of the nain branch are processed top d??n. from the root to the terminus. If the nude is an ASSuxF. P node. a PROCLAIM P instruction Is generated. If the node is the conclusion Q of an inference rul?. f?'r c?ch Iy??ti?esLa ?g ??.. ruir. the jeat re?( lun k'I?L'I?tt i'1 is send-al. te IL ha: r i. a.' .`a..l).l It. `). ?),s I':'?x':A)?i () in.: tice is generated so tiLat q will ba sdcI?tI to tl? sat o? accoasibla formu- las. Wkn a ptuof block is encountered (ace Figure 3.20). an OPLM instruc- tion La tenerated to save the state of the Asacrtion Table at point a. Then the V-code senerator is called recursively on the eubtraa contsined in the proof block. Upon return. the Assertion Table will contain the set 0 formulas accessible from the terminus of the proof block. Since the set of fornulas accessible from point a is the same as the set accessible from point b. a CLOSE instruction is generated to rcstore the Assertion Table to the etato it we. in at loint a. The above translates quite simply into a tecursiva descent paraing al?orithn. For example. the Implication Introduction rule is shown in Figure 3.21e. and tie generst?d V-code is in Figure 3.21b. Mute the PitocLAlit P -> Q instruction is generated after the CLOSE instruction because the formula P > Q is not accessible from soy of the lines within Ebe proof block. 3.13 A.rp??r R,1?. ni Ahr?u?ir.pn. The V-nsct:ine described in the previous section is quite easy to implement. ?owever. the PLICY Proof Checker uses a more powerful V- iachine. In particular. the gEQUIRE P i?struction baa been suamented so that it will succeed if F is in the Assertion Table. or if it is deducible rom tha formulas in the table. Precisely what is meant by 1,deducible0 is the subject of Chapter 7. For the time being. note that the rules And Introduction. And Elimination. Or Elimination. Implication Elimination. `lot Elimioation. and False Elimination are nautomatic.5 in the sense that if all the b9pothesea to one of these rules have been oparands of PROCLAIM 8? - "? q IV Inmo5 PROOF; EAssuNF. P;) Q DV ... Qt'n o:'r.N PROCLAiM ?(V-coda recursiwaly generated o+ for the proof bloc?) n:;qu:R:t Q CLu?E PROCLAiM ? s? Q (a) Figure 3.21 The liplicetion introduction rule and the generated V-code instructions. than a REQUiRD ? instruction. ?here P is the conclusion 0 Lhe rule. ujil succeed. 1 e formula is simply written without any justification: then the following V-codes RFA?I:Rr: P PROCLAiM ? is generated. The effect of the above V-code is to check that P follows froi the application of automatic rules to formulas already in the Asse? tion Table. and then to add P to the Assertion Table so that subsequent rules (automatic or otherwise) can use it as a hypothesis. Therefore. justification syntax for the automatic rules is unneces- sary. and. in an effort to reduce the complexity of the Proof Checker. and none was provided. In retrospect. this omission appears to have been bad idea. There are several reasons why one might want to write. for example: Q DV iMPEL P P > even though: and sometimes nothing at all. is sufficient. The automatic rules are 88 - fairly powerful. end iL is n?t always clear to a bunen reader bow a par ticular line is to be derived, even though it is perfectly clear to tbe Proof Checker. For this reason. the inclusion of proof linen or justifica- ticns th?t are. strictly speaking. unnecessary is often desirable. And even if the unnecesUry syntax were never used in practice. its existence would simplify the description and teaching of the system. Let us reconsider the V-code generated for the Implication introduc- tion rule. Civen the autom?tic rules. it is not necessary for Q to appear as the last line of the proof block; it is only necessary for Q to be dedo--H cible from the formulas that are acce?aible to the end of the proof block. Therefore. It is perfectly plausible to have a proof of the form: P -) Q BY INTRO. P?OCF; ?ED; as long as the V-code in Figure 3.21b is successfully executed. that is. as long aa Q is deducible from P and the other formulas accessible from the QED. The above proof is silly. and can be abbreviated as: P --> Q BY INTRO; for the same V-code will be generated. Note the use of a semicolon to mark the end of the justification. If the proof of Q is a one-liner: P --> Q BY iNThO5 PgO3?; Q BY ; QED; and Q is a large formula. it can be unpleasant to have to write Q twice. Therefore. the above proof can be abbreviated: P --> Q BY I?TRO ; 8, ? o+? --`. (a a? (5 =? p))) BT INThO. PROOF; ASSUME P; Q --? (a --> (s --> p)) zv INTRO. PROOF; ASSUME Q; R --> (s --> P) BY INTRO. P?OOF; ASSUME a; 5 -> P BY iNTRO. PROOF; ASSUME 5; QED; QED; QED; QED; Figure 3.22 An example of deeply nested proof blocks no matter how complex qjs By iNTRO. CASES. P?Q. PROOFt QED; or just: PjQ => QIP BY INTRO. CASES. PjQ; Becsuse the commutativity of diajunction ta an automatic rule. the proof: -`0 PIQ --? QIP BY INTRO. PROOF; aSSU? PIQ; QIP BY CASES. ?iQ. CASE P; CASE Q; PIQ. QED; (a) PIQ --? QIP BY INYBO. CASES. PIq. ?kOOF; CASE P; CASE Q? QED; ligure 3.13 abbreviating a proof PiQ --? qiP BY INTgO; is also sufficient. The generation of V-code for abbreviated proofs may appear to bs difficult. but it is actually a simple exercise in recursive programming. The LCC contains a recuraive routine called JUSTIFY(P) that reads the jus--H tilication for P and generates the appropriate V-code. That is. after the LCC has read: P BY it calls JUSTIFY vith P as a patameter to read the rest of the justifica- tion. Here is hnv JUSTIFY operates. First of all. it reads a token fro. the input. According to the PL,CV syntax. that token must be the name of a rule of inference. As an illustration. suppose the rule is INTRO. Then JUSTIFY uses the main connective of the formula P to detar.ine which introduction rule is being used. If. for example. P has the form Q :? g? Implication Introduction is being used. Here is bow JUSTIFY handles Implication Introduction. No matter ?har the justification is. the generated V-coda must begin vith the 91 --H header: OPEN PROCLAIK Q and end with the Lrailer: REQUIRE 5 CLOSE What V-code is generated between the header and the trailer depends on what appears in the justification. First JUSTIFf generates the header; what happens next depends on the next token in the input. If the token is a sesicolon. there is no sore justification. so the trailer ia generated and JUSTIFY returns. The only other token allowed by tho syntax at this point is a coasa. which is usej to injiceta that there is sore justification. If a coena is found. the token T after the cornus. is peeked at but nut actually rend. (That is. the token will be available to subsequent read operations.) If T is PROOF. the user has supplied a proof block. The PROCLAIN Q corresponding to the optional ASSU?E Q has already been generated as Parr of the header; the only processing perforsed on a ASSL?KE line followicg the PROOF is to check that Q is the foraula on U?at line. Next. a routine is called to parse and generate V-code for the contents of the proof block. Note that during the course of the V-code generation for the proof block. JUSTIFY can be called many tiuea; it is a `,?rv recursive routine. A proof block always ends the justification; after the proof block has been read and V-code generated. the trailer is generated and JUSTIFY returns. If the token T is not PROOF. the remaining justification is part of an ?bbreviation. In that case. JUSTIFY(R) is called recuraively to read and and generate V-Code for the resaining justification. If. for example. - 92 he rest of the justification begins with the rule rams INThO. mbleh introduction rule is applied depends on the main connective of I. liter the recursive call JUSTIFY(s) returns. the trailer is senerated. and Y?STlFy(p) returns. 3.14 Su???sr?n. ?or ????? I an rather pleased with the abbreviati?n rules. No matter how powerful the automatic rulea are made. there will always be proofs that the autocatic r??les can almost. but not quite. find. Often the abbrewia--H tion rules can be used to ?ketcb an outline of the proof. and the autonatic rules will fill in the details. I would like to see more work done on the design of flexible ?juatification languages." in which direc- tions that eutcnated theorem provers ahould proceed can be expressed. One such approach are the "tacticala" of LCF (32). The abbreviation rules also encourage a kind of top-down refinement style of proofs reeiniscent of structured programming. One way of seeing this influence is by looking at two examples of nonstructured proofs. The PL?cv SOME Introduction rule is: SONE 1 FIXED. P BY INTRO. t; where F[tflx) is a hypothesia. If P(tilx) cannot be obtained from sutonatic rules. a proof of p(t#x) must precede the SOME Introduction line. This is an example of the proof-before-theoram style of APL?cv that the PL?cv syntax was designed to avoid. One improvement would be to extend the syntax to allow: SONE x FlXED. r fly ININO. t. ; in csae? wI'?ac a on?-iis'n j.L?fi?utiut i. pussibie. - 93 - The follovina patLern Occure quite often in PL,C7 proofs: Io. PROOF; CASE X <: 0; The above is another example of the proof-before-theorem style. The ?roof of 1<0 1>0 is really a pbrt of the proof of P. end belongs somewhere after P is mentioned. Some ayntax ia needed to be able to forasily say. 1P BY CASES. 1<0 I 1>0 (which is true by ARITh). PROOF...? The abbreviation rule. allow one to move away from the practice of writing formal proofs. Instead of demonstrating that a formal proof exist. by exhibiting one. a description of how a proof can be obtained is given. We shall return to this idea in section 8.3. CItAPTER ? ______ mL Lu&wn TI?e priciry purpose of the PLICY system is to check proofs of pro--H grans. But to understand how the system checks proofs of prograls. one lust have an understanding of just what is meant by a proof of 5 progran. A progra, can be defined as a collection of "points" and "atomic actions." Out point is singled out as the "start?' of the program; another is sir.?led out as the "rinis." The execution of the program consists of the execution of a seq?ence of atomic actions. Between the execution of two atonic actions. we say thet control is at some "point" in the program. ?nenever control is at some point other than the finis. there is always a unique attric action that will be executed next. T?e state of a ?rogrsm is defined to be a function that maps vari- ables of the program to cleir values. There are two kinds of atomic actionsI (I) Unconditional actions. in which a function is applied to the state to obtain a new state. and control is transferred to the (lexically) next point in the program. (2) Conditional actions. in which a new point is selected on the bssi? of s?ne function of the state. snd control is transferred to that point. A special case of (2) is the atomic action that always transfers control to the same point. independent of the state. For every point in the program. there is a corresponding place in the text of the program. There is op harm in being sloppy about distin--H - 94 - a q 17 A > I ThEN DO; ?a b a? ?(AX :- A; ?a c a? END; ELSE iD; ?* d *? ?tAX I I e t? END; ?t f a? Figure 4.1 A program fragment with its points labeled guishing places from points. In this chapter. points in programs will be Labeled with lower case letters enclosed in comment brackets. For exam- ple. ?iaure 4.1 contains a program fragment with its points labeled. The atomic actions that follow points a through 5 in Figure 4.1 are: (a) Evsluate the Boolesn expression A > g. If the result is `l'B. transfer control to point b. and if the result is .O'Z. tranater control to point d. (b) Evsluste the expression A and store the value in XAX. (Control is implicitly transferred to point c. the point that lexically follows point b.) (c) Transfer control to point f. (d) Evaluate the expression 1 and store the value in MAX. (Control is implicitly transferred to point a. the point that lexically follows point d.) (a) Trans?or control to point f. Civen a program. an assertion is defined to be an ordered pair (P. q). where P is a formula. nnd q is a point in the program. The for- mula P will in general contain variables from the program. Validity can be defined for assertions in a fashion sinilar to the way validity is defined in mathematical logic (3l? for formulas. A netructurem is given that assigns meanings to all the operators. con- stants. and function symbols that can appear in formulas. The a:ructure - 96 IF A 0 ThEN DO? ?t q aigure ?.2 A program fragment cam be used to determine the validity of any formula that coetains no freo variables. A state a is said to "satiaf? a formula P whenever substitut- ing for every free variable v in P the value of v specified by a yields 0 valid for?u'.s. The formula ? is defined to be valid whenever every state O satisfies P. When coutrol is at a particular point q in the program. some states cannot occur. For exanple. at point q in the program fragment in Figure 4.2 a state in which the valuc of the variable A is xero is impossible. An assertion (P. q) is defined to be valid whenever P satisfies all the states 5 that are possible when control is at point q. For example. given the program fragment in Figure 4.2. (A --H? 0. q) is a valid assertion. For each programming construct. there are proof rules of the form: (P1. q1). (P2. q2). ??n q0) ? (R. a) vhere for s?me nonne?stive n. q1. qqn and a are points in the pro- gram that are located in the program relative to so instance of the con- struct. The proof rules are actually theorems about the semantics of the progrsmmLog iao?us?c. Tl?sc tl?cort?ms stale that if the hypotheses of the rule are all valid assertions. then the conclusion of the rule o+ust be a valid assertion as well. For example. the proof rules for the IF state- ,?j?t ar? .l?wn in F1.8ure 4.3. wI??t t5 to v.?? 5 ptt)v.rflm. 1f a 5 tIts atnit of .0 55..?rI `to of tIts f.?rst (1?. . I. s5.om...Ii II's itl"s h?Ing 1* a IF fl Turn DO; /* b *? c END; ELSE DO; /t d a? END; ?a f s? (P. a) ? (?. b) (P. a) ? (r. d) ? (n, b) ? (?B. d) (r. c). (r. e) ? (P. f) Figure 4.3 Proo2 Aules for the iF statement that the proarsa will only be begun in atates that satisfy P. Usina (?? a) as a starting point. the proof rules can be used to derive other assertions. The usual goal is to derive some asaertion (?. f). where f i? the finis of the program. that aaya what the program is supposed to do. Howe,,er. there is another aet 0 `required" saaertiona that must be proved. For example. given the assignment statement: A : the assertion (c 0. r) vust be proved to demonstrate that when control reaches ?oint r the progr?m does noL immediately short. That (r. q) La one of these required assertions will be designated by writing: (r. q) ? The above can be thought of as a proof rule that does not give back a valid assertion in exchange for being provided with one. it simply must be satisfied for tie overall proof to bc corr&ct. Ti?crn si elh0 soiflo ri?i?iir4? n.s?rtions assoristed with luu?s. ?or every loop. a )oop invarient P ?`?st h? sp?rifj.d. ?omp of the proof r..i.s -`a- a s? (P. a) ? DO WUIL(B); ? (5. b) ?* b s? ? (R. b) (5. c) ? END; ? (5. d) ?e d a? ? (--H1. d) rigura 4.4 Some of the proof rule. for the WHILt loop for the W?ILE loop are shown in Figure 4.4. It Is somewhat abusive to refer to the rules involving 5 as proof rules. It is not. for example. a theorem that (5. b) is a valid assertion. The actual proof rule is closer to: (5. a). E(r. b) ? (5. c)1 ? (5. d) in which ?ne `1cd?ction is u.?d as a hy??thceis to nn?thcr dtduction. But the proot checker vcrifice that the actual proof rule has been properly used by checking the rules in Figure 4.4. These rules are based on a model in which before the loop body is executed. the state is tested to see if it satisfies 5. and if it does not the program aborte. When writing IL/CY proofs of programs. one dons not use the notation (5. q) to write assertions. Instead. one writes the formula 5 at the point q in the program. The formula it may be written at point a. (masnine the assertion (1..) is to be proved) if the formulas ?l ?2 5n each hsvc been written at q1. q2. qn respectively. and if ??l q1). ??2 q2). ?5n q?) ? (1. a) is a proof rule. Because the proof rules all have the property that for each i in (1 ... DI. point q1 lexically precedes the point 5 in the pro--H gram. there are no problems with circularity. Once the formulas 11. 12. . have been written at point 5. predicate calculus proofs of - 9, - othor formulas ?l eSk that use R1. 1Mm at hy??theses can b. written at point at for each I in (I ... k). (Si a) is a valid a.sertion. 4.2 Sh?ei?.n? Occasionally. after a program has been proved correct it is compiled and executed. The effort ro?uired to produce a documcnt that has beca certified to be free of human errors (nut counting the humans thnt pro- duced the prugrammin? logic. the ?rouf Checker. the mechino on which the Proof Checker is run. etc.) will have been wasted if a human must then modify this document to obtain a program acceptable to a compiler. There are two solutions to this problem: (I) design the input to the Proof Checker so that it is also acceptable to the cuml?iler. or (2) have the Proof Checker produce from the proof a program that is acceptable to the compiler. In hindsight solution (2) is superior. but the Proof Checker was designed using solution (1). All the assertions and predicate calculus proofs in the input must be "shielded" from the compiler by the special comrent brackets ?a? and t? The syntax of rL/Cv does not specify the positions of the shielding brackets. Instead. it is defined assuming different colors of ink are available. so thst programs can be written in black ink. and as?crtions and proofs can be written in red ink. The structure representing a token that is returned by the scanner contains a field indicating its color. Of course in reality. only one color of ink is available. The brasket ?s? can be read ?switch to red ink.5 After reading this bracket. the scanner returns red tokens. until it reads a a/ which can be read 5return to black - loo - ink." (As ?iacuased in sectio:t 4.9. the syntax uses 5 third color of ink. which is introduced by he bracket ?e: .) Thus. essertions ?nd proofs can be shielded on a line-by-line basis. or as a block. The Local Context Checker uses the same linkage to its scanner found in most language translators (34). There is a global variable that con- tains the "current synbol." A call to the routine SCAN has the effect of reading the next symbol fr?m the input and storing it in the global vari- able. where it can be inspected by the various parsing routines. There is another global variable. SHlELDgEQUlRED. that can hold a shielding color or ?. Just before the scanner replaces the current symbol. if SnlELDJLEQUltED is not ga?. the current symbol is tested to see if its color natches SNIgLD?gEQUlgED. If not. an error Is reported and a flag is at that prevents further messages until the color of the tokens is again syoctr'?ni:ted with SHllLD?REQUlRF?. Therefore. the parser need not explicitly test each symbol it reads to see if it has the proper color. When it reads the first symbol of a construct that must be conpietely shielded. it sets the value of SUlELDJ?EQtlkE1) to "red.5 When it reads the first symbol that should not be shielded. it sets S11IfLD?REQUlgED back to "black." In the few cases where delicate token-by-token testing nuat be performed. SitIELDJtEQUlftED is set to ?. Shielding brackets are annoying both to write and read. There is only one place in the syntax whtre the color of the tokens involved is necessary to avoid ambiguity. Be?auae of the questionable decision made by the deei?ners of PLI! to use the same symbol to denote both assignment and equality. the color of the tok?ne is needed to determine whether: 101 - n ? A := 0 q s? ?igure 4.? A proeral fragment A a Ba is a. assignment statement or an assertion. In the p.L?cv examples in this thesis. all shielding brackets have been omitted. and :a is used to denote assignment. 4.3 Accessjhiijrv The proof system described so far is a subse: of PLICV that has all the power of PL?Cv. but is not as convenient to use. As an exa:ple. con- sider the proof frsgment in Figure 4.5. Suppose the assertion (B ? 0. c) is required as a hypothesis to a proof rule. bow given that (3 0. p) bae been established as a valid assertion. a proof rule for the assignment statement can be used to establish (a ? 0. q). But recall what it means for (B > 0. p) to be a valid assertion: whtnever c?ntrol is at point p. the variable B contains a positive value. Noy the only way that control can reach point q is by way of point p. and along the way the variable I is not changed. Therefore. whenever control is at point q. I nust still be positive. so that (I ? 0. q) must be a valid assertion. We say tiat the ssaertion (B ) 0. p) is haccessibleiL to the point q. The following definitions forsaltie the Lonce?t of accessibility as used in programs. Recall that in s?ction 3.3. accessibility was defined for predicate calculus proofs. In the l'?ic as dtf ined by Constable and O?Doniell (18). there is actually only one concept of sccrssibility. but - 102 when discussing the Proof Checker it is useful to have rwo seterete con cept.. ??l?o+ 4.1. A sequence of points p0. p?n ?? defined to be an execution path from Po to ?n whenever: (I) it is possible during the ex&cution of a program for control to reach p0. and (2) the execution of the progral thereafter consists of the atoflic actions AAi. AAAA? such that for all i in (I ... n). after AAi has been performed. control is St The path is said to pass through a point q whene?er q is ?i for some i in (I ... n-lI. The path is ssid to pass through an atomic ection B if B is AAj for ?o?t i in tI ... ol. ?or any point p. there is always e null exe- cution path fro: p to p that passes through no points. In 5 straight line program there will be exactly one execution path from p to q. but in a program that contains conditional actions there will in aeneral be many execution paths from p to q. n??'?.rinn 4.2. A "simple execution path" from point p to point q is an execution p?th from p to q that does not pass through point p. fl.fi?,'ri?n 4.3. A point p is said to `dominate" 5 point q whenever every executio? path from the start of the program to q passes through p. fl?''?,-r;p 4.4. An assertion (P, p) is "accessible" to point q when--H ever p and q are not the Ume point. p dominates q. and no simple execu- tion path from p to q passes through sn stonic action that modifies a ?ariable in P. The notetiom Aq is used to denote tbe set of all essertions eccesaible to q. The definitio? of eccessibility was carefully constructed so that the following theorem holds. - 103 - m'lttgS1 4??, If (P, p) is a valid sasertion acceasible to point q. then (P. q) is a valid assertion. Pr?nf Suppose (P. p) is a ?alid asaertion acceaaible to point q. and control ja at point q. We must show that the state of the program at point q satisfies p. Control reached q alon: an ex?cutioa path from the beginning of the program. Seceuse p dominates q. that path must pasa through p at lesat once. If the path is cut the last time it passea throu?h p. the re?ult will be a simple execution p?th from p to q. Becauae (P. p) ja a valid assertion. the state of the program whs? control was at point p satisfied P. Since no atomic action along the simple path from p to q can modify any variable in P. the state of the program when control reachee Q muat also satisfy P. (] If a point p dominates a point q in a PL?cs prpgram. p muat lexi--H cally precede q. Given this fact and Theorem `.5. the requireLents on what conatitutea a proof can be relaxed. The proof rule: (P1. q1). (P2. q2). ??n q?) ? (a, a) can be used to introduce the formula R at point a in the program. if has been written at point ??. or if some assertion ??i ti) is accessible to ??. Likewise. it an assertion (P. t) is accessible to point a, ? can be used as 5 hypothesis in a predicate calculus proof appearing at 5. flefinir.nn 4.6. The union of the aeta of assertions accessible to point a, introduced St a by a proof rule for a programming constru?t. and proved in a predicate cslculua proof at a is called the set of formulas flknowan at a. and will be denoted K5. It is important to note that accessibility is a luxury; the proof rules are sufficiently powerful that if the assertion (P. p) is accessible to point q. then (P. q) can be proved without using accessibility. 104 - /* p q v > 0 IF F(x) < 5(T) ThEN V :- O? l? X >-- Y ?IEN DO; Pigue 4.6 Is (V > 0. p) accessible to qt T?e reason it is important that accessibility does not ade a27 power to the logic is that as currently defined. the problem of determinIng if the assertion (5. p) is accessible to q is undecidable. Consider the example in Figure 4.6. Is the assertion (v > 0. p) accessible to point qr In general the answer is no. because there is an execution path from point p to point q passing through the statement V :- 0. liowewer. if the func- tion F 55 monotonically increasing. no such path is possible. For point q to be reached. it nust be the case that X > Y. and therefore F(x) ?-- F(?). But if F(x) >-- F(Y). the assignment statement ii nut exe- cuted. The Proof Checker cannot be expected to determine whether the func- tion F ia monotonically increasing. When computing "all execution paths ?roo p to q." it must in gtneral make some approximations; it must include some bogus execution pnths that cannot actually occur. The result of this approximation is that some assertions (5. p) that are by Defini--H tion ?4 accessible to a point q in the program will not be recognized by the Proof Cbecker as being acc?ssible. ii the assertion (r. q) is needed a ty??thcsis. it must be dcrived using a proof rule. Three approximations are ?ade by the the Proof Checker when deter- mini?? execution paths. Approxi?.ation 4.7 is u?ed in AfL/CV. the logic ac - lOj - dafined by Constable and O?Donnell E2o?. The otbe- two.approz:isations have been added so that the Proof Checker can efficiently Compute 1p for. each point p in the program. Apnrov--H?ton 4.7. To find all the execution paths from point p to point q. (and some bogus paths as well). begin at n. and trace the flov of execution through unconditional actions. When a conditional action ia reached. ignore whatever computation is performed to determine which is the next point in the execution path. and nondeterministically choose any possible outcome of that computation as the next point in the path. Any such sequence by which point q can be reached is assumed to be an execu- tion path. Annro.i??tio 4.8. GOTO. LEAVE. and RETU?N statements are preaumed to be munreliable.1 That is. when an execution path is traced to. for example. the statement COTO L. the path may be extended through the corresponding label L. However. a second (bogus) path can be extended to the point that. lexically follows the COTO statement. Civen the Approxima- tion 4.7. the effect of this approximation is as if every statement of the form: COTO Lg were replaced by: ir `I'D flIEN COTO L; and likewise for LEAVE and gETUgH. Witiwut this approximation. it is possible to have points in a pro- Sram throu?h which no execution patha pass. By Definition 4.4. every assertion is accessible to these points in the program. Two examples in which this approximation prtventa assertions froI - 106 ?a p V > 0; GOTO LI; L2:; V :- 0; C?TO 13 p V > 0; 17 X > 0 ThEN Do; V :: 0; REThRN; E&D; LI:; ?t q ?a q 13:; (a) (b) Figure ?.7 Bogus execution paths beiLg recog?ired as b?ing accessible are shown in Figure 4.7. In each case, the assertion (V ? 0. p) ia not recognized as beins accesaible to point q because a bogus execution path passes through the assignment statenent V :-- 0. The third approxination is discussed in section 4.16. ?.? C?.?jn? Prn'?r?n Prnofa As was the case with predicate calculus proofs. proofs of programs are checked by generating V-code and executing the resulting code with the V-code lnttrpreter. The generated V-code can be partitioned into contigu- ous sections, such that each section corresponds to a point in the pro- gram. The V-code section corresponding to a point p has three parts. The first part of the V-code updates the Assertion Table so that it contains A? Then. a series of PROCLAIN instructions are generated. There will be oLe PROCLAIN P for each proof rule of the form: ? (P. p) - 10? - that is used in the proof. The second part of the V-code consists of the V-code generated for any predicate calculus proofs at point p. After this V-code is executed. the Assertion Table will contain The third part of the V-code may begin vith one or o+ore oPt'N instructions that each saves Xp It end. with a aeries of gquigi inatructiona. ?or every proof rule of the for.: ... (p. p) used in the program. there is a REQUIRE P instruction. 4.5 The NEWtion The first part of the V-code generated for a point q in the proaram must set the Assertion Table to Aq This operation often involves delet- ing eeaertions that contain a variable v that has been modified by an atomic action preceding q. To accomplish this task. instructions of the form: NEW v are used. The V?iachine has an inexhaustible queue of unique names. none of which appear anywhere in the proof being checked. The action specified by the NEW v inetruction is: take a variable v' off the unique nane queue. and substitute v' for every occurrence of v in the Assertion Table. The effect is to delete the formulas containing v. and then to PROCL??lN some new formulas containing v'. The reader may wonder why the NEW v instruction does not simply delete all the formulas containing v from the Assertion Table. There are two reasons for performing the substitution inatead: (1) The substitution can be implemented more efficiently than the dele- - 108 - ion. (2) The V-co?e generated by ao?e rules makes use of the ne? formulas containing ??. 4.6 T,??i?re. The turnstile notation for ?roof rules is somewhat difficult to read. A new notation `aill be used to present the proof roles for each languase construct For each construct a ?teaplate" sissilar to those i? Figursa 4.3 and 4.4 will be presented5 but only the points referenced in the diacussiun of the construct will be lattled. For each proof rule of the torn: ??l q1). ??2 q2). ??n q0) ? (R. a) the notation I? Pj) will be written at point ?? in the template. and (I a) will be written at point a. Formulas narked with question marks will usu- ally correspond to REQUIRE instructions in the generated V-code. and tbose marked with exclamation points will usually correspond to PROCLAIN instructions. For certain constructs. some justification syntax is needed to indicate to the ?roo Checker which proof rules are being used. The jusLit jcsttun syutax is also shuwu in tie tewpiutss. There are two kinds of language constructs: simple and compound. A template for a simple construct. such as the assi?o+nment ststtsent. will itake the form shown in Figure 4.8a. A template for a compound construct. such as the li staterent. will take tie fuss: shown in Figure 4.8b. These t--Hs.j'ist?s have u?.--H ur wuis ui.?i?..s wi'??i. sre tnjitatej by vtrticat eiiii'?cs. A ilicy n??of can be Lors?&i by )ayinp a scrita of t?mj?)atcs rud to --H 109 --H 1' p q (? r) ?t q */ (I qi t? kJ t! s) /e t *? IT T) 1? u (I II) IT Vi (I wJ (a) Pipure A.? The format of tempistee end. recursively filling in tho boles in any compound tempistes by the same process. Predicate calculus proofs can be inserted in the oter stices betveen templatee. There are two kinds of points in each template: "f5?????wn" points. like q. 5. u. end v in Yigure ?J. and "face-up" pointe like p, r. t. and v. In a proof. each fece-down point in a template (?xcopt for the lest point in the proo?) wj)l be foliv?d by a face-up point of another template. possibly separated by zero or more predicate calculus proofs. V-code is generated for the various templetes in the same vay that machine code is senersted by a compiler. ThL three parts of the V-code (as describud in section ?.A) ?enerated tor eny joint p corre.po,? to a fecu-down polt of a tempiete. some predicate calculus proofs. and a face-op point of another temptete. 110 - O?ereiuc Du?aLn rru1i? I ? J J --H? 0 I as J J >0? (I --H? 0 I J --H? 0) Table 4.9 Domain predicatee for partial operators 5.7 ?0?-in Ch?c?jne TI? srV,u??nts to any ?srtisl function used in tic prc?rsm must be proved to be in the domain of the function. fle partial functions (and operators) that ar? primitives in PL?Cy are division. exponentistion. and array eubscripting. In addition. all the ueor-definod functione are essum?d to ?e partial. 7or each function. there is a predicate involvina ite operande that formally e1presses that the operande are in the domain of the function. 7cr diviejon and exponentietion operators. the predicatee are shown in Table ?.9. The ?redicate for each user-defined function is found on the AS?ME line or the function definition (see section 4.12). The case of arrays deserves special ettention. If the array A hes been declared by: DECLAtE A(L1:U1. L2:U2. ... Ln:Un) type; (5.1) then for all i in (I ... ni. the FIJI functions LBOUND and MiOUND have the following values: LBYJD(A. i) Li ili(L'NI)(A. i) Ui Tbe V-code generated for the declaration (4.1) is shown in ?igure 4.10. The reason for the complexity of the V-code is a peculiar restriction in flil that every array must have CL least one element (48). That is. each lower hound of ab array is required to be less than or equal to the Ill --H Rv.QU:RE L1 < U1 ME?UuL? L2 <- U2 iEQUIRE L <-- U n n PROCLAIM LBOuND(A. I) L1 PROCLAIM LRtAJN1)(A. 2) o+ L2 PI((X:.AIM U?()UML)(A. n) L0 rROCLA:M IIfltAJ?b(A. I) u1 PROCLAIM llRoUN1)(A. 2) u2 PROCLAIM i(0()UMD(A. n) PROCLAIM LI:(IJME)(A, I) 4 II?(?RD(A. 2) PROCLAIM LaouNL)(A. 2) 0 is an abbreviation for the sequence: - ll.? - lBQuThB J ?= 0 ? (It 0 I 0) REQUIRE ?( a REQUIRE (LBoUND(A. 1) <: K*aj 1 N) & (KtaJ ? ? < flOUND(A. 1)) Another problee with partial functions is defining what they mean when used in assertions. For example. the formulal ALL (x v) FIX?D. (x a fllx v would appear to be invalid. since for any v. the value of (0 a v),O is undefined. v?t it seems there should be formula very muc? like (4.2) that is valid. In an attempt to rule out the case in which ? a 0 we light tryt ALL (x. v) FIXED. (X 0 --? (X a fl/x v) (4.3) v?t how is formula (4.3) any lore meaningful than formula (4.2)? We still have the problem of siving meaning to the formula 0 0 a> (0 a v)J? a The solution used in Ptlcv is never to reason about partial func- tions. The semantics of PLICY are such that. for example. the division operator is actually a total function that has the same value as the fami- liar partial function on the domain of the partial function. Since a PL/CV program that has been proved correct only calls the total function using operands that are in the domai( of the ?artial function. w? can cheat whun we implement division in the programming language. and use the partial fwjction. No axioma are provided to specify the value of the total function outaide the domain of the partial function. Thus. formula (4.3) can be proved In IL/CY. since It Is valid nu uatter `eat the value uf 0/0 I.. But formula (4.2) can neither be proved nor disproved in PLICY. because all that can be proved about the value of 0/0 it that is an inteLer. This same trick is used with all the partial functions. liowever. in - 114 - ONE : It TWO : 2; ThREE :-- 3; ZERO ONE?ThREE + ONE?niRE + ONE?ThlEK; s-- otE?Twu o+ ON?ThO; Fisure 4.11 The an?malous PIJI diviajon operator the case of division the 5fa.iliar partial function" is the division operator from FORTRAN (71. That is. the value of 1,J is undefined if J 0. sud otherwise is the integer K closest to zero such that IKI < jItJj. where o+ is rational division. Althou?h it is unpleasant to give axims for FO?TRAN'. division operator. PL?l?s division oper?tor is an axiomatic nightmare. Rather than truncate the result of a division. PL?I maintains as much precision as it csn while evaluating an expression. and truncates on assignment. Assunins all the variables in the pro&ram fragmant in Figure 4.11 have been declared FItED (which is short for FIXED DECIMAL). the variable ZERO is set to 0 and O'.E is set to I (twice). The reason for the apParent discrepancy is thst one half has a short decimal representation. whereas one third has an infinite one. In pL?cv. the division operator is only allowed in contexts where its result is innediately truncated. An equivalent way of stating this res- triction is that if the division operator is used in an expression. it must be the main connective of the expression. The total function one reasons shout in PL?CV is an extension of the FORTRAN division operator. The splemeotation uses the PLIL operator. but it is not allowed in any context ?here it can be distinguished from the FORTRAN operator. Intentional incompleteness can also be used to model uninitialized variables. Accessiog an uninitialized variable is not considered a run- time error in PL/CV; nor are variables assumed to be initialized to zero. IlS UDF,F: PROCF.DURE (X) RETURflS (FlXE?); DECLARE (v) FIXED; RETURN(Y); END UDEF; Figure 4.12 & function whose value depends on a uninitialized variable If p ia the point in the proarsi just after the variable V has beau declared. no asSertion (P. p). where P depends on the value of V. can be proved or diaproved. An implementation is free to initialire a newly declared variable to whatever garbage happena to be on the atac?. and any program that has been proved correct will run properly. Unfortunately. if a routine ia called lore than once. newly declared variables lust be initialized to exactly the same garbage every tile. This restriction is required so that. for example. the formula: ALL X FIXED. UDEF(1) UDEF(x) which can easily be proved. is valid given the function definition in Fig- ure 4.12. The reproducibility restriction is tantamount to requiring an iLple--H mentation to initialiso newly declared varibles to sone constant. A clever compiler could in some cases detect that operation of a routine is independent of the initial value of one or lore of it, variables. and olit the initialization of those variables. Another solution to this problem would be to require that the specification given for esch user-defined function ilply that it is in fact a function. For example. if the user proves that F(x. y) always returns the greatest common divisor of x and y. then it will do so independent of the value of newly declared variables. But if he only proves that F(i. y) returns a positive value. then different calls to F with the same arguments can potentially return different. though pesitive. osulto. 116 /t p s/ (Dom t) (? P(q/v)? v :--H--H (I PI ?igure 4.13 Template for the assianment rule AA The A??t St?te?ent The template for the PL?cV assignment rule. which is essentially Nosre?s sssiLnmcnt axiom (`I). i? ?huwn in Figura 4.13. The first and second parts of the V-code for point p. which will have been generated for anotber tenpiate and coy predicate calculus proof5 at p. will set the Assertion Table to X To set the Assertion Table to Aq it is only neces- sary to delete all assertions that contain an instance of v. A NEW v instruction can be used to delete these instructions. and replace them with sinilar assertions. with v' substituted for v. These new assertions are somewhat peculiar. If v' is interpreted a? nthe value the variable v had before the assignment statement.5 the asser- tions are clearly valid. liowever. there will ne?er be a REQUIRE Q instruc- tion such that Q contains an occurrence of v'. But recall that a REQUlRIQ instruction will succeed if Q is in the Assertion Table. or deducible via automalic rules from the formulas in the Assertion Table. For example. if the formula x o+ v*O y is in the Assertion Table before the V-code sen- crated fur the assigument statement i, proceased. the l?EW instruction will chan?e it to X + v'sO y. Subsequcotly. tie instruction REQUJRE x y willed. Extra deductio??s such as tj?is ouC. which are nut w?utt'oned 117 ?OHAIN t REQUIRE P(tllvj' HEW v P?ocLAlM P haute 4.iA Adequate V-code for the aseignuent atate?ent he PLlCV Reference Manual (I?) are. depending on one's point of view. a feature of or a bug in the Proof Checker. However. citra deductions that use the automatic substitution rules are the basis for?the method used for checking the assignment rule. A V-code seqtience that would adequately check the assignment rule is shown in Jigure 4.lA, The drawback to this sequence is that it is neces- sary to know what P is to generate it. Some justification ayntax. such as v :? t P BY ASSICH. L; would be necessary for each use of the assignment rule. Ilot only would this be cumbersome for the user. but to generate the proper V-code. either the BY ASSIGN lines would be required to immediately follow the assirnment statement (in which case the labels would be unnecessary). or a finip technique would have to be used to insert the REQUIRE instructions that must come before the NEW v statement. A different approach is used in PL?CV. The assignment rule is con- pletely automaticI no juatificetion of any kind is needed. Instead of the V-code in Fi?urs ?o.l4. the ful?uwin? V-cude: DOMAIN t NL? v PROCLAIM v (t(v'llv)) is ?at.d, whe,? v' is the variable with which the NEW Instruction rt?lacea - 118 - every occurrence of v. The na,se v' in chosen by the V-code interpreter in such a way that the Local Context Checter can predict "bat it viii be (see section ?.4 fur o+ore details) lecall that the interpretation for v? is "the value the variable v kad before the snaitnuant atetetoent van executed." For exauple. for the asairneent atatesent J :- Jal, the V--Hcode instruction: ?k(,(?tAt? J J'sl will be g?ner?ted. leanfog. "henceforth the velue of J will be its previ- ous value plus one." a tbst us. the assigneent rule in Figure 4.13 are sccepted beca?ae of an automatic substitution rule built into the V-code Inter- preter. If tie fornulsa P(tlis) and a t are in the Assertion Table. the inatr?ction 1?Ul?E ? will succeed as a consequence of this autoxatic rule. Suppose the assertion: PLt#v) (4.4) is in X? Then for,:ula (4.4) saust be in the Assertion table when the HEW v instruction in executed. This instruction will delete foriula (4.4) and replace it vith: prtllv)(v?llv) (4.5) and the PROC?t?AlM inatruction will add: v = (t(v'llvi) to the Assertion Table. The o+et=notation used in (4.5) seens: first replace tvery occurrence of v in P by t. and then replace every occurrence of v in the result by v'. Any occurrences of v reesining after the first replacesent suet be in the copies of t that vere inserted. These - 119 --H occurrences 0 V are changed to v' by the second replacement. If the occurrences 0 V in t are changed to v' before it is copied and inserted into P. the resulting formula will be the same. Thst is. the formula represented by (4.5) and by: P(tEv'#v)llv) (4.7) are identical. After the V-code generated for the assignment statement is ezecuted. a lEQUIRE r instruction vill succeed as long as formulas (4.6) and (4.7) are in the Ansertion Table. since the substitution rule can ho applied to these two formulas to obtain P. The dcduction of P fron forculas (4.6) and (4.7) can be performed even after (4.6) and (4.7) have been updated by a NEW v instruction. as long as v is not a ?arishle in P. since Lhe only part of the two formulas that can be changed are copiea of t?v'llv). and all copies are changed in the same uanner. Therefore the gEQU?E ? will still succeed after a NEW v instruction has been performed. unless v is a variable in P. flecause the V-code Interpreter can deduce any formula obtained by any sequence of aubstitutions. applicationb of the assignment rule can be chained. For example. for the sequence of assignment atatements: ?e p t? A :- A + 3. I a-- I t C a- A + I; q q the V-code: 120 A PROClAL? A - A' + 5 hEW 3 PROCLAIM 5 a 31 * ? c ??cCLAIM C A + 5 viii be generated. Suppose the asaer:ion (C(A n) + (? * c)) ) 0. p) is acceasible to p. After the above V-code is executed. the foraulas: ((A' + 3') + (3' * c')) > 0 (4J) A - A' + 3' (4.9) 3 5' a c' (4.10) C-A+ 5 (4.11) vill be in the assertion table. the sasertion (c > 0. q) can be derived by three applications ? the assignment rule. Dut because C ? 0 can be ?erived by p?rforming aubatitutiona on formulas (4.8-11). the V-code instruction tEQ'JlRE C > 0 will succeed. 4.9 Ar-v ??? An array A in Pt/cv is a quintuple of the ?ora (h'. L, V, 1, z). Tb* conponent n. the nunber of dimensions. is a positive integer. The con- ponenta L and V. the lm?er and upper bounds. are vectors of H integers. such that for each i in (1 ... N). L. ? V.. The component F is a function I I whoae doasin is the set of vectors x x such that for each i in ?l n (1 ... Ni. Lj ? a? A V1 auj ,bo.c rs?go Is tho baa type of the array. Ths co1ponent Z is a value whose type is the base type of the array. When applied to an array. tbe ?BwND and l?CUND functions return the approprIate citment of its L or V component. TI? suhacriptin? operation, vh.'n a',', i?d to a,? or. fly a?,d a v?Ctur X ret.1rna `(x) If X is in the domain of P. and Z otI?r?t'o+e. ?. an. If .t?,in h??Inr. (.?n o+?t inn 1.1). 121 --H IZQUThE LBQi?D(A5 1) n 1JO(JND(fl. 1) iaqumg LBWND(A. 2) = LBw?D(B. 2) RQUIR? LBouND(A. n) LBouND(n. n) RE?U1KE )IB(L't'1)(A. 1) ll???D(B. 1) MEQUIRE HB()Ur??(A. 2) HBULND(B. 2) REQUiRE llBcUND(A. n) tIBOUND(fl. n) NL? A PROCLAIN A (lEA'llAl). ligure 4.15 V-code generated for the array assignment A a- 3 program that baa been proved correct can apply the subacripting operation to a vector outside the domain of F. Therefore. an implementation of the programming language need not store Z. There are three kind? of aasignnent atate:ents involvina arrays. The template for the first kind of?srray assignm-n? is: (T PtBllAi) A a (I P) where A and 3 are both arrays with the sane domain. This assignment statement is essentially the same as the one presented in the previous section. The V-code gen?rated for such an assignment statement appears in Figure 4.15. The only difference ?etween this assignment statement and scalsr assignment is that REQUIR? atatenenta must be generated to check that the domains of the two arrays are the sane. The Local Context Cluckar must siso ensure that A and a have the same numLtr of dimensions. The template for the second array assignment statement isr A I (I Al.!. (J1 ??n? VlXLU. A(J1. J2. ?n? ci where c is a constant of (he ni?proprin(e tyic'! the coctcs1'?nJin? V-coda is in YI?tsrs 4.l?. The assotits of this sIst?m=nt is I'. molify tt,s V ?nm - 122 - fl? A P&OCLAIN ALL (J11 ??n? FIXED. A(J1. J2. ?n? ? Figure h.16 V-cod. genersttd for the array assigneent A :5 c gubes.L of A to be LI.s Coustallt fus.&Liufl wiwas value ta sverywI?re es sad the Z coapontnt of A to be c. Since the program can never determine the walue of the Z component it should be impossible to prove anything about the value of the array outside its doisin. A more diligently incoeplete rule would bet A I' c; (1 ALL (Jt( Li?????J.ni)?FI ALT(A. I. ?)(X) = it) ALL I FIXED. (A(s) it) type. LflOUHD(A. I) = LflOU?iD(ALT(A. I. it). 1) (4.14) ALL I FIXED. (A(s). it) typc. llllWMD(A. I) IilllND(ALT(A. I. T). 1) (4.l?) are sufficient to characterize the function ALT. The proof rule in Figure 4.1; has been derived by a process I call reduction. Given a language construct C that can be expressed in terms of other constructs C1. C2. Cn for which proof rules are known. a proof rule for C can be derived from the rules for C1. CC0. In this case. array assignment can be expressed in terms of scalar aseignrent and the ALT function. The resulting rule for C will be sound if the rule for each Ci Is sound. and it will be as complete as the rules C1. CCn Certainly it is necessary that a proof rule be sound. and desirable that it be complete as possible. But soundness and completeness are not the ultimate yardeticka with which proof rules should be measured. A good proof rule for a construct C is one in which a programmer's intuition about C can be easily expressed. In a poor proof rule for C. the - 124 progremme?at5 inteitic? ?ust be encoded Proof rules that are derived using reduction are not necesurily eoof ones. We must ask ourselves the question. o+If tbe construct C can be ex?resaed in terms of the constructs C1. C25 .. Cn why does the con struct C appear in the language at all?'o+ Sometimes the answer is that the designer of the language simply did not realize that C could be expressed in terms of other constructs. If it is truly easier to understand C as a ccmbi?stion of C1. C2 ... C0. then C should be eliminated from the language. But more often the answer is that when C is built up from Co. the resulting whole is somehow conceptually simpler than the parts. Any proof rule for C that does not reflect this simplification vill be unpleasant to use. The int'.ition behind the proof rule in Figure 4.17 is that an array is a single object. and that array assignment statement: A(x) :- is so-called syntactic sugar for: A :-- ALT(A. z. Du: one could just as easily claim that there is only one true variable. an array called STATE. in any program. and that variables programmers write are just constants usej to index into this array. The assignment statement: v :: is just syntactic sugar for: STATh :-- ALT(sTATE. v. and the array assignment statements --H `25 --H (Doe A(z)? (Doe yl (? P(y#A(z))) A(x) (I PI Figure 4.18 A more intuitive array ru?e (Doe A(x)) (Doe y) (? P(yllA(x)JI (1 fl Alt A(x) a- y (I PI (1 ALL J FIXED. (J (x(3llA)) --> A(J) a(J))J and A cannot be the name array Figure 4.19 The PLJCV rule for A(z) a y A(i) an y? in junt nyntactic sugar for: STATE ?: ALT(STATE. A+x. y) Thin view of aaaignment in used in many nemantic dencriptiona of progras:- eing langaugen. and it can be helpful when attempting to construct cosa- pilern for or to prove propertien of the langauge. But it in not very helpful when attempting to entsblinh?the corr?ctnenn of a parLicular pro--H gram. I propone viewing an array an a collc?tiun of vsrinbL?n. An array annigneent statement aelectn and modiflen a particular variable in the collection. A rule nuggented by thin alternate view in ahown in Figure 4.18. But thin rule in not nuffaciently complete to prove most progrean that use arrayn. The rule used in PL/CV is shown in Figure 4.19. and the corrca?onding V-code in ahown in Figure 4.20. An advanta?e of the rule in Figure 4.19 over the Rule in Fi?.ure 4.18 in that the AIT notation and the - 126 - DG?Ifl A(x) DOXAIN y A P??LAL? A(x(A'??AJ) PkOCiAlN ALL J y1z?r. (J (x(A'llA)) ? A(J) a Figure 4.20 V-code generated for A(x) is 7 `ales that aust cosac with it are not necessary. The disadvantage to the rule in Figure 4.19 is that in general there wLll not be an array fl that La equal to the array A. In alnost all cases. an extra array I must be declared with the same bounds as A. and the atatement I :- A o+ust be written prior to every atatement A(x) a y. The array I is an "auxiliary variable" similar to those used by Owicki end Cries (63) to prove parallel programs. eo that this extra array and the extra assignment statements. which are needed only for the proof. do not reduce the efficiency of the pro- gran. the declaration of the array I and the assignments to it can be enclosed in the ahieldi?g brackeis ?a: and t/ As long as the rules: (1) suxiliary variables spp?ar only in assertions and shielded state--H ments. and (2) n?nauxiliary v?riables are not modificd in shielded statements. and (3) if p and q are points in the beginning and end of a bl?ck I of ,hielded statements. the only execution paths into I pass through p. and the only execution paths out of B pass through q are obeyed. any progranning constructs can be shielded from the compiler. Since none of the examples in this thesis are intended for execution. shielded atateLents will not be used. The following example will be used as a benchmark to conpare the two array rules. Suppose we wish to write a loop to set each element A(K) of --H 12? - GIVEN: ALL K FIXED. (1 < x < j ? A(K) Ks5) ALL X FIXED. (I A(K) 1+5); Figure 4.21 A proof using the ALT rule GIVEN?: ALL I JrI?. (I <-- I < J --) A(K) 1+5). fi :a A; GIVEN?: ALL I FIXED. (5 -? & N>eB ? (N-? 1 RI); This specification could be satisfied by a procedure body that simply assigns the same value to A. 1' and M. To pin down the desired func- tionality. some way of ensuring that A and 1' are not modified by the pro- cedure is needed. To correct the specification. the declaration is changed --H 132 - to? DECLARE (A. 3) FIXED lEADOILYt DECLARZ M FIXED; We say that A and I are readonly parametern. wherean M is a readyrita paranater. The Local Context Checker reports an error if a procedure directly modifje. a readonly variable. Dp?nripn 4.9. A procedure is defined to "directly modif?' a var?--H able V whenever V appears on the left aide of an sasignient. is used an a loop index. or is paased by reference to a readwrite parameter of a pro- cedure. E?ry external variable that appeare in the body of procedure must be declared in the procedure htader. External variables can be declared with the RLADo%.iY attribute. in which case the Local Context Checker enurts they are not directly modified by the procedure body. However. a re?donly exttrnal variable can be modified by calling some other procedure in which it is declared readgrite. ??f?m,tin', 4.10. If 11 and are routines. define the relation Ij? 12 to hold whenever there in a call to in the body of R?. define ?+ to be the trannitive closure of ?. and define ?t be the reflexive transitive closure of ?. If R1 is a routine. and V is an external vari- able. Rj in defined to "depend on" V whenever there in a routine R2 such that X1 ?? 12. and V in dcclart? in 12. RI is defined to "indirectly modif?' V whenever there is a routine such that 11 ?t and V is declared readwrite in 12 The ?tAX exam?le `as the property that each procedure I)nramuter Is u.?d nulaty f,r l?put ..r uutr.uL. If we win to write a apit icatlui, for a 5 r?Al'(A. ?) hat ?x, t.s,??es the valr,a. .?f A ?nd It w? hava a prob--H --H 133 los:. To ssprnss the values the parameters should have Co output. the exit condition aunt use acne notation for the values those variables bad on input. Auxiliary parameters are used for thia purpose. the specification used for SWAP is: SWAP: PROCEDUlE(A. fl ?s: AO. BC DECLARE (A. B) FIXED; ?a: DECLARE (AO. BC) FIXED READONLIEl t? ASSu?tE A-AO & g--Bo; ATTAIN A?BC & B--AO; the a'axiliary parameters AO and 50 follov the same rules as the auxiliary variables discussed in section 4?? When SWAP is called. shieded actual Parameters must he given that satisfy the input assumption P. as in: CALL SWAP(X. v ?t: (1). (v) t?)j In this example the parentheses are required around the shielded parame- ters to avoid alissing (see section 4.11). Roughly speaking. the rule for a nonrecursive call to a procedure is: iDom actualsi t? P(actualsflforialsi) CALL R(actuals); q t? (1 r?ec:ua?sllformnisJ) where P and I are. respectively? input Sesumption and exit condition of the procedure 1. It is rather cumbersome to spell out the actual rule in detail; the V-code generated for the procedure call is easier to understand tban tttu rulc is. Tt? ?-??.f? Mt'llur.ottJ !?)r the j tJura call concists 01: (I) a I)(l:AlN t instruct ton (`r each actual psra?tcr t. (2) a Ptt()It)ItF. instr,?ut inn. - l3? au( ?r.W iusLru?I I?ns. and a series of ??OCtAl?t instructions. The operand of the I?QUlR? instruction in obtained by substituting for each forsal parasater in the input aasunption P the corresponding actual para.--H eter. The pur?ose of the sequence of NEW Instructions to to set the aseor- tion table to A . A NEW v instruction must be generated for each variable v that can be modified as a result of the procedure call. The variables for which NEW instructions mUst be generat:d are: (I) scalar or array variablee V that are paseed by reference through a readwrite parameter (2) array vaxiables A. where an array element A(X) is passed by refer- ence throu?h a read?rite parameter and (3) external variables V that are indirectly modifjed by the procedure being called. In PL?C. all para:etcrs of the form V or A(x) are passed by reference (`0). rt.at is. when the corresponding formal parameter is modified. the corresponding actual parameter is modified as well. All other expres- sions. including those of the form (V) and (A(x)) are passed by value: modifying the corresponding formal parameter has no effect on any other variable. Designate by V the aet of variables V for which NEW instructions are generated. the notation ?(V'llV) will designate the formula (or expres- sion) Q with V? aubatituted for each variable V in V. where V' is the nov variable selected by the NEW V instruction. As in the case of the assign--H o+ent statement. the proper interpretation for V' is the value the variable --H 133 --H V cuntafnod beturs the prut?dnre caSt. The operand of the first ?RoCLA1H Instruction to obtained by per forning subatitutions on E. the exit condition for the procedure. For each formal parameter F1 let C be the corresponding actual paranerer. ?n each case1 Cone variation on C or V is substituted for every occurrence of V in 5. in order to relate the final value uf the formal para.rter to sole value in the calling procedure. There are four casesa (1) If V is flEADOHLv1 the value of F at the end of tha procedure is the same value it had at the boainning. Variables in C can be chaned by the procedure; cV1llv? is the value V contained throughout the execution of the procedure. Therefore. c(vlllv) is substituted for for every occurrence of V in 5. (2) If C is passed by value and I is resdwrite1 tl?e value of V at the end of the called procedure is not related to any value in the cal- ling procedure. Therefore. a variable V' that appears no?here else in the proof is substituted for every occurr?nce of V in 5. (3) If c is a acalar or array variable paseed by reference and V is readwrite. C and V have tl,e same value when the procedure finishes execution. Therefore1 substitute C for every occurrence of V in 5. (4) If c is an array element of the for. A(x) and V is readwrite1 the variable that is the actual parameter and V have the same value when the procedure finishes execution. However1 after the procedure call. A(x) is not necessarily a name for the variable that is the actual parameter if the procedure call modifies variables in x. The expression A(xCV'llVJ) is substituted for every occurrence of F in 5. Once the appropriate aubstitutiona for each fornal parameter in 5 have - 136 --H bean perforsed to yield 1' t%e inatruc:io:, PIOCLAL? I' is generated. If one or more array elements of the form A(?) are passed by refe:- ence to a readwrite parameter. a NEW A instruction will be generated. Assertions involvin8 elements of A that were not modified by the procedure are still `,alid. but are not accessible to points past the procedure call. So that these a&strtions can be established after the procedure call more PROCLAI? instructions muat be generated. For each array A for which there are elements A(x1). A(x2) ... A(xn) passed by reference to raadwrite paraneters. a PROCtAIN Q instruction must be generated. where q is of the form: ALL J FIXED. ( J --H? x1(V'llV) & j --H? x2(v'flV) & J x (v'll? -> A(J) Given the strengthened notion of accessibility discussed in section A.?1 these PROCLAIN instructions could be omitted. A routine R is said to be recursive whenever a ?+ R. (Note that a procedure need not calL itself explicitly to be recursiva.) the rules for recursive proccdurea are exactly the same as those for nonrecursive pro- cedures. except that termination must be proved as well. A termination - predicate T with a free variable a is specified for every recursive pro--H ce??re. The predi?ate T will. in Mcneral. alno dcpend on the pruceJure parameters and external variables accessed by the procedure. Intuitively. t says that the difficulty of problem to be solved by the routine can be characterired by some metric m. and that m ? a. At the top of every 137 ?scursive procedure. ?he formuln: SON' a ?IXED. a ?s 0 a T must be proved. usins only the input aaaumptioc ma a bypotbesin. flefinirign ?.ll. Let 11 be a routine tha catIs 12. Tbe call ia said to be a "recursive call" whenever 12 ?a Since Il 12 and 12 ?a 1j. we have 11 ?s and 12 ?5 12 Therefore. recursive calls can only occur between recuraive routines. ?Iote. however. that it is possible for one rt?ursive routine to call another without the call being a recursive call. Suppoae 11 and 12 are recursive routines. and Ii calls 12. Let T1. T2 ?l? ?2 be the termination parameters and the arbitrary variables declared in the bodies of R1 and 12. If the call to 12 is a recursiva call. to ensure termination two additional 1??UIlE instructions are gen- erated for the call: lEQUIRE ?i 0 and lEQUlIE T'. ??ere T' is obtained by performing the following substitution. on T2. The corresponding actual parameter in the call to 12 is aubstituted in T2 for each occurrence of each formal parameter of 12 and --H I is substituted for ?2 Intui- tively. these two assertions expreas the idea that if Ii is performief a recursive call. the problem it is sol?ing is nontrivial (that is. every difficulty metric for the problem is positive) and it is using ?2 to solve a probl?m easicr tan thu one it is solvinM (tl?re is a difficulty metric for the problem 12 is solving that is smaller than every difficulty metric for the problem Ij is solving). To sue that these rules ?uarantee termination. aup infinite chain of routine calls. Because there are only finitely many routines in a program. the chain of calls must have an infinite tail that is a sequence of calls to routines 1a0' 1a?' 1a1 where if routine 138 - appears in the tail. it appears infinitely often. Because every routine that is called in the chain is called again at a later point in the chain. avery call in the chain must he a recuraive call. Let Tj be the tcraination prcdicate for each Define an integer a to satisfy a termination predicate T. in a atate whenever substitutins a for the free variable a in Tj yields a formula that is satiafied by the state. The termination rules guarantee that: (I) whene?er a recursive routine Rj is called there will be some non- negative integer I satiafying Tj in the state in which the routine begins execution. and (2) for any integer ?. if is begun in a state in which a aatiafisa T. and from that state R. askes a recuraive call. then a cannot be zero. and (3) for any integer a. if I. is begun in a state in which a satisfies Tj and from that state a. :aakes a recuraive call to ?. then a - I satiafiCe Tk in the state in which Rk is begun. Let a he a nonnegative integer .atisfying Ta in the state in which 1 is 0 a0 begun. by (I) auch an I must exist. For each nonnegative I. in the state in which is begun. a - i must satisfy T?i by (3) and induction on Therefore. 0 must satisfy T5 in the state which is begun. Since wham begun in this state. a makes a recursive call. (2) is contradicted. 5k Therefore there can be no infinite chains of procedure calls. 4.11 A1i?s,n? The V-code generated for every programming construct includes a BEW v instruction fcr evary variable v that can be modified by the con- struct. To generate this V-code. the Local Context Checker be able to - l3? deteriine which variables are `odified by a construct by exanining the construct. For example. the assignment statements X &- I + Ii modifion the variable I. However. if X and v are the two parameters of the procedure I. and there is a proceJuro call of the for?a CALL i(z. z); then the assignment statement (4.16) con modify the variable v as well. Procedure calls such as (4.17) are said to o+aliasfl the parameters I and v, Cartwright and Oppen (133 diacuso the additions necessary to a pro--H aramming logic to reason about progress in which aliasing occurs. The PL,Cv system uses the simple expedient of declaring any program that con- tains aliasins to be in error. The Local Context Checker tests ench pro- cedure call. and issues on error sessage if it con potentially introduce? alisoing. Hvery variable in a program can be considered a naae for sone storoge location. If a varioble v has been declared to be readouly in a procedure 5. then v con only be used to exasine the contents of tbe storage location. In that case. the procedure I will be said to poaaeas v as a "read name" for the location. If the variable v h?s been declared to be readwrite in I. then v can be used to both examine and modify the storage location. In that case. I is said to possess v as both a read name and a `write name" for the location. To prevent aliasing. it is suf- ficient to prevent any procedure from possessing two distinct variables r and v ouch that r is a read name and w is a write name for the ease loca- tiqo. There ore three kinds of program variables in PL,CV: local vari- ables. external variables. and procedure parameters. Distinct variables that are not peraneters Sr- always names for distinct storage locations. Therefore. if the variables r and v are aliases5 at least one of them must be a parameter. In a procedure 1 it is impossible for a parameter and a local variable to be names for the sane location. because the location naned by the local variable and the parameter must reside in different environments. Therefore. aliasing can only occur between two parameters5 or between a paranter and a external variable. The following test is used to prevent aliasing between two parame- ters. For every procedure cal!. all the parameters that are are being passed by reference. including those being passed through readonly parame--H tera. are examined. If the same variable is being passed through more than one paraneter. and at least one of those parameters is readwrite. an error is reportad. When array variables or array elenents are being passed by refer- ence. sos extra processing is required. All pairs of actual parameters involving the ssr'e array. except for pairs being passed through two reaoon:y paramaters. must be considered. If one of the pair i. an array variable. an error is reported. In the other case. when the pair is two array elements A(x) and A(y). the V-code instruction? REQUIRE x y must be generated. This test can be extended to prevent aliasing between parameters and extsrnal variables by treating external variables as implicit parameters. If a routine R indirectly nodifics an external variable V. then V is included as en extra implicit readwrite parameter to every call to the r?u( ins R. If rho ????L inC It I.on V. h'.r Jues nut In rr.ct1y sudify - 141 - RI PROCEDUREs Is PROCEDURE; DECLARE C FIXED EXTUSAL; DECLARE C FIXED EXTERlAL; CALL s(C); CALL s(C); END R; END R; Si FROCEDUME(X); 5: FROCEDttE(X); DECLARE X FIXED READONLY; DECLARE X FIXED READONLY; CALL T(X); CALL T(X); END St END 5; Ti PRoCEDUIE(Y); DECLARE Y FIXED IWOSLYs DECLARE C FIXED EXTERNAL IEA?NLT; Ts PgOCEDUgE(T); DECLARE Y FIXED READONLY? DECLARE G FIXED EETElL?AL; (a) Figure 4.25 Legal (a) and illegal (b) uses of parameter pasaing Vs then V is Lucluded as an implicit readonly peraneter t? each call. The implicit parameters are of course passed by reference. An example is shown in Figure 4.25. In routine I in part (a). the variable C is being passed to 5 explicitly. But since 5 calls t. and G is declared in T. the routine I also passes the variable C to 5 implictly. flowever. both the implicit and explicit parameters are both readonly. so the call is legal. It can only result in multiple reed names for the location occupied by C. The difference between ligure 4.25a and 4.25b is that in (b). C is declared readwrite in T. The call to 5 from R is now illegal. because C is being passed explicitly readonly but implicitly rea??rite. The pro- cedure T can pottntislly possess Y as a rt'ad name and G as a write name for the .si?, loc?tion. 142 - N?e: P?OCEDui?E(A. B. C o+..) REThRNS(Lype)? DF.CLAR? .. (paraneters and external variables) AsSUN? P? (I pi AflA1? E; (predicate calculua proof)t t? ??H? a ylX?1,. (a 0 ? T)11 ARBITWY a PIXED WliERE T;1 (I T11 (local variables) (procedure body) (? `01B) 1oLitted in ?onrecuraiwe functions Fi?ure 4.26 Ttnplata for a function definition 4.12 F?,nc?jnns Ani F.?n???nn Calls To reanon about a programeing language in which expresalona can have aide affecta. IL I. necessary tu nake aseertion. about pointa in the pro--H gran w?thin expreaaiona. Expreasiona. and in particular uaer-definad functiona. are for thia reeson not allowed to have aide effecta in PL,CV. All function parameters are irplicitly readonly. and a function is not allcwed to icdirectly nodify any external variable. Therefore function. are much siepler than procedures. For instance. there ia no need to check function calls for aliaaing. The template for a function definition is ahown in Figure 4.26; it ia easentially identical to the template for procedure definitions. Let I stand for nane(A. 3. C ...). Then the exit condition E will be sons predicate involving the function parameters. external variable. (which can only be accessed readonly), and N. For each statement of the forms IrULN(I); in the function. the aseertion (E?xllN1. p) must be known. where p is the - 141 - REQUIRE P' OPEN PROCLAIN Eactualsilforealsj REQUIRE Q CLOSE Figure 4.27 V-code generated for the FUNCTION rule point in the prograss just prior to the RETURN statesent. There is no "function call statementH; functions are siuply written in any expression. The domain predicate (see section ?.7) for a recursive call to the function 12 eppeerina in an expression in a routine is: P(actualsflfnraals) & T(actualsllfor?1a. sI?llla2) & sl?O (4.18) where ? end T are the input assumption and t?rmination perameter of L'-2. and o+1 and are the arbitrary variables declared in the definitions of 11 and R2. If the call is not recursive. the donsin condition is juat: PEactualefiformals) . (4.19) User-defined functions can also appear in predicate calculus proofa. the following rule is used to reaaon about user-defined functions: Q flY FUNCTION. R(actuals); . (4.20) The V-code generated for (4.20) is shown in Figure 4.21. where E ie the exit condition of 1. and ?` is either (4.18) or (4.19). Thus. Q is any concluajon that can be derived via auto.etic rules from the exit condition of I. When computing the relation ?a to determine which routines and rou- tine calls are recursive. an application of the FUNCTION rule (4.20) counts as a "call" to the function I. In the V-code in Figure 4.27. if the rule application is a recuraive 1call" then P' is (4.lS) otherwise P' is (4.19). 144 WROIG: PRcCEDuRE(x) RETuR??s(FI1zD): DECLARE I FIXED; AsSU?E `l'B: ATTAl: %1LoN?(x) x & wROtIG(x) 1+1; who?G(X) I & WRONG(I) X+l BY FU?CTIONp Wto)IG(x): I ugoNc(X) x+l; I I & I 1+1; REThR:(x); Figure 4.28 A fallacious argument It nay seem peculiar that a function that is called from a vitbin comment must be proved to terminate. But Figure 4.28 shows the kind of nonsensical argunenta that can be made without this requirement. When one is using the function rule. one is proving that e function has some pro- perty by induction on the size of its arguments. The termination rule is used to show the induction to be well-founded. Sup?ose we wish to prove a function FACT(N) that returns N factorial. What do we put on the ATTAIN line of the fui:ction body? We cannot write ATTAIN FACT(N) NI. because the factorial function is not a primitiva in tbe assertion language. A solution to this problem is to write: ATTAIN (N - 0 > FACT(N) 1) & (N ? 0 > FACT(N) N a FACflN-l))g If we write the function recursivelys it is a simple matter to prove it correct. If we write the function iteratively. the ??Nt?loN rule must bq used recursively to prove the function. as shown in Figure 4.29. Note that the technique of recuraive specifications used to define the function FACT cannot be used with procedures. A specification for a procedure rAcir(N. x) tat stures NI In k must be written in tetmi of tit. VAtT Iun?ti?u tu ?lgute 4.29. Aitlough functions arc not alluwod to modify external variables. tley are ailowtd to deptud on external variables. Supi?se the function 145 ?ACTa `R0CIDtlI(M) RETURNS(lIxED)I DECLARE N FuED? ASSU?E N >= Ol ATTATh (N = 0 => FACT(N) =1) & (N >0=> 1ACT(?) : ? ?ACT(M-!))? BONES FIXED. (5 >= 0 & N <=5) BY INThO. `Ig ARBITRARY 5 FIXED WHERE N <= 5; DECLARE (J. F) FIXED; F := I; l>N => (N?0 => F=l) & (N>0 => F:N*FACT(M-1)) BY INTRO N 0 BY ARITh. 1>N. N>=O; ?N>0) By ARITh. N = 0; QED; DO J t= I TO ?I BY I; ASSUNS (Ji =0=> F = I) & (JI >0=> F = (JI) t FACT(J-2))I Pla (J = 0) BY ARITh. J >= I; ?* abog FACT(J?l) ?eI1-defiued *? 5 a 0 BY ARITh. 1< J. J = 0 BY ARInI. J >= I; C: 31:0 13-1>0 BY ARITh. 3>: 1; F = FACT(J-I) BY CASES. C FROO?; CASE 3-1 = 0; F = I; o+?* from the invariant *? FACT(J-i) a l BY FUNCTION. FACT(J-l)g CASE 3-1 > 0; I * ?ACT(J-2); ?* frola the invariact ?? FACT(J-I) = (3-1) * FACT(J-2) BY FUNCTIOl. FACT(?1); QED; Pla F * 3 = 3* FACT(3-I) BY ARITh. F = FACT(3-I). *. 3>0; ?* from PI and F2 we get: *? (3+1-1 :0 a> F*J = I) & (3+1-1 >0=> F*J = (3+1--H1) 0 lACT(Jo+1-2)); I a: I * 3; ?* fro. the assignment rule we get: s? (3+1-1 = 0 a> I : 1) & (3+1-1 > 0 :> I = (3+1-1) * IlCT(J+1--H2)); RF?aRN(F)s ?iguro 4.29 A nonrecursive function proved using recursion - It' - ,(x) is d-(in?d to be tie sum ci X and the external variable Z. and the assertion (F(Y) ? 0. p) has been proved to be valid. If point p dominates point q and the variable Y is not eodifled along any aimple path from p to q. then by Definition 4.4. the assertion is accesaible to q. and by Theorem 4.5. (F(Y) ? 0. q) ic a valid assertion. Nowever. if the variable Z is modified along a simple path from p to q the assertion (F(Y) ? 0. q) need not be valid. For Theorem 4.5 to be correct. the def?nition of accessibility needs to be modified slightly to acconodate functions that depend on external variables. Tf a formula con- tains a function that depends on?an external variable v. then for purposes of conputing acceaaibility. the formula is considered to conLain an inatance of v. ??..?cver the Lucal Ccntext CI??ker g.nurstes a NEW v instruction icr an eLternal variable v. it also generates a NEW f instruction for every function f that depends on v. In the example above. F(Y) ? 0 is in the Assertion Table when the V-code interpreter gets to point p. But between points p and q the variable Z is modified. so that NEW Z and NEW F instructIons are executed. When the interpreter gets to point q. the for- mula in the Assertion Table will have been replaced by F'(Y) ? 0. and a lEqUIME F(T) ? 0 will not succeed. 4.13 & Thep?? bor A???.sbi1.'rv Fur each point q in ti,e proMraI. tbe Lucal Cunteat Checker must Men--H Crate V-code that sets the Aaaerti?n Table to Aq given that it contains where p is the point in tho program that immediately precedes q lexi--H cally. For tbe simple constructs (the assignment statement and procedure call). the claim was made that this V-code consists of simply a NEW v for - 147 - each variable o+odiflad by the construct. In this section. a theorem is proved that justifies this claim. The thoorca will be used to show bow the computation of Aq can be performed for more complex control atruc- tures. Two assumptions will be made about the nature of execution ?atbs. Pirat. every poiut in the routine is assumed to be ruachable. That is. for each point p in the routine. an execution path from the start of the routioe to p is aaaumed to exiat. Thia easumption is valid given Approxi- motion 4.a. Second. if there is an execution path from p to q. and a path from q to r. it is assumed that these paths c?n be concaterntcd to form a path from p to r. Thia assumption is valid iven Approximation 4.1. fl?e fact that an execution path from p to r that passes through q can bo cut at q to yield a path itu? t to q .-?nJ a ??t1 fi?m q to r Is also used. but this property of execution paths holds no matter what (ji any) approximations are being used. Le?? 4.12. If point p dominates point r. there is a simple execu- tion path from p to r. ?. Because r is assumed to be reachable. there is an execution path from the start of the routine to r. Because p dominates r. p must be on that path. if the path is cut the last time it passes through PS the result will be a simple path from p to r. U nefinition 4.13. If p and q are points in a program. define Vp5q to be the sot of all variables Uat arc modificd by atomic actions thr..?h which any simple execution path from p to q passes. uefice Np5q to be the set of all assertions (a. r) such that r is any point and IL cont?ins a variable in Vp?q In Lemma 4.14 and Theorem 4.l?. p and q will refer to points in a --H 148 routine vith the fotloving t'Io properties: p docinates q (A.21) for any point r. there is a simple execution path from p to q (4.22) that (!oes not pass through r. L??nnt 4.14. If r is a point that is distinct from p. and r do.- inates q. every path from r to q passes through p. Proof. Let r be a point that is distinct from p and dominates q. Consider any path T from r to q. Us must show that T passes throush p. Since every point is assumed to be reachable. there is a path from the beginning of the routine to r. Cutting this path the first time it passtk through r. we obtain a path 5 from the beginning of the routine to r that does not pass through r. If 5 is concatensted with T. the result is a path from the beginning of the routine to q. Since. by property (4.2l)? p dominates q. this path must pass through p Since p is distinct from r. either 5 or T must pass through p If T passes through p we are done. Suppose 5 passes through p. Cut 5 at p to obtain a path from the beginning of the routine to p. Concaten- ate thia path with any path from p to q that does not pass through r; one ssust exist by property (4.22). The result is a path from the be?inning of the routine to q that does not pass through r, contradicting the assump- tion that r dominates q. 0 Theor? 4.15. Aq = Kp - M p.q ??. It is easy to show from properties of set subtrection that Aq K - Np?q if and only if the following thre? conditions hold: --H 149 Aq?C?p (4.23) A nM .4 (4.24) q p.q Kp Mp?q SAq The theorem viii be proved by proving eacb of tbe above conditions. Condition (4.23) viii be proved by contradiction; suppose it does not bold. Then there is an assertion (I. r) that is accessible to point q. but is not Inown at point p. Therefore (5. r) cannot be accessible to point p. so that eithera (I) ?here is a path from the start of the routine top that does not pass through r, or (2) a variable ins may be modified along a sieple path from r top. By property (4.22) there must be a simple path from p to q that does not pass through r. Let T be one such path. In case (I). concatenete the path from the start of the routine to p that does not pass through r with T. The result is a path fro. the start of the routine to q that does not pass through r. contradicting the hypothesis that (5. r) is accessible to q. In case (2). the simple path fr? r to p along which a variable in a is modified is concatenated with T. The result is a simple path from r to q along which a variable in It is modified. again contradicting the hypothesis that (It. r) is accessible to q. Condition (4.24) is also pr?ved by contradiction; suppose it does not hold. Then there is an assertion (It. r) that is accessible to q. and there is a simple path T from p to q along which a variable in 5 is modified. The points r and p must he dietinct. since if they were the same point then (It. r) could not be accessible to point 1. because of path T. Because 1?0 - r dominates q. by Leima 4.12. there is a simple path from r to q. and by Leima 4.14. this path passes through p. Cutting the path at p. we obtain a simple path S from r to p. Now cithera (I) the path T does not pass through the point r or (2) T does pass through point r. In case (1). concatenate 5 with T to obtain a simple path from r to q aloog which a variable of I is modified. contradicting the assumption that (a. r) is accessible to q. In case (2). cut T at the point wher. it psases through r. The ruult is a path from r to q. Since. by lemma 4.14. every psth from r to q passes through p. the path T must also pass through p. contradicting the assumptiun that T is a simple path from p to q. To establish condition (4.2?). suppose: (1) an assertion (a. r) is known at p. and (2) no variables of a are modified along any simple path from p to q. We must show that (a. r) is accessible to point q. We first show that point r doninetes p?int q. Let T be any path from the start of the rou- tine to q. fly property (4.21) p dominates q. so that T passes through p. fly hypothesis (I). either r and p are the same point. or r dominates p. In either case. T must pass through r. ?ext we must show that no atomic action along any simple path U from r to q nodifjes a variable in a. If r and p are the same point. by hypothesis (2) we are done. Otherwise. by hypothesis (I). r must dominate p. a?d then by Lemma 4.14. the path U must pass through p. fly cutting U the last time it p?sses through p. it can be split into toe simple path fi froi,r to p and a simple path T from p to q. By hypothesis (1). no vari- --H l?l --H able in I can be modified along 5. and by hypothesis (2). no variable in I can be modified along T. 0 Theorem 4.l? is used to derive the V-code that is to be generated for Lie various co?itrol structures. Given a point q in a template. a point p is located that satisfies conditions (4.21) and (4.22). After the V-code generated for point p that will set the Assertion Table to Kp an OPEN instruction is generated that will save K . At point q. a CLOSE instruction is generated to restore the Assertion Table to Kp and a NEW instruction is generated for every variable in Vp,q For this approach to work. it is necessary that the V-code generated for each template is bal- anced with respect to OPEN and CLOSE instructions. in the same way that open and close parentheses are balanced in expreesione. The notiona of "balanced" V-coda. and `.nests'. are defined recureively in terms of each other as follows. Defrjnjrjnn 4.16. A sequence of V-code instructions is defined to be balanced whenever it consists of a sequence of zero or more eleaents o+i' ?2 5n' where for each i in (1 ..n). s? is either a neat or a V- code instruction other than OPEN, CLOSE. or CLOSE-NEW. A "neat" is defined to be an OPEN instruction, followed by a balanced sequence of V-code instructions. followed by a (matching) CLOSE or CLOSE-NEW instruction. The CLOSE-NEW instruction is discussed in the next section. 4.14 Cnnditinnnl St??p??nra The template for the PL/CV IF rules is shown in Figure 4.30. Point P dominates both q and r. since the only way to get to the ThEN?or ELSE part La by way of the IF. Since the only simple execution path from point n to point q or r does not Pass through any points in the program. by --H I?2 (Do. B) ATTAIN E? ?t p ?I IF B IliEN DO; /? q (`II) o+ (body of Eh. ThEM part) (? E) ELSE DO; [I --HB) o+ (body of the ELSE part) (? E) (I a) Pigure 4.30 Template for the PL/CV IF rulee OPEN OPEN DONAIN ? PROCLAIM B o+ (V-code generated for the ThEN part) q?UIRE P CLOSE iROCLAIM --HB o+ (V-code generated for the ELSE part) ItEQUIRE P CLOSE i;?o+' T(s-llle)) (Do. DI END; ti PI (I --Hn) Figure 4.34 The basic WIlLS rule lEQUIRS lEQUIlI DOMAIN Nt? OPEN PROCLAIM PROCLAIM PROCLAIM REQUlgE 1?UIRE REODIRE DOMAIN CLOSE P1((x:LA)N P PROCLAIM D P SOME a FIXED. (a 0 & t) n TEa-Ills) Fi;ure 4.35 V-code generaLed for a WIlLE loop derivins a contradiction. Therefore the rule requirin ?(0lls) La usually easier to use. l?6 --H A typical way of provina terminatiun La to find some expression a involving variables that are modifjed in the loop body that has the two properties: (1) just before the loop begins execution. and at the top and bottom of the loop body. e is nonnegative. and (2) Each execution of the loop body reduces a by at leaat one. This termination proof can be expressed in pL?cV by lettins the predicate T be e <: a. Note that the formula: SO)E S rUED. (s >-- 0 ? E < s) is always valid no matter what ? is. choose S to be the maximum of 0 and 5. 5eca?se GOTO statements have been restricted so that they cannot branch from outside to inside the body of the loop. point p dominates both q and r. There is a simple path from p to q that passes through no other points in the program. There also is a simple path from p to r. the one in which the loop body is executed zero times. that passes through no other points in the program. Therefore. by Theorem 4.15. Aq Kp - ilp.q and Ar ?p - Np.r But Vp?q and ?p.r are each the set of variables that can be nodi?ied by the loop body. Given Approximation 4.8. this set is just the set of variables that can be moditied by any statement in the loop body. The V-code generated for the WItiLE statement is in Figure 4.35. A sequence of hEW instructions generated for point q are used to set the Assertion T?bla to A? - M???. An OPEN instruction is used to save a copy of A Np?q and the CLOSE instruction generated for point r restores the p Assertion Table to that value. - 1?9 - The NEW in.tructions Ust muat ha gen.'rat?d for point q are not known until the body of the loop has been processed. This forward referencing problem is the major reason that the V-code instructions can--H not be interpreted as they are produced. Instead. the output V-code je eeved and interpreted after the entire proof hae been prucessed. In the implementation there is a V-code instruction of the form MULTINEW b. where b is e bit string. There is one poaition in the string for every program variable. The action specified by a ?WLTlNEw instruc- tion is to perform a NEW for every variable whose corresponding bit is on. When the V-code for a loop is being generated. room is saved for a KUL- TINEW instruction. and the location of titat ?oom is remembered. After the body of the loop has been proces?ed. and it is known which variables are changed. the appropriate NULTINEW instruction is generated and installed in the sp?roprisLe place. The use of the COTO statement is generally discouraged by advocates of structured programming. One exception to this dictum is the use of the COTO statement to exit a loop. (253 In an attempt to clearly distin?uish between acceptable and unacceptable uses of the COTO. the LEAVE statement has been introduced to pL?I. A LEAVE statcment is just a cuphemism fur COTO L. where L is the statement just after the loop being left. If a WHILE rule being proved using the rule in Figure 4.34 contains a LEAVE statement. the assertions P and --Hn must be known at the points preceding each LEAVE statement for that loop. But in general these asser- tions do not have to be valid when a LEAVE statement is executed. For example. if the statementI IF Z ThEN LEAVEl appears in the body of ? loop (in a place where the LEAVE can ever be axe- 160 - cuted)? ? will ?ot be Inown just before the LSAVII. The solution to this problem is to eslociate a third predicatn s? called the "exit condition." with every loop. The exit condition is vhit is proved to hold when the execution of the loop is complete. WHILE loopo can optionally be preceded by a line of the form ATTAIN E to indicate what the exit c?ndition is. If the ATTAIN line ja not present. the exit condi- tion defajlts to P g There are two pert. to the proof that E holds when a loop execution completes. The formula E must be known just before every LEAVE that exits the loop. and E must be shown to hold when the loop terminates normally. ILl the case of UNJLE loops. this second condition is equivalent to showing that E follows from the cet of formulas: Aq U (Fl u (?Bl . (5.26) To accomodate the LEAVE statement. the V-code in Figure 5?3? must be rodifi?d 3s follows. The final PROCLAIM is changed to PRuCCAIN E, and the following V-code: PR(CLAlM 3 RE?UThE E CLOSE (V-code generated for proof of E) is inaerted just sft?r the PRt)CLATM P and be?ore tha P.poCLAIM T. In many cases. E will follow by automatic rules. If a proof ie required to estab- l?sh E. it may be placed between the ASSUME end ARBITRARY lines in the loop body. This mechanism is fairly clumsy. A cleaner solution would be to require the assertion B -> E before the loop begins and at the end of the loop body. The problem with this solution is that the user must write 161 essentially the ea.e proof. that --H? :? 5 follows fro. (4.26). twice. A bettor solution is proposed in section 4.l?. 4.16 I1flflL Loon. Wirth (71) gives the following rule rule for UNTIL loops: (Pi S (Qi (Q & --HBJ s (q) (P) DO UNTIL(B) S END tQ) This rule cannot be easily adapted to PL?cv. because two proofs involvin: the body of the loop nust be written. and in a PL?cv proof. the body of the loop is only written once. Any UNTIL loop of the fore: DO UNTlL(B) END can be reduced to a WHILE loop and tvo assign,ent statenenta ?s follows: f :--H--H `I'D: DO WHILE(--HB f :--H- `O'B; END; ?here f is 5 Boolean variable that does not appear anywhere elee in the prugree. lLtduction can Lberefure be used to obtain a proof rule o+?ur U:.?1L loops suitable for use with PL?cv. Coebining the proof rules for assign aunt end WiilLE loops yields the proof rule in Figure ?.36. (The rule is valid only for loops for which there are no LLAv1: statenents.) The UNTIL rule in Figure 4.36 is another example of a poor use of reduction to obtain proof rules. The rule is as conriete as (he assi?n- Cent end WilliE rules are. but in ;ractice it is clumsy to use. Th loop - lb2 - (7 P('l'Bllf)) (7 SQIE a FIXED. (a>:O ` T)) Do UNTIL(B); A?E?TRAR? L MIT WiE?E P ? (--Hfl 1)1 ARBITL%BY a FIXED WHERE T; o+ (Predicate calculus proof) -Tiolls) o+ (Loop body) (7 P['o'Bllf)) (7 --HB o+> Ts-llla)J END; (I P('o'Bllf)J Figure 4.36 A proof rule obtained by reduction ?a p o+/ (7 P) (1 SOME a FIXED. (a)O L T)) ATTAIN E; DO uNTIL(B); ASSUHE P; ARBITRAR? a FLIED WHERE Tg (Loop body) 1? B o+> El (7 --HB --? PI (7 --HB --> -T(OllsJJ (7 --HB o+> T(a-llls)l ElID (I El Figure 4.37 Tbe PL(CV UNTIL loop rule inesriant P is usually of the for. (f o+> P1) & (--Hf > Pi). vbere P1 holds at the beginning of the first execution of the loop body. and P2 holds at subsequent executions. Proofs in the body of the loop vill eake heavy usa of the CASES rule. split on f being sitber `01B or `l'B. Essentially. the use of the verieblo f is a trick that allows the two proofs required by Wirth1a rule to be packaged together in one lo?p body. - 163 - REQUIRE P REQUiRE SOHE a FIXED. (s? & T) ?EW -rEollal CLOSEl PROCLAIM I 1necessary o?ly when loop baa LEAVE statements Figure ?.3S V-code for UNTIL loop. The rule used for the UNTIL loop is shown in Figure ?.31. In that rule. the loop invariant P is shogn to hold at the top of the loop body by shoving it holds before the loop begins. and by showing that it holds at the end of the loop body if the loop body is to be executed again. The exit condition I is shown to hold after the loop completes by showing that it holds just before every LEAVE statement that exits the loop. and that it holds at the end of the last execution of the loop body. The termination rule is similar to the one used for WHILE loops. The assertion required before the loop is SO?lE 5 FIXED. (5 ? 0 ? T). rather than SOME a FIXED. (a >- 0 & T). reflecting the fact that the body of the UNTIL loop will be executed at least once. For the sane reason. the required assertion involving -T(O/ls) appt'srs at the bottom of the loop. As was the case in the WHILE loop. point p dominates point q and there is a simple path from p to q that pasSC. through no points in the program. so that An a Aq - Mp?q Since the GOTO statement has been res- trict?d so that it cannot enter a loop. point p dominates point 5 as well. Mowever. Theorem 4.15 cannot be applied to pointa p and a. Since the loop - 164 body is executed St least once. the?e can be points in the proaram that are on every Simple e:ecution ,ath from point p to point a. 8owever. there is a simple path from a to r that does not pass throush ary points in the program. And if there are no LEAVE statementa for the loop. 5 dominates r. Then. by Theorem ?.l5. A5 - Kr The corresponding V-code is that shown in Figure 4.38. with the OPgN and CLOeB atttecents d?lcted. But this V-code is only correct for loops for which there are no LEAVE statements. In the geutral case. the following approximation is used. Ann?oxi?arinn 4.17. An execution path may be extended from the top of the body of an U?TiL loop. to the point just after the loop. Given Approximation 4.7. the effect is as if the statement: IF `O'B ThEN LEAVE; Vere inserted at the top of the body of each UNTIL loop. Given the bogus execution path from q to r provided by Approximation 4.17. Theorem 4.15 can be applied to to points p and a. and VS have A5 - Kp Mp?? The OPEN instruction in Figure 4?38 saves Ap --H Np?? and the CLOSE instruction restores the Assertio,. Table to this value. The Proof Checker does not keep track of whether ?n UNTIL loop contains LEAVB statements; it unconditionally generates the OPEN and CLOSE instructions Because of Approximation 4.17. assertions that are known at the end of the loop body and before every LEAVE statement for the loop should be sccessible to point a but will not be recognirtI as such by the Pruof Checker. Any such asatrtiona that are subsequently needed as hypotheses must be explicitly included as part of the exit condition of the loop. l6? I a La fn I a L TO V ST xa ?lLE(I <: c)a `ND I a' I + K END; (a) Figure 4.39 Reducing an indexed loop to a WIjiLE loop and assignments A..17 Tn?.xp? 1.ppna The indexed loop in Figure 4.395 can be reduced to the ?I1L? loop in Figure 4.39b. assuming K is alvays positive. For compatibility vith rL/I (49) the sensntics of PLIC indexed loops are slightly more complicated. Copies are made of the expressions L. V. and K before the loop begins execution. and the copies are used to control the loop execution. Thus. if V and I have side effects. those effects are performed exactly once. and if the body of the loop modifis. variables in V or I. these nodifications do not affect the loop control. Hovever. some restrictions have been added to PL/CV: expressions cannot have aide effects and the control variable I and all variables in L V and I are readonly in the body of the loop. Civen these restrictions. the reduction shown in Figure 4.39 is valid. Note that for the reduction to be valid. it is vital that the vari- able. in I are not modified by the loop body. and that the variable I is modified only by the indexing mechanism. In particular. if the variable I or any variable. in I are external. procedures that indirectly o+odify any of these variables are not allowed to be called in the loop body. A second conet'qu?nce of these rcatrittions is that every indexed loop muat terminate. Therefore the terminetion parameter is omitted from the proof rule for ind?xed loops. - 166 - (? L > U+l --> PEI+?/IJ) (? FridlI)) Do I L TO U BY I; ASSU?(E P; (I PI (I L <-- I <-- UJ (loop body) rl+llll) BY (1 L ? U+l ? ?(ullr?) I? F?L-llll)I DO I L TO U BY It AISUME F(I-lllIJt (I PI-lllI)) (I L < I <-- UJ (loop body) (? Pi END; (I F(U+lllI)J (I PEUllIl) (a) (b) Figure 4.40 T%ao?proof rules for lEAVE-free indexed loop. PLLllI) BY L <-- L BY Alim; L ? U+j :> P(Utllll) BY I s L; I <- I > U+l -? F(U+lllI): DO w?ilLE(I <-- ASSL?j F & (L < I) & (I ) Uti --H--H> P?u+IllIJ) ARBITRARY 5 W?ERE I-L < I <-- < 0) B? APITH, L<-I; (loop Lo?y) P(l+lllIi BY L <- 1+1 BY ARITH. L<--I; (1.1 > U+l) BY ARITH. I <-- 1+1 > 0+1 => P(U+l//I)t 1 :--H 1.1; L <-- I; I ? 0+1 `> P(0+lllI); D?D; P & (L <- I) & (I > 0+1 --> P(I+lllIl) & (I 0+1) BY ARITH, --H(I <-- P(0+lllIJ BY CASES, (I 0+1) 1 (I > 0+1)t Figure 4.41 Using tbe WHILE rule to prove an indexed loop --H 167 - In an indexed loop. the loop body is executed once for each element of LI)e aet (L ... V) Lhat is congruent to L mod K. uhen thia construct La used. K will almost alwaya be 1. and ?he loop body will be executed once for each element of (L ... u). So that the proof rule for indexed loops doea not have to involve congruencee. K ia restricted to be I or -I in PL?Cv. Wirth (?O) made the aame decision when he designed PASCAL, Only the proof rule for the ceac of K - I will be diacussed beret there is a similar rule for the case of K -I. For any indexed loop that uses an increment greater than 1. there ta an an equivalent loop of the formi DO J 0 TO V fly It I ;- L + KaJt FND; that is allowed in PL?Cv. though it might be argued that such a transla- tion is another misguided use of reduction. Two proof rules for indexed loops for which there are no LtAvg stat? ments are shown in Figure 4.?. It turns out that rule (a) is more con- venient for loops of the form DO I 0 TO ?I-l and that (b) is more con--H wenient for loops of the form DO I - 1 TO fl. Since the latter for of loops seems to be more common among pL?I programmers. rule (b) probably should have been used in PLICv. but rule (a) was chosen so that the Proof Checker would not need to test that the loop invariant is of the form I-1111). In PL?Cs. the value of the loop index is set to an undefined value after the loop completes execution. ?Iewly declared variables are set to the same undefined value. If a variable containing this value is accessed. a run--Htime error occurs. l6S (T P(w/l)l (1 L ? U --> ATTAIN E; DO I L TO U BY l? ASSUtE Pt II P) (I L <-- I (? I U --> (P(I+i!Il))) 1? I u --> E?D; fEl visure i.A2 A rule for indexe? loops vith axitn As was the case with newly declared variables the undefined value In nodelled in PL/CV with intentional incompletencas. The proof rules in vig?re ?.iO do not allow any conclusions to be drawn concerning the value. of the loop index after the co?plstion of the loop Nc'te the similarity between the rules for indexed loops and msthemstical induction. Any proof involving an indexed loop can be rewritten using the WHILE rule. The resulting proof will be similar to the proof in Figure 4.41. (In the figure, assertions that are justified b? are the assertions one would have to prove if one used the indexed lo?p rule.) The proof using tie WlllLE rule is much more cocipliceted than the proof that uses the indexed loop rule. The indexed loop construct is an example of a succcssful use of reduction to derive a proof rule. The proof rule that is used for indexed loops with LEAVE statements is shown in Figure 4.42. Since the value of the loop index is not known sfter the loo? completes executi?n, the exit cundition E is nut allowed to contain an uccurr?ncc of the I l??I.?x 1. if no ATTAIN 1 u?t Is present. th--H d..f?.nl t `sit cnndir i'?n is p(n+ i?/i1 - 16? Vho rule In Jigure 4.42 is cot as elegant as the rule in ?igure 4.405. Let us refer to V - L + I as the number of tisses the loop hod7 In executed. A properly written loop will work in the case in which the loop body &s executed zero tiees; that case will fit natursily into the logic of the program. But typically. the loop body will never be executed a negative number of times. That is. the assertion V - L + 1 ?-- 0 csn be proved at the point just before the loop begins execution. When using the rule in Figure 4.AOa. the precondition L ? U+l z> P(V+llll) can be proved vacuously for a loop that never executes its body a negative number of times. But when using the rule in Figure 4.A2. proving V - L + I > 0 does not vacuously prove the precondition L > V > K; one must also prove L 1+1 > E. A better rule would require that: (1) P(I+lllI1 to bold at the bottom of the loop. (2) L ? U+l --? B to hold before the loop begins. end (3) ? : :1+1 s> Z to be a consequence of the formulas (D) u Ap This rule would not single out the loop executit's zero times as a special case. Unfortunately. there is no good syntactic place to put the proof of (3). The accessibility calculations performed for indexed loops are the same as those done for WilLE loops. The V-code generated for the indexed loop is shown in Fi?.rs 4.43. 4.18 Ju?n Ststernpnrs fl?re are three kinds of jump statements In FL?cyt the RETU?N statement. tie LLAVE statement. end tic COTO statement. The proof rules for each of these statencets are shown in Fi?rs 4.44. itecail that the assertion ftF.QU1?F, pUI??i3 RE?UIRE L ? u ` M lIkEN DO; FOUND LEAVEg END; IF A(I) SET THEN Do; FOUND `I'S; LEAVE; END; I :--H I o+ 1; ligure 4.30 An erroneous linear search program bore. Since the location of the beginning of the nest in which all the variable modifications must be located is not known until the label is encountered. a fairly elaborate system of bookkeeping would have to be devised to generate the proper NEW instructions. The PL?cs langauge is advertised (241 as an 5a1,,,,st aubset" 0 ?L,C. Included in the "almost" part is the LEAVE atatenent. which IaN has recently added to PL?I (44). In PL?I. the DO a'nd ENI) that are t'sed to specify grouping in IF and SELECT statements actually conprise a degen- erate loop whose body is executed exactly once. In fact. there is just one loop construct in PL/I. The phrases wlIlLE(B). UNTIL(4), and I : L TO U ST K are considered "options" and can be used in any or all comhjnation.. in conjunction wiLh LF'AVF. Jn an attt.m?t to introduce some discipline into the language, the designers of pL?CS saw fit to ssake the restriction that at most one option can appear on a loop construct. and only 1001)5 with such an ui'ti,n can t, exited via a LLAVE. A reanon fur fort,icttlL.ng i.r.AVE stat&.rn.?nts in d?'t.encrate loo?s is `hat Lhoy are t'rror--Hj'ron?. As an cxnn'plc. consij..r (he int`,nJ,'d Iinrar srarch - 182 COTO Lg C('ro L: COTO L ATTAI?I a; La ; ATTAIN Li DO; LEAVt La LEAV? LI LEAVa Li END; (a) Fisure ?.?l Replacing the COTO statc1enL with the LEAVE stateusnt ATTAIN E; L: LO inilLE(s); ASSLIE F; can either be a pri:itive atate:ent. such aa an assignment atatement or a procedure cell. or it can be an omnibus statement. The ayntsx in Figure 4.35 should not be taken too aerioualy. It uaes as little punctuation sa posaible while atill avoiding ambiguity. Con- structa of any conpiexity vritten in this syntax are difficult to under atand because it does not have enough redundancy. I have experimented vith a few variations on the syntax. some better than the one in Figura 5,35. but I do not have a aingle solution with which I sm completely satisfied. Every lp?n and ajjL in a program is associated with an omnibus statement in the folloving atraightforvard manner. If the innn or maLL' is folloved by a label. aasociate it with the amallest omnibus statement that - An? --H t) `La a vh?n l'?n ( contains the lww or LL and begins with that label. Xf thero is no such omnibus statement5 the program is syntactically incorrect. If the laaa or ULL is not followed by a label. aasociate it with the amalleet omnibus atatement containing the loop or ?`. The semantics 0 the omnibue statement thou are given operationally aa follows. To perform an perform ita . To perform a in the .) To perform a beginning with iiLtLci. first evaluate the anolean expression. If the value is o+l.B. perform the firat . To perform a 1flfl?. tranafer control to the beginning of the 0 & T must be known before the Afl. and a 0 and T[s-Ills) must be known before every lnDJL associated with the statement. The formula 5 is known at the beginning 0 the first followin8 a Xtzii 5. --H8 is known at the beginning of the second following the xhtjL. and E is known after the omnibus state--H meet. All of the control constructs in PL?cv (except indexed loops). and some that are not. are special cases of the??mnibus statement. Some exam--H plea are shown in Figure 4.56. The proof rules for these control con- structs can be derived by writing the equivalent omnibus statement and tha proof rule for that statea?nt. TI? rule ust'd in rL?cv for the U?TlL loop was first discovered by this process. If the omnibus atat.nent is used in an exprcssion language. evcry --H 189 - I? stateuent: Aa `(hia 3 - 0 ? h,r? p.r then generate V-code for the tail. and finally generate a PsOClAIM 1. 1cr a tail. generate V-code for each atatenent. and than generate V--Hcoda for the terninus. The V-code generated for a terminus depends on which of tha tbrea kinds of termisus it is. For a ??? the V-code: BFr?IRE F kt?UIkE a 0 ?QtIRE Tta-lllsJ is generated. For an uiL. the instruction REQUIRE I is generated. For a terminus of the form h?n fl . one of the V-code sequences shown in Figure 4.58 is generated. Which of the three sequences is used d???nds on tie position ot thn t?rminus vis--Ha-?ia the least upper bound. The iuur cases. and the sequcoce that is used in each case. are listed in Table 4.57. if s and t are the points In the pro?rem just before the start of each tail. by the sane argument used for the IF statement. A5 At Therefore. the V-code generated for the first tail is enclosed in a pair of OFIli and CLOSE instructions. The tail imnediately following the :La will be referred to as the nsin tail. The V-code generated for the main tail must set the Assertion Table to Aq which we have seen is equal to Kw - If t?e omnibus statenent contains exactly one ?. either case (1) or (2) in Table,4.57 will apply to every terminus beginning witb Xh?. In each cane. V-code in generated for the tail containing the ULL second. Therefore the lent V-code instruction generated for the lain tail aunt be the REQUIRE ? generated for the &Li& that in the lenet upper bound. There- fore. after the V-code generated for the lain rail is executed. the as?? tion table will contain Xv Civen that there in only o?e ?. Vb.q ie Cipty. and 5? Xv - M w.q Iext consider the case in which there is lore than one ijL. In cane (1) or (2) of Table 4.?. the tail that contains the lesar upper bound contains every ?; the V-code for that tail in generated second. The last V-code instruction generated for the lain tail will be the final CLosg-?Ew instruction in yigurs e.58c that is generated for the least upper bound. After the V--Hcode generated for the lain tail in executed, tbe Assertion Table will therefcre contain Xv - CwTE? ? A D?C1SIO? b,,KOCEDURE FOR T??ANSFORNAT1OMB 5.1 Tranafo o+?d ???????? The V-code Interpreter uses two decision procedures 10 implement the PLIcV automatic rules. Tbe first of these two decision procedures is dis- cussed in this chapter. An algorithm is given for finding all conse- quencta of the axioms in Figur?? 1.1 and 5.2. The symbol is used in the axions to stand for either or <>. depending on the type of the operands. Civen any set TA of transformation axioms of the form R S vs say that a 5transformation5 can be applied to the formula P to yield Q when- ever there is an axiom R 9 such that Q can be obtained by replacing in? a single occurrence of 5 by 9 or a single occurrence of 9 by R. Define the notation ? ?T Q to mean that a transformation can be applied to P to obtain Q. Then define tbe relation Et to be ?T? the reflexive transitive clos'jre of ?T If ?T is defined with respect to a set of axioms TA. then a sequence of formulas P0. PPa such that for each i in (1 ... n). ?i?l ?T ?i is called a 5derivation of ?n from using TA.5 and ? ET Q if and only if there is such a derivation. The problem discussed in this chapter is Lhat of computing the rela- tion =T defined by the axioms in ?igures 5.1 and 5.2. The solution is to show how to compute a normalization function N with the property that NI(PJ ???? if and only if P ET Q The function N is baaL'd on a replacement system. A replacement sys- tea cnnslsts of a dutnein Ji and a mary reintIon ? ths? Is a suhaet of D D. A ae??n?u r0E'n wh?ie fut- each I I a Ii ... a - l?6 - --H l9? P a Q (where P and Q conrain no variablen and have the same value) c:> <=> P <=> `O'fl --Hp a <--> `i'n = a c--? a =- `l's p <:> --Hp (`0's => = `l's (`I'D => P (P => `0's) = --Hr => `l's) = `l's (P --> `l's -> --Hp) = --Hp =? p) = --Hp (a 1 `c's) = a (a `l's) = `l's I a) P (a 1 q) (Q I a) (a I Q) I 1 F I (Q I R) (a & `c's) = `C's (p & `l's) a (a & p) =- a (a & Q) & I P & (Q & 1) (a & Q) (q & a) (a & --Ha) = `c's Figure 5.1 The Tranaforeation Axiom.. `art I a1?1 ? at. is called a derivation of an from a0. The length of the derivation is said to be n. Note that the notion of a derivation baa been defined with respect to tranaforeation axioms?nd with respect to replace--H ment rules. The two ?inds of derivations are quite similar. the differ- enco between them is if a can be derived from Q using tranaforeation axioms. then q can be derived from a. but aerivstions using replacement rules in generel work in only one direction. Rosen E67) has defined a special class of replacement systtma called subtree replacement systems. In a subtree replacement Cystem. the domain is ii set of trees. and the relation ? is defined by a set of replacement ruirs of the form ??o+ Q. wher? P end Q are `rP?s. We say a r.p)s?em.nt - 198 - =--H (Q --H= (?p + R) (Q + 1) < --H--H (P + R) < + a) (P < < q-l) < =- (q > (p <- --H + it) <` + a) <-- Q) (P < Q+l) (P <-- Q) (9 >-- ? 9) =--H (P + it) > (Q + a) ) 9) (P )-- Q+l) (P > 9) (9 < (p >: 9) --H (P + it) )-- + a) >. 9) > Q--Hl) >-- 9) (9 <-- (P + 0) P (P'+ 9) + a p + (9 + a) (F + 9) (9 + P) + p) --H= 0 - 9) =--H p + -Q + 9) z--H (?P + -9) --9 :- 9 x 1) P 9) (9 x x 9) x a p x (9 x a) at I) P (P ? I) P Figure ?.2 The Transformation Axioms. Part 2 rule P 9 can applied to a tree it to obtain 6 whenever 9 can be aubsti- tuted for a single occurrence of P in I to yield 6. The relation a --H 6 than defined to bold whenever there is a replacement rule that can be applied to a to obtain 6. Suppose it is possible to derive a formula 9 from P. At any point in the derivation. there will be in general a number of replacement rules that can be applied. if it is impossible to select a rule to be applied --H 199 --H that results in a dead end It from which q cannot be derived. the system is said to have the Church-aosaer property. Formally. the system is defined to be "Church-Ro.sor" whonevcr for all P. Q. and 1. ? ?a Q and r ?a ft imply the existence of an 5 such that Q ?e Sand 1 ?* 5. That is. if two derivations that each begin with P branch off in different directions. they can always be brought back together with a suitable sequence of replacement rules. A replacement system is defined to be "finite" whenever there are no endless derivations. in a finite replacement system. if one begins `,ith an element. and repeatedly applies rules. one will eventually obtain an element to which no rule can be applied. Such an element is said to be "irreducible.5 Whenever a finite replacement syatCI is Chuech-Rosser. it is said to be "confluent." These definitions have been adapted from ones in a paper by Sethi (69). We are now prepared to define the normalizing function N. it is defined in terms of a confluent aubtree replacement system called TRANS. which will be presented in section 3.2. if P is a formule. def?ns ?LPJ to be the unique formula Q such that P ?* Q and Q is irreducible. l;[p? is called "Lhe normal form of P.5 The following theorem shows that if TItANS is confluent. then M truly is a function. Thenre 5.!. Given a confluent repl:icement system and an elenent P. there exists an element Q1 such that P ?a Q1 and q1 is irreducibla. Moreover. if there exists an element Q2 such that F ?e Q2 and Q2 is irreducible then Q1 Q2. Prn?f Begin with P and keep applying replacement rules. Because the system is finite. eventually an irreducible element Q1 will be derived. if there were an irreducibla element Q2. distinct from Q1. such - 200 the I ? ?2 by the Church-Roeear property. then vould be an clement B such that Q1 ?s a and Q2 --?* a. Since Q1 and Q2 a:e irreducible. both derivations must be of length rero. Therefore. Q1 I Q2 contradicting the assumption that Q1 and Q2 are distinct. 0 A set of tranafortutiun axioms iL extracted from the replacement system as follows. For formulas P and Q. P Q is an axiom if and only if I Q is a replacement rule. fl?e folluwing theorem ensures that the nor- malization function U has ti?e desired property. Th?o?e? 3.2. If TIANS is confluent. then for any formulas P and Q. I ET Q if and only if ??PJ luitil. From the definitions of T and ?. we have I ?? Q if and only if I Q or Q I. SLppose N?PJ a. Then I ?a g so that ? T* a. and there- fore 5 =T a By the same reasoning. q ErR. Since ? ErRand aT Q? ? --H=T q. To proys that I ? q implies N?IJ ?FQJ it is sufficient. by Leama 6.10 (?hich will be proved in section 6.7) to prove that I 4?+T Q implies a N?QJ. If r T ? then either p q or Q I: assume without loss of generality that I --H Q. N?IJ can be computed by starting with I and repeatedly applying replacement rules until the result is Irreducible. Because TRANS is assumed to have the Church-Rosser property. no matter what the first step of the derivation is. it will lead to N[(FJ. There- fore. we can require the first step of the derivation to be I Q. and tbe?e will be a derivation q it. where it is lrr?Jueible. Becaube I ?s g N?PJ a. Bt'ceuse ? ?t it N?(?? it. Tht'reore it?pJ a t,.???. 0 1? th? Cat aCrt ion. thC r.I?la?c?Cnt syfltt'm TRAitS Is ?resented. In - 201 acctlons 5.3 and 5.4. TRANI ii ?hown to be confluent. then. in section 5.5. an elgoritbi for computing the normalization function le presented.5 Let Til be the set of axioms obtained directly fro. the replaceneot eye--H ten. In eaction 6.6. the axiom set TRI is shown to be equivalent to the axiome in Figures 5.1 end 5.2. 5.2 Iha svsre TRANS The domain of TRANS is the set of all PLIcv formula trees. with two extensione. the pairs of terms "formuls" and "tree." "operator" and nnode.s "operend" end `?offepring." and 1?msin connectiveh and "root" will be used interchaitgsbly. As in most computer languages. there are no negative constants in PL?cv. When one writes -3. one is applying a unary operator to the con- stant 3. The domain of TRANS includes negative consts?ts. It is impor--H tent to keep straight the differences among the sign of a negative con- stant5 the unary negation operator. and the binery subtraction operator. In the rest of this chapter5 the unary negation operntor will be raised slightly. as in A. to help distinguish it from the hinary subtraction operator5 an occurrence of which appears in (0 - A). Negative constants will he indicated by underlining. For example5 the additive inveree of 3 is written 1. Trees containing nodes of arbitrary out degree are also needed. In most computer languages. there are unary operators and binary operators. end possibly some functions with a fixed number of arguments. The correaponJi?? nodes in ptrse trees h?ve one. two or some fixed nu?ber a of offspring. For example5 the expression (A + I + C + fl) is ususIly p?r.tJ aa (((A + I) + + D). Tie duwein ol TRAIS sill Intlude trees - 202 - with sasociative operators that have any nonnegative nuiber of offeprius. If a node p has two or more offspring. it viii be written P ?2 P .. P0). If it has one offspring. it will be written (p r). and if it has zero offspring. it will be written (p). As discussed in section 3.8. the I and g nperators in ?L/cv are not restricted to be binary. Though I believe that these "multiary'1 operators correspond more closely with people's intuition about ? and I than the binary operators. they appear to be more trouble than they are worth. They rake data str,ctures. algorit!.?s. and proof rules more complex. and in ter:, of wnat is and is not a valid PL/cv proof. the only place it ma?'es a difference that these operators are not binary is in the CAS?S rule (see section 3?). In this and the remaining chapters. the PL?cv operators ? and I will be assumed to be binary. T?e donain of T?A??S includes quantifjed formulas. Quantifjer count representation (see secticn 2.2) will be used to represent these formulas as trees. Since the only replacement rules that alter the quantifier structure of a foriula are the folding aules' SO? a. `l's `1'S SC'? z. `0'S `0'S ALL i. `I'S `l's ALL a. `0'S `0'S there is no need to worry about changing the quantifier counts within bound variables. A set of schemata will be presented from which the rules can be obtained. A ?chrma consists of an ordcred pair of trees. Each leaf of each tree is either a constant or a variable called a parameter. Some of the achemata are shown in Table ??3 To obtain a rule from a scheme, one consistently substitutes a tree for each parameter in the scheme. Some of 203 T?Dlc.tln ii,1?. `i'b :> ? `00B --> P ? `I'S p :? ?j?3 ? 0111 P --? `C'S ? --HP P --> P ? `I'S P --? --HP ? --HP --Hp :> p ? --H? ?p??i?,?len?p Mu o+l'B <--> P ? P P <--> `I'S ? P i011 `0'S ? --HP P <--> P ? `l's P --HP ? `0'l --HP <--> P ? `C'S Ifln??? P--Q ? P-Q-C P. <-> ?5. ?. or some operator for which there are only Folding Rules. First check whether every Qj is a con--H stant; if so. apply an appropriate Folding Rule. The result is irreducible because there are no rules that can be applied to constants. If no ?i is a constant. use any of the rules in Table 3.3 that can be applied. If a rule is applied. the result will either be a constant. or of the form Q?. ?? or The result cannot be of the form or Mi. where Q1 is a con: stsnt. for if it were. both ?l and Q2 would have to be constants. and a Folding Rule could have been applied. Since each ?i is. by induction. a nornal for. and the only replacement rules in which the main connective of the left side is are Folding Rules. the result is irreducible. Finally. if p is and no rules have yet been applied. arrange the two operands in lezicographic order. The second case is that p is an associative operator. First. flatten each ?i wbose roet is p. fly induction. tin subtrees introduced are irredu- cible. and therefore cannot have p as their root. Next. use a lexico- graphic sort (1) to put the subtrees into order in linear time. After the subtrees have been sorted. all the constants will be adiscent. all identi--H 22.' eel subtreea viii be adjacent. and all subtrses 0 tbe for. --H? vill be adjacent. as will a'ibtrees of the for. a. All the constants can be easily located and folded together without disturbing the sort order. if the resulting constant is the identity ele- ment. delete it; if it is the annihilating element. replace the entire suhtree with it. If p ia & or I. make a pass through the list of sub- trees. deleting all but one duplicate of any subtree in the list. All cancellations can be performed in linear time as well. All of the suhtrees R1. R2 o+. R? will appear together. ?oreover. if any of the subtrees `E) IRn are present. they will be in that order. A simple linear algorith. that is similar to a merge can be used to locate and delete all the -a and 5 pairs. The same approach can be used to locate --HR and I pairs for the False Introduction Bule. Finally. if the above deletions result in a p havin8 a ai?gle operand 1 the normal form is 1. If the deletions result in p having sero operanda. the normal fur. is the identity elenent of ?. The third case is that p is -o+ Then the only rules that can be applied are Folding. Double flegation. and ?egation Distribu?ion. The first two rules will result in irreducible?forms. Let us consider the aubcase in which the tree is of the form P?. where PI is of the form (Q1 + q2 + ?n?? and each ?i is irreducible. Applying legation Distri- bution yields (?Q1 + ?2 + ?n? now each ?i must be normalized. Because P1 is irreducible. no ?i can have o+ as a root: if it did. the Asso--H ciativity Rule could be e?plicd to i'1. Tt?r?fore. escb nt?d only be checked for Double ?iegation and Folding. and these rules result in irredu--H cible forms. Ilowever. the resnltin? tree (Rj + ?2 + fl?) will in genersi not be - 222 - irreducible. Nost of the rules for + cannot be applicd. because if they could be. there would be corresponding rules that could be applied to and Pi is irreducible. Folding cannot be applied. since two constants and 1. must correspond to constants Q. and Q?. Associativity carn?ot be J I J applied. aince if a. is of the form (s + ...). Q? must be of the form (5 o+ ...) and then the Negation Distribution Rule could be applied to P1. identity Elimination cannot be applied. because if R. is 0. Q. must be 0. I I This leaves C?mmutativity as the only rule that can be applied. But there is a trick that can be used to make it easy to apply the Commutativity Rule. if the ordering among symbols us?d to represent trees is chosen so that - is the smallest, symbol. and all constants are greater than noncon- atants. will take the form: o+ 5n + ?l + 4 Tm + c) where t?e root of each 5 and T is not -. and c is a constant. (in sen- 1 I eral. so::e parts of the above may not be present). Them the normal form of is: (-T1 + -T2 + Tn + Sj + + 5m + where ? is the constant whose value is the same as c. The normal form 0 ?? can be computed from P1 in linear time without sorting. The fourth case is that p is -. Subtraction Eliiination Rules are used to replace P - Q by P + Q. Replace -Q by the normal form of q (as was done in the third case) and proceed as if p were +. The final case is that 0 is a comparison operator. The Comparison Rules are used to turn comparisons to aubtractions. Then the Subtraction Elimination Rules re used to turn the subtractions into additions. and a Folding Rule is applied to 1. The result will he of one of the forms 22? (? + Q) p 0 or (P + -q + ? p 0. where P. Q and 1 are all irreducible sod ? is either : operators Ln P. If n is the size of P. there can be only 0(n) --H operators in ?ItP?l no more can `ofit" without having subtrees of the form --Q. Therefore. NI(PJ can be larger than P by at `oost a linear factor. a simple charging argument can be used to show that N?PJ is com- puted in 0(n2) time. where n is the size of ?. The elgorith. processes 22? operator node?p b- first normalizing its operandn. And then combinima the normalized forms. The aize of the normalized ope?snds is Linear in the size of the original operands. and the time needed to combine the. is linear in the size of the normalized operands. This time is charged to the operator p. Each operator in the fcrmuls gets 0(n) time charged to it. so the entire tree is nor?nlir.ed in 0(n2) time. A rule for the diatribution of multiplication over addition could have been included. but tb?n hffP? could grow exponentially with P. Dexorgan's Laws. the logical analogue of the flegation Distribution Rule. could also have been included. but to maintain the linear space bound between h?P? and P. the rule F P would have been required. This rule and one of teNorgan's four rules are not constructively valid. So that constructive proofs can be checked. all the automatic reasoning performed by the Proof Checker is constructive. For the same reason. the rule I P) `O'B wns omitted. It is not implausible that the O(n ) run time can be improved upon. A variation on the linear tree isomorphism algorithm found in Aho. flop- rroft and Ullnans's book (2) can be used to a compute normal form based on a aubset of the rules of TItANS in linear time. The Folding. Commute- tivity. Annihilation. Idempotent. and the Comparison Rules can all be han- dled. Because the algorithm processes a tree from the bottom up by lev- els. replacencot rules that alter the level of a subtree. such as the Associativity and Double `egation Rules. are a problem. If this problem cannot be solvtd, a hyb?id algoritI?m thot docs not have a bettcr worst- ca?c a,y?jtotic runuin? t iu? but ?n ptattlcc ib la.ttr. mey be possible. 225 --H 5.0 Xha Tr.?n We bave seen that if a set of axioms A1 in constructed by including en axio. of the fore P Q for every replacement rule P ? Q in mANS. then P =? Q if and only if ??PJ N?qJ. where v ?? defined in terns of TA1. Because the replacement rules of mANS were carefully constructed so that the replacement system would be confluent. the rules are rather messy to state. But there are no corresponding constraints on the axiom system. In this section. the set of axioms appearing in Figures 5.1 and 5.2. which viii be referred to as TA4. are shown to be equivalent to U1 in the sense thst the relation v defined by TA4 is the same as the relation defined by TA1. Theor.m 5.7. the transformation axiom acts A and A u B are equivalent if for every axiom P Q in 3. there is a derivation of Q fran P using axiom set A. liaaL. To prove two axioms sets equivalent. we suet show for any two formulas X?and v? if v can be derived from X using one axiom set. tbse it can be derived from X using the other set. and vice versa. Suppose it is possible to derive the formula v fran I using the axioms in A. Certainly the same derivation is possible using the axiana in A u B. Now suppose there is a derivation D of v from I using the axioms in A u Bt we wish to construct a derivation that uses just axioms from A. Bach step of n is of the form R[P0#x). g(P0flxl. where g is a formula in which x appears exactly once. and either either Po ?n or ?n P0 is an a?iom in B. This step will be replaced by a series of steps of the fare g(p0llxJ. R[P1llxJ. ... ?P?llx). cech of which uses an axiom fron A. Such a rtpleccewnt le possible beceist.. by hypothesis. tijere is a drrivstion 226 - r0 that only use. axioms in A. The derivation of Y from I using only axicos in A is obtaincj by performing the above replacement on every step in D. (I To obtain TA? from TA1. we will make a aeriee of additions and dale- tions to the aCt of axioma. all of which viii. by Theorem 5.1. result in equivalent aets of axioms. of the equivalent intermediate axiom eats in the atquence betwetn TA1 and TA4. only two (TA2 and T?) will merit naeas. The Connutativity Axioma are of the form: (ri p P2 ... Fn) (Q1 D Q2 where p is a comnutative operator. one aide is a permutation of the other. and the right side is eorted lexicographically. We can always derive a formula of the form (5 p T) from (T p 5). becauee one of those two formu- las will have sorted opcranda. Thcrefore. by Theorem 5.?. the set of axioms of the fora (5 p T) a (T p 5) called the Binary Commutativity Axioms. can be added. The liLary Con?utativity Axiome and the Aesociativity Axioms can be used to derive the Swapping Axioms. which are of the of the forms p F2 ... `i ? ?i+i P0) (p1p ?2o+???i+l ? ?i The derivation is as follows: (PI P P2 ... ?i ? ?i+i (Associativity) p .. (Pi P ?i+i? P0) (Binary Commutativity) (P1 p P2 .. (Pi+i P ?i? Pn) (Aseociativity) ? ?2 Pi+i P Pi . Pn) Therefore. by Theorem 5.7. we may add the Swapping Axioms. But the Swap- ping Axioms are sufficient to derive the Conmutativity Axioms. since they can be used to implement a bubble sort. Therefore all the Commutativity --H 22? --H Axioms could be deleted. We will delete all of then except the Dinary Commutativity Axiois. which along with the Associetivity Axioms are auff1- cient to derive the Swapping Axioms. Those axioms. having served their purpose. will now be deleted. The net effect has been to replace the Con mutativity Axioms with the Binary Comnutativity Axioms. In the same fashion we can reduce the other axioms to simple ache- mats. For example. the Identity Elimination Axioms. which are of the form: (P1 p o+.. `i pip ?i+l ... rn) (P1 P P .. Pn) whers e is the identity element. can be used to derive tbe linary Identity ilimination Axiom CF p E) = P. The derivation is: CF p i) (Identity Elimination) (p P) (Reduction) P But all of the Identity Elimination Axioms can be derived using the Binary Idantity Elimination. Binary Commutativity. and Associativity Axioms. Therefore. the Identity Elimination Rules can be deleted. The same kind of reductions can be applied to the Annihilation. Idempotent. Cancella- tion. and False Introduction Axioms. The Folding Axioms will be generalized. Clearly any valid statement of the form F Q. where F and Q are trees whose leaves are all constants can be derived using the Folding Axioms. All such statements will be added as axioms. From P we can certainly derive P - 0. It follows that from p 0 ve can derive P - 0 - 0. and from F < 0. we can derive F - 0 < 0. so that the axioms (F - 0) E (P - 0) - 0 and CF <0) = CF - 0) <0 can be added. The 22f effect of adding these axioms is to rnmove the restriction that Q cannot br 0 in the axioms (Fe Q) = - Q) 0 and (P < Q) m - 0 The axiom (P - =--H (?p Q) can be derived as follows. in sen- oral. F will be of the form (r1 + ?2 + ?n? letting n be 1 if the root of P is no +. Similarly. let Q be (Q1 + Q2 o+.. + Q1). The derivation will begins + + ?n? (Q1 + q2 o+. + q0) (Conparison) (P1 + P2 ... + Fn) - (q1 + o+.. + Q1) 0 (Subtraction Eiim.? + ?2 + ?n? ??l + ?2 + ?ts?? (Negation Diatrib.) + ?2 ??+ ?n? + ???l + + ?n?? :0 (AasocLativity) + + ?n + ???l + o+q2 ... + ?n?? (Associativity) + ?2 + ?n+ ?l + ?2 ?m? ? (5.1) fly applying a sequence of Cancellation. Double Negalion Elimination. Nega- tio? Distribution. and Associativity Axioms. we Can get a formulas (R1 + R2 ... + Rk) 0 (5.2) where each Ri is of the for. 5 or 5'. no 5 has - or + as its main con- I I i nectLve. nut every S? is a const?it. nud if Sj and Sj are the same. then the correaponding R? and R are the same. At lca.t on- of the folloving: ((T1 + T2+ Tk) -0)--H ((R1 + R2+ R??) -0) (5.3) ((RI + R2 + o+. Rk) 0) ((T1 + T2 + ... Tk) 0) (5.4) where Ti is ? if R? is a constant c. Sj if R1 is not a constant ?i? and if 0. is S.. will be an axiom. If every 5. is a conatant. then both (?.3) anJ (?.4) will be ?ol?ing Axioms. Otherwise. let S? be a smallest noncufls'sflt in 5k? If 5a is in (T1. TTkl then (5.3) ill b.. an Ej?aI it y M5atl?.ll A.I?'mI it' 5 ? (R1. a2. . 11k? Ih.n 229 (5.?) wiLl be am ?uality Ilegation Axiou. taint tbe appropriate aziom. we obtain: (T1 + T2 + Tn) 0 Now the derivation of (5.2) from (5.1) can be reversed to obtain: + -P2 ... + ?n + ?l + + ?n? and then be continued as follows: + + ?n? + I + + ?n? ((Pj + P2 ... + -P ) + ... + pn)?+ +?I??+i?? .)??n????o? - + ( + + (Negation Distrib.) + + pn n (Dc'jble Negation) + P2 ... + ?n? + (Q1 + ` + Qo)) - (Subtraction ilie.) + + ?n? - -(q1 + q2 ... + Q0)) - 0 (Conparison) -(r1 + r2 ... + ?n? - -??l + + Therefore. by Th?orem 5.?. we can add the axiom (P - Q) (?P - Q). But using this n?w axiom and the Folding. Negation pistribution and Double Negation. we can derive the Equality Negetion Axiom we now joyously delete that axiom. Lot TA2 be the set of axioms produced by all tie additions and dele- tions to TA1 made so far. The set TA2 can be generated by a set of ache--H mats that has no restrictions on how trees can be substituted for parame- ters (the Folding Axioms are generated by an infinite set of schemata that ue? 110 pai::'ctora). Sinco 110110 of the s?'I'crnata conta?n ?a?-iablen. if x ia a v,s. iat,La (iut a l.ara.?L?r). TA2 I?a. Lie ????ieLty: if r m Q is in TA2. then P(iLllx) = Q(itllx) is in TA2 (5.5) since a derivation of (?Rllx) from r(i:llsJ can b. obtained by substiLutins 230 II q) (r . I() (q + a) (5 < Q) (p o+ a) < (Q + a) (5 < Q) = <-- q-l) (5 < Q) : (? > 5) (5 <-- ?) (5 + a) <: (Q o+ (5 <. Q) m (5 < (5 <- Q) (Q ?-- 5) (5 > (r + a) (Q + a) > Q) (F >-- (5 q) (Q < (5 >a Q) (5 + a) >= (q + a) (5 >: (P > (5 >-- Q) (Q >-- Figure 5.? Extended axioms for comparison relations I for every occurrence of 1 in a derivation of Q from 5. We can nov easily show ?hat all the axioms in Fig?rn 5.9 can be derived. Lot 5 = Q be one of the axiom achemata in the figure. and let 5' be 5 with every parameter replaced by a variable with the same name. and q' be obtained from Q in a similar fashion. fly applying the normalization function to 5' and Q' (not in an abstract sense. but by actually performing the steps of the computation) we can see that N(tP'J ?ffq'?. Therefore there is a derivation of Q' from 5' using TA1. Since TA2 and TA1 are equivalent. there is a derivation of Q' from 5' using the axioms in TA21 Let 5" ? q5 be an axiom obtained from the scheme 5 a Q by aubatituting trees for parameters. if those same substitutions are made for variables ia the derivation of Q' from 5' using axioms in TA2 the result is. by property (5.3). a derivation of Q" from r in TA2. Therefore1 all the axioms pro- duced by the schemata in ligure 5.9 can be added to TA2. The right side of each of the axiomas - 231 - r-q 0 m r-q 2. If P is a formula in the extended languase. denote its translation into the strict language as M?tP?, Nt(P? can be tbought of as the "mean- 1ngfl of P. If P ja in the strict language. define ??PJ to be P. gow suppose we haive a derivation ?O ??n in which Po and Pm are in the strict language. and the other formulas are in the combined langu?ge. WIwt we must show is that for each I in (1 ... n) that ?LPiJ can be derivtd from X?Pi?1J using only intermediate atepa that are in the strict lauguage. If an application of an axiom to a formula in the extended langua?e transforms Pi?I to Pi leaving negative constants and extended sasociative operators intact. then the same axiom can be used to transform NLPi-I? to riP1i. Let TA3 be the current set of transformation axioms. TA3 consists of the axioms in Figures 5.1 and 54. plus the Identity Introdu?tion Azi?m: E ?here p is an associstive operator and E is its ldt'ntity elemtnt. the 233 --H eduction Axioms (p 5) ? 5 the Negation Distribution Axio5s + ?2 + 5n? --H= ???l ? + and the Associative Axiom: (Pj ? 5jP (Q1 P Q2 ... Qm? P ?i+l --H? ??i ? Pj P Q1 P Q2 ... ? 5i+l ... Yber?p is an associative operator. By inspecting all the a:ioms in TA3. we find that the only ones that do not leave estended associativa oneratoro and negative constants intact are the Folding Axioms and the ones listed above. There are Folding Axioms. such as 1 2 - ?. that do not lesve nega- tive constants intact. But if 5: Q is a Folding Axiom. flILPJ : ?Q? is as well. In the above example. the corresponding step in the strict language could use the Folding Axiom 3 : 2 - If a step uses an Identity Introduction or Re?uction Axiom of tbe form 5 Q. an extended associative operator ?ill be modified. In this case. ML5J i. the same as N(EQ?. and no corr?sponding step is necessary im the strict language. The application of the Negation Distribution Axiom can modify an extended associstive operator. Translating this step into the strict language. there are three cases. If n > 2. we must be able to derive: + ?2? + 53)...) + 5n? from: 234 - + a ?)..?) + rn). This derivation can be performed by n-l applications of the axiom (p a : (-p + -Q). If n is I or 0. we must be able to derive P1 from or 0 from 0. each of which Is trivial. Finally. consider what happens when the Associativity Axiom Is applied. Suppose we have a formula P of the form (P1 p P2 p where. for some i in (I nj. ?i is of the for. (Q1 p Q2 p ... Q1). Applying an Associativity Axiom flattens the tree. Let a be the flattenad tree. We must show that Mi(RJ can be derived from ?PJ using intermediate steps that are all in the strict language. The cases in which ? : I or o+ c 2 are all trivial: we will assume that n ? 2 and m ? 2. Consider binery trees whose nooleaf nodes are all p. and whose leaves are formulas. Define inductively what it means for these binary trees to be in o+left normal form" as folluws. All leaves are in left normal form. A tree of the form (L p x) is in left normal form if and only if L is in left normal form and x is a leaf. The notion of left normal form can be used to state more precisely vhat the translations of P and R are. One way of viewing NItP? is as a binary tree in left normal form whoae leaves are. in travereal order. -??l? MtP2J. ??n? N?Pi? can. in turn be viewed as a binsry tree in left normal form whose leaves are. in traversal order. r.?Q1J. N?q2J. ???m? But if HtPiJ is not viewed as a leaf of MLPJ? then xLPJ can be viewed as a binary tree whose leaves are. in traversal order: NFP1J. M?P2J. ... ???i-i? H((Q1J. MI(Q2?. ... NFQ?J. H?Pi+lJ? ... NLP?J but which is not. in general in left normal form. MLal can be viewed as a binary tr?e that has the Same leaves. b..t is At. left n?r.al for.. WI'cn the Binary Associativity Axiom ((P p ?) p It) E (? p (Q pa)) La applied to a tree. its leaves and their order are unchanged. Thus. to prove that M?flJ can be derived from NffP? using the Binery Associativity axiom. it La suffLcient to prove tbe following theorem. ItLeaun 5.8. Any tree can be tranaforned to one in left normal form by repeated applications of the Binary Associativity Axiom. P?nnF The proof ia by induction on the sixe of the tree. The base case is when the tree is a leaf. Since all leaves are in left normal for.. no translation is necessary. If the tree is not a leaf it will be of the form (sp t). If T is a leef. 6 can. by induction. be transformed to a tree U that is in left nor- mal form. The tree (u p T) vill then be in left normal for.. If T is not a leaf Lt can. by induction. be transformed. into left normal form. yield- ing a tree of the form (6 p (v p x)). where x is a leaf. Apply the Binary Associativity axiom to get ((6 p v) v x). (6 v v) can. by induction. be tranaforned to a tree W that is in left normal form. Then the tree (W v x) will be in left normal for.. El We have shown that any derivation that begins and ends in the strict language can be performed using only intermediate steps that are in the strict language. The extended language is only an implementation detail: it is not essential to the logic. Therefore. any sxioa in TA3 that has as one of its a?des a formula in the extended language can be deleted. The result. TA4. is the list of transformation axioms in ?igures 5.1 and 5.2. Q'.APtER 6 A DECISION rROCEDuRE FOR THE THEORY OF sQuALlTv ?.l Inrodictign As we saw in section A it is necessary for the V-code Interpreter to perforn the substitution of equals for equals to pronerly implement tb? auto?atic assignment rule. For example? the V-code generated for the fol- loving PL/cV proof fragment: + C) + l)*2 ? 2 BY A :-- n + B :-- A o+ 1; C :-- B * 2: C ? 2: 15 PROCLAIM ((D ? o+ l)?2 2 A PPOCLAL' A - D + C ??OCLAIN B - A + I NE'A C .PRO?LAIN C - B a 2; RcQJIRE C > 2 r?ccLAlN C ? 2 The V-code interpreter deduces C 2 from the PROCLAIMed for?ulas unins n decision procedure for the theory of equality with uninterpreted function symbols. the aubstitutiona that must be perfortasd to check assignment state- nenta are just 5 special of case the more general equality rules. The traditional axiom ?nd rules of inference fur equality are shovn in Figure 6.1. ?owever. the Symmetry and Transiti?ity Rules are redundant; they can be derived fr?m the I(:f lesrYity Axiom and Substitution ?ule. To deriv tb Sy??et.y HuI? suijose we I?uvc, 5 t. To Met t 5. substitute t fur --H 237 - ?ef 1exivi?y set Symmetry tea set :eu Tranaitivity Ieu o+ e ? P(allx) Substitution P( tllx) yiure 6.1 The axioms and rules of inference for equality the first a in the axiom a a. To derive the Transitivity rule. suppose ?e have 5 e f and ? : u To get 5 u. substitute u for t in a Therefore to decide the theory of equality it ie only necessary to recognixe all consequences of the lef lexivity Axiom and the Substitution Mule. Algoritha Eq. vhich recognizes all consequences of the Substitution Rule and the Meflexivity Axiom. is presented and proved correct in this chapter. And as we will see in Chapter 7. Algorithm Zq is not only used in the V-code interpreter to implemcnt the automatic equality rules. it forms the foundation on which the algorithm used by the V-code Interpreter to perform propositional reasoning is built. The next section contains a formal specification for Algoritha Eq. 6.2 ? ?1 D?finirion ? itzc P?ohie Suppose we are given an alphabet A of function symbols. The syntac- tic object "expression" can ho inductively defined as follows. If f is an absent of A. and x1. a5k sre ??rn or more caprPssjons. then - 21il - 5k? ie slsu an expnesius'. The unly es?r?asiona are ubjecLa that can be obtained by repeated suplicatlons of the preceding rule. Time Cde?reelI of an expression is defintd to be time number of function syibols it contains. The exact nature of the object "expresaion?? baa been deliberately left a bit vague. An expression could be a string of function sysbola. coonas. and p?renthesea. but representations that can more easily be mani- pulated by computer programs are possible. Suppose there is also a set. EQS. of unordered pairs of expressions tbat bave been declared to be "equal." Adding the pair (aj. `2? to EQS is an indication that in any context where o+i appears. `2 would do equally veIl. Two expressions are defined to be ?equivalent? whenever one can be tranaforsed to the other by a sequence of substitutions of expressions for tbeir equals. fl??,?Imn 6.1. Let xj and be any two expressions. Define 11 ?S 12 to mean there exist expressions Sj and `2 such that ??l? `i? is in EQS, and substituting `2 for a single occurrence of in 11 yields x2. Then define to be ?5 the reflexive tranaitive closure of Since is a synmnetric relat?on. =? is an equivalence relation. The input to Algorithm Eq 5a a series of instructions of the form .`Assert(x.y)5 and 5query(x.y)." The operation of algorithm Eq on these instructions is described in terms of the set EQS. (Eqs is not actually used in the coma- putatlona; it is merely used for specification.) Initially. ?S is empty. When an Assert(x.y) instruction is encountered. the pair (x.yl is added to EQS. Wten a Query(x.y) instruction is encountered. a boolean value is out- put indicating whether a =? y. where is the relation defined by the current value of zQS. rigure 6.2 A graph created by Eqinsert The problem of computing Es from EQS is equivalent to the uniform word problem for finite?y presented algebra.. Several algorithas for solving this problem have appeared in the literature. Melson and Oppen 62) and Downey. Sethi and Tarjan 30) give slgorithms that run in 0(11 log 11) time. liowever. these algorithus are offline. which means toat all the Assert instructions must come before all the Query inatr?ctions. Samet (68) gives an online solution to the problem. but he does nut give a complete run time analysis. He simply states that the worst case run time (his slgorithm uses bashing) for a single Assort instruction is qu?dratic. Algorithm Eq processes a list of instructions in an expected time (it also uses bashing) of 0(11 log 11). where 11 is the total size of all the expres- sions in the input. 6.3 ? Overview ? Aigorithm ? In Algorithm Eq. a linked data structure is used to represent expressions. ?he routine ?qInsert(e) is used to obtain the linked reprsaenta?ion of the expression a. If a is of the form f(xl. x2 ... xk) Eqinsert first calls itself recursively to obtain a node ni representing each x? The node representing 5 will contain the label f and pointers called operand links to the nodes n1, n2. ... n? A haahed search is used to detsriine if the data structure already contains such a 2?O - Gb ? a d Figure 6.3 A 8rapb with eprliok? node; If not. ? oe? one is created. After a few calls to Eqinsert have been wade. the data atructuro will take the for. cf a directed acyclic graph. in which each node represents an expression. For example. if Eqinsert is callad on the expressione s(c().d(g().h())). b(d(g().h()).f()) sod e(h().i()). the result will be the graph in F??ure 6.2. When tvo expressions t1 and e2 are asserted to be equal. thia fact is recorded in the graph by connecting the the node representing ?i to the node representing e2 with a pointer called a reprlink. After a number of expressions have been a?scrted to be equol. the nodes will be partitioned into equiv?leoce classes. Mcllroy and Morris's UNION-FIND algorith. (3) is used to kccp track of the equivalence classes. All the nodes of a given equivaleoct class art cunnecttd by reprlinks to form a tree. One nude in each equivalence class. the root of the tree. is singled out as the ???pr?sentative? of the class. Oper I I inks are al owed to point only to representative nodes Twe equivalence classes are merged by connecting their representatives n1 and n2 witb a reprlio't. One of the nodes. say n1. is chosen as the representa- tive of the new equivalence class. All of the operand links pointing to "2 must be located and changed to point to 01. Once reprlinks have been put into the data structure. a node cnn reprrse,?t a cla 5 ul eqoivaten55ions. Fur esample. tI?a node with - 241 ligure 6.4 A graph with a cycle label a in the graph in Figure 6.3 (reprijoks are shown as dashed lines in figures) represents the following set of formulas: (e(b().d()). a(b().e()). a(c().d()). a(c().e())l. Once reprlinka are introduced. the graph is no longer constrained to be acyclic. Nodes in graphs with cycles can represent an infinite set of expressions. For example. the graph in Figure 6.4 is the result of asserting x and f(x) to be equal. The node with label x represents the infinite set (x(). f(x()). f(f(x())). f(f(f(x()))). ...). A Query(x.y) instruction is processed by testing?hsther the two expressions x and y are represented by the same node. For this strategy to work. it is crucial that enough reprlinks are added so that all nodes representing the same expression are in the sane equivalence class. Suppose we are given the graph in Figure 6.5a. As the result cf?the instruction Assert(d(). e()). the nodes representing d() and e() are "merged" by adding the reurlink and moving the opcrnnd links as shown in Figure 6.5b. But now the two nodes that have b as a label. both represen- tative nodes. have identical operand links. Only one of these nodes can be us?d as the representative of. for example. b(d().e()). Arbitrarily. the node on tlie rigia is choscn as the rcpr'suntntivc. and the two n?des are nergod. as shown in Fi?re 6.5c. But n?w nodt'a th?t ha?e the label a are ejuivuleut and must be mer?ed. as sht,wn in Fl?ur? 6.?d. 242 - (a) Od a Gd Fiure 6.? Nergiog equiva)en? nodes f?eId labt?l opcrands containers reprlink reprcount noxt previous eligibie a funcLIon nymI??.i a li,t of puintcra to nodes a list of pointcrs to operand fields a pointer to a node. or ALL a nonnegative integer a pointer to a noJ?. or nil a pointer to a node. or ALL a bit Table 6.6 The fields of a node The problem is to find all the nodes that need to be merged. lelsoc and Oppen (62) use an Iterstive technique in their offline algorithe. First they add all the reprlinks for all the Assert instructions. and then they step through the all the nodes of the graph serially. merging a?l the equivalent nodes they find. The algorith. does not halt until it has made an entire pass through all the nodes without finding any nodes that can be merged. Each pass through the list of the nodes takes 0(N) tinne. end they prove that they can make st most log N passes. giving a run time of o(M log N). An efficient onlins algorithm cannot afford the luxury of asking a pass through the entire list of nodes each time a raprlink is added. Algorithm Eq maintains another set of links. called container links, that are used to locate the nodes that need to be updated when a reprlink La added. 6.4 ? flerala aL Algorithi En consists of the routines shown in Figures 6.7-10 and a global data structure. or "graph." as it will be callad. The graph has three parts. the first of which is a collection of "nodes.' The fields of the nods are listed in Table 6.6. The operands and containers fields are - 2A?? (01) (02) (03) (06) (07) (03) (09) (10) (Il) (12) (01) (02) (03) (04) (06) (07) (OS) (09) (10) Process ? list of instructions ? h.ein vh'I, there are instructions left fla Read an instruction i li i is of the form Assert('. 7) ?h?n EqAasert(x. y) lif i is of the form Qucry(x. 7) Lhei? Output qquery(x. y) li LnA .011 vigure 6.? Algorithm Eq Eqquery(xi. yy): ? Deteruine if expression, xx and 77 are aqual ? awL nx :-- Eqlnaert(xx) fly Eqli'sert(yy) li nx ny thn? EqQuery :-- liiLa pl?n Eqlutry li Figure 6.8 Routine EqQuer ?eads of sin?l7-linxed lists of nodes. iiou?er. tbere is no reason to present the details of list manipulation here. For the purposes of ibis discussion. we will assume that nodes are flexible. and the operand anI container fields contain variable-si?cd lists. ?,`ot? th?t ?arh Ioint?r on th? contnin?r list points to a spcciflc o??rsnJ f ?cld of a node. Some nism wnust also bL providod for obtain- ing from a container link to an operand field a pointer to the node con- taining the ??erand field. One ainpl? method Is to Implement the con- (01) (02) (03) (04) (05) (06) (07) (08) (09) (10) (11) ?l2) (I)) (14) (15) (16) (17) (18) (19) -(20) (21) (22) (23) Zqineert(e)a ( Add expression e to the graph ? e viii be of the form f(x1. x for a function symbol f and some k ? 0 a for each Xj ? a(i) a- EqInsert(??) ad a h :--H--H haah(f. (a(1). a(2]. ... a(kJ)) a Search bucketh) for a node with operator f and operanda a[1). aC2]. ... a(ki a il the search succeeds in findin a node then while n.reprlink ? nil ? n :-- n.reprlink j??? e1aP a a- a pointer to a newly allocated node a Put a in bucket(hl a n.label a-- f a n.operands a-- (a(I). a(2). ... a Add a pointer to the i?th opetand field of to the container list of a(il. for each i in (1 ... laJ n.containera a-- thia empty liat n.reprlink a-- nil a.reprcount a I AlA Ii Eqinsert a- n Figure 6.9 Boutine Eqilfeert tamer link as a pointer to a node and an offset. The term ?1node? will be used to refer to an area of storage, end not its contents. For example. if a1 and a2 are nodes. a1 V n2 means that a1 and a2 occupy different locations in memory. but doea not exclude the poe--H sibility that corresponding fields of a1 and n2 have identical contents. Initially. there are no nodes. As the algorithm executes. neg nodes can be allocated. but nodes are never deallocated. The second part of the graph is Io+bucket." an array of pointers to nudes. Each element of bucket is the head of a list of nodea that is dou- - 246 - (01) EqAaaert(ax. yy): (02) d assert the equality of e?preasions xx and yy a (03) b??? (04) na :- F.qIn?ert(xx) I ny I5 Rqlnaert(yy) [(0o?5)? Add??(?5xx?Yy)y?0toT0?q0s ? (07) s EqLoop: (08) ?h1p ToDo is not empty 09) ? Remove an element (x. y) from ToDo (10) ailtti' x.reprlink iE il? x :- x.rsprlink ? (11) xhiu y.reprlink # ?jj ? y ?: y.reprlink ? (13) LILUL iL y.rej.rcount > x.reprcount (14) ?h?n s?ap x and y li (15) y.reprlink x (16) I x.reprcount I x.reprcount 4 y.reprcount (I;) I ConLoop: (18) iLLL every w on y.containers (19) 1lg u.operand : x (20) z :-- a pointer to the node containing w.operamd (21) li z is eligible (22) ?he? Remove z from the bucket it is in (23) h :-- hash(z.label. z.opersnds) (24) ; Search bucket(h) for a node with (25) the same label and operanda as a (26) I li the search finds a duplicate d (27) thpn Add (d. z) to ToDo (28) is Put a in bucket(h) (29) li (30) Li (31) 32) I Append y.containers to 1.contsiners (33) li (34) aA (35) n'L Figure 6.10 loutine EqAssert 247 - bly linked through the next and previous fields 0 each node. If a mode La In one of the bucketa. the node will be said to be 1eligible"; otherwise it is said to be "ineligible.1 A bit in each node is uacd to keep track of whether the node is eligible the bit is set when a node La put in a bucket. and cleared when it is removed. The function 1hash" takea as input a label and a list 0 the addreaaes of zero or aore nodes. and produces the index of one of the buckets. Initially. there are no nodes. so that all the buckets are empty. The third part of the graph is "Toflo.5 which is a set of pairs of pointers to nodes. The notation "(n1. n2) is in Toflo.' will be defined to mean that either (n1. n2) or (n2. n1) is in ToDo. Initially. ToDo is empty. The set EQS. which contains the pairs of expressions that have bean asserted to be equal. will also be considered to be part of the graph. The stet is not used anyuhere in the computation. but it is used in invariant assertions about the graph. The comment on line 6 of IqAssert indicates exactly when. for the purposes of invariant assertions about EQS. a new pair is added to ?S. 6.5 an Ove?v.p nL aha Cnrrpcrnppa Prpnfr The method used to prove the correctnesa of Algorithm ?q was inspired by the methods of Owicki and Cries E63) for proving parallel pro--H grams. Three areas of the algorith.. lines 12--H20 of gqimsert. lines 5-6 of IqAssart. and lines 9-32 of zqAssert are designated as Critical legions I. II. and III respectively. All modifications to the graph are performed vithin critical regions. A nunber of invariant assertions (ninvariantafi for short) about the graph are proved to hold whenever the program is not in e criticaL region. There are two ways of establishing an invariant. The first way is to show that it is a consequence of other invariants. The second way is a two-step procedure. First. the invariant must be shown to hold when the algorithm begins. that is. when EQS and ToDo are e?pty. and there are no nodes in the graph. For all the invariants in this proof this step is trivial. and will he omitted. The second step is to show the irv?riant holds?at the end of each critical region. In this step. we are allowed to assume that every invariant. including the one being established. holds at the beginning of the critical region. (Therefore if none of the structures on which an invariant depends are changed by a critical legion. the proof that the invariant holds at the end of that region is trivial.) Essentially. the theorem 5every invariant holds at the end of every critical region" is being proved by induction on the number of critical regions executed. Since the graph can only be modified within critical regions. once an invariant has been proved to hold as control leaves a critical region. it must remain valid until another critical region is entered. To formulate the invariants. some equivalence relations and a func- tion will be defined. The relation defined on nodes. is the equivalence relation deter lined by the reprlinks. A second relation. :N is defined on nodes. Its definition is quite technical. depending on the reprlinks. operand links. labels of nodes. and on the ToDo list. The relation is always refine- ment of and the two relations are the same whenev?r r.qquery is called. EqAssert(x. y) operates by first addng the pnir of nodes that represent x 2&9 nod ? to Tolo. This addition updates ??. but not ?. Tbe bodv of ConLoo? Rdda reprlink? to the graphi it is repeated until and are once again the sais relation. In section 6.3. the notion of a node representing an expression was introduced. To be more precise. an expression is represented by an equivalence class of nodes. The function recl(e) is defined to ap the expression e to an equivalence class of that represents e. (The name `red" is an abbreviation for o+representative class.") For any e. recl(e) is always a finite set of nodes. even for cyclic graphs. If C is an equivalence class of the set of expressions (a I recl(e) cl can be infinite. but this does not cause any problems. The definition of recl mirrors the computation performed by Eq1n- sert. When the routine Eqquery(x. y) calls Eqinsert on z and y and Co,--H pares the results? it is testing whether recl(x) racl(y). The relatiom which is defined over expressions. is intended to o+irror the computa- tion performed by EqQuery. For expressions x and y. z :1 y is defined to mean recl(x) recl(y). The key to proving the correctness of Algorithm Eq lies in estab- lishing the invariant that EE and ?re (almost) the 55me. We will sea that Critical Regions I and III leave Es (essentially) unchanged. Critical Region II updates both EQS and ToDo. changing both EK and We will as's. however. that it makes the same change to both relations. 6.6 So?p si--Hn?. 1n???i'.?ra AwL sa ftx Th?n?? There are two levels of understanding of a complex algoritha. First. one understands whn? the algorithm is ?oing, and thcn he can under- stand it works. The invariants and theorem presented in this section - 2?0 se u tie wI'.t" varietys tI?y ?eeswt o+urc fureisily suIa uf LI? ideas intruduced in section 6.3. Sincc only ToDo and EQS are changed in Critical Region IX. and none of the invariants in this section depend on ToDo or EQS. Critical `Legion II can be ignored. `?`????r 6.2. The directed graph whose vertices era nodes and whose edges arc reptijoks is a forest in which the reprlinks of offspring point to their parents and the roots have flil reprlinks. ?. When a node is crested in Critical Region 1 its reprlink is set to LiL. creating a new tree of size I in the forest. In Critical Segion III. lines 10 ard 11 guarantee that I and 7 are roots of trees in the fcrest. In line 15. the tree whose root is y is made a subtree of the tree wi?se root is a. U Invariant 6.2 guarantees the termination of tbe loops on line II of sninsert and lineL 10 and 11 of EqAssert. T?v?'??r 6.3. If n is the root of a aubtree t. n.reprcount is the number of ncdea in t. If a is an offspring of n. n.reprcount is at least double o+.reprcount. ?. When a new tree of size I is created in Critical Region I, its reprcount field is set to I at line 20. When the tree y is added to the tree z in Critical legion III. x.reprcount is suitably updated at line 16. Becauie x.reprcount was at least double the reprcount fields of each of its sons upon entry to the region. and x.reprcount is being increased. z.re?rcount is still at least double the reprcount fields of each of its old sons. Because lines 13-14 guarantee that z.reprcount ? y.reprcount. after line 16 is executed z.reprcount will be at least double y.reprcount. 0 invemiammt e.? ii mmut mm--H,mlnmi Lo omove Lime em'mtem'tmmess mt ALsoriLhl Lj. It Is used in sneLiom? 6.i? Lo derive Limo o(n log II) rommmmimm? Liso. Tnvarm?nt 6.4. Each eligible node with label f end onerends njm n2. ... n? is in bucket(h3. where h hash(f. (nj. n linfiL. When a node is created in Critical Region I. it is placed In time pm?por bucket at line i?. The lebel tield of a mmode is mm?ver chmm'?ed, end the operand field of a node. or the bucket in which it resides, is changed only in Critical Region III. When an operend field of an eligible node is changed at line 19. the node is remeoved fron the bucket it is in. and if it is put back into a bucket. the bucket is selected at line 23 on the basis of its updated operand fields. U Tn?nriant 6.5. There are not two eligible nodes with identical operand ammd and label fields. P?nnf Before a node with a label f and operands `i' ?2' 5k is crested in Critical Region I. bucket(haaim(f. (a1. a5k??? is searched for a node with those fields. By Invariant 6.4. if such a node eiists. it will be in that bucket. When the operand field of a node : is changed in line 19 of Critical Region III. it is nade ineligible. If another node d exists with label end operand fields identical to those of z. node z is left ineligible. D npf.'n?minn 6.6. A node n is said to be a representative whenever n.reprlink is ILL. 1nvari?nr 6.7. There is a one-to-one corr?pmnience between operand links of representative nodes and container links. If an operand link of a representative node n points to node am. there is a corresponding container link in node am that points back to the operand field. P?nF. When a node is created in Critical Region I. for every 2?2 op?rand link created. a corresponding containe link La crested a. veil at lines 16-17. Since at the time of the creation of the node no operand link can possibly point to it. its container list is node empty at line 18. Whenever an operand link of a representative node is changed in Crit--H ical Region lii. the corresponding cont$iner link ia changed as veil. ConLoop searches all the nodes on the container list of y for the corresponding operand links pointing to y. and changes then to point to I Then. at line 22. the cont?iner list of y is appended to the container list of x to preserve Invoriont 6.7. The container list of y is no longer relevant. because y is no lon??er a representative. 0 1nv?lini?L 6.8. ?very optrond link points to a representative node. ?. First observe thot Eqinsert slwoy? returns a representative node. either by finding one wiLh the loop at line II. or by creating one at line 19. ?htn a node is created in Critical Megion I. its operands are set to nodes that are returned by a recursive call to Eqinsert. flenca. those nodes flust be representative nodes. Wh?n the node y is chongcd from a representative to a nonrepresenta--H tive at line l? of Critical Region Ill. nodes with onerand links pointing to y no longer point to representotives. Contoop searches the container list of y. which by Invariant 6.7 allows it to find all the operand links poining to y. and to move thee to point to x. reestablishing Invoriant 6.8. 0 t?'.?? 6.9. Outside 0! routine E?Assert ToDo is es?ty. ?. lnltio)ly TuDo Is emity. fle only place ToDo is `nodiflod is in EqAe?ert. which odds a pair to ToDo and executes the budy of E?Loop `ant ii it is empty again. 0 ?s3 6.7 Ania `.--H--H.s 1hp.? s?isrl??. In the following sections. it `rill be necesury several times to prove that one relation is the some as another relatios. These taske vill be made easier by the following lemma. Lem?s 6.10. Let be a relation defined over a domain D. and be ?*. Let p be any relation defined over D that is both reflezive and tran--H sitive. To establish tbat: or all I and y in D. x o+= 7 implies I p y (6.1) it ia sufficient to show: for all I and y in D. x y implies I p y. (6.2) Pr?F Suppose (6.2) holds. Then let ? and y be any elements of D Guch that I m y. If I 7 then. since p is by hypothesis reflezive. : p 7. If I # 7 than. since = is defined to be ?a. there is a sequence of one or more elements vi. v2. vk froi 0 such that I v1 Y2 . vk But by (6.2). z v1 ? `r2 . vk y. Since ? is by hypothesis transitive. I p y. As an example. Lemmo 6.10 is used to prove a simple lemna on sub- stitution. Laisa 6.11. ?o? any expressions C?. ?2 d. and I. if ?i m5 ?2 then dEa1llxi =? d(e2llzJ. flwL. By Lemma 6.10. it suffices to show that ?i ?S ?2 isplies d(a1llx) 6 de2llz). By definition ?i ?S ?2 means there is a pair of expressions ??l ?2? in ?qs such that substituting 5j for a single occ'irr('?nc4 of ?2 In Cj yields e2 If this anne substitution is applied to ench copy of cl in dCe?flx). the r?sult viii ic d(c?ll1J. Therefore ve have d(n1llsJ ? dEn2//a). El 234 - The following lemma is used in conjuction with induction on the relation tp?? 6.12. For expressions e1 and if e1 ?? e2. then either (ej. e2) is in r.qs. or for so. IL ? 0. e1 is of tho for. f(x1. xxk)e a2 is of the for. f(y1. y2. ...y?) and for each i in (1 ... IL). Xj =? yj. li?????. The substitution that transforms e1 to e2 either operates on all of e1 or .o.ewhtre in one of ita nperanda. If it operates on all of then (e1. e21 must be in rQS. If it operates on one of its operands. the rest of is unchan?ed. Tl?refore e1 and e2 must begin with the same function symbol and have the asee numLer k of operanda. One operand 1. of a1 ca be traiaformed to the corresponding operand Yj of a2 by a single substitution. That ia. Xj s y3-. The other operanda must be identical. Therefore. for all i in (1 ... IL). x? =s ?? 6.8 n?r.?i?.n?. In this section. definitions and proofs are given that formalize the concepts introduced in section 6.3. The relation --H n2 is defined to mean that n1 and n2 are in the :1 sa?e U%;1ON-FL':? tree. ff.-ir.pn 6.13. For any nodes n1 and n2 define n1 ?? n2 to mean n1.reprlinA' n2 or n2.reprlink n1. Then define ma to be ?Rt Informally. n1 =M n2 means that either n1 :1 n2. or that nodes n1 and n2 muat eventually be merged. When EqAasert detects that n1 and n2 must be merged. it puts the pair on the ToDo list. Any other nodes that have identical labels and equivalent operanda will need to be merged as well. Therefore a definition should be chosen for such that any of the --H 255 - following conditions: (6.3) (a. n) is in Toflo (6.4) o+.lebel n.lsbcl. o+ han operands ?l? P2? ?k5 ? h?s operanda q1. q2. o+. qks (6.5) and for each i in (I ... ki. ?i ? q1 inpiy a n. Conditions (6.3). (6.4). and (6.3) can be used as the baste for inductive definition for Efl. However. because the graph can be cyclic. the induction cannot be on the structure of the graph. n?f.?.r?0? 6.14. Define over the let of nodea a sequence of equivalence reletiona h:N. for nonnegative integera h. The relation ?:: is defined to be the identity relation. For h > 0. define ? h?N n to asan that (6.3) or (6.4) holds. or that o+.label = n.label. a has operands PI. P?k n has operands q1. q??. and for each i in (1 ... ni j.--H=N ??. for soae ij < h. Then define ??N ?? h?N5 Finally. define o+ = n to aean there is soas h ? 0 such that a --H n. --HN h--HN ZlLcaua 6.15. For any nodes a and n. if conditions (6.3). (6.4). or (6.5) hold. then a linaL. If 1 ER nor (a. nJ in ToDo. then o+ I? n. and therefore o+ aN a If a and n are eligible nodes with identical labels. and operende P1 P?k and q1. q2. ... such that ?i EN ??. then there are j1. j2. ... ik such that ?i 1?? q?. Letting h be the aaxiaua of ?I? i2' ?k (zero. if k = 0). we have that a ?l?N n1 so that o+ ?l-? n. and a n. 0 The converse of Theorsa 6.13 is also true. but will not be needed. n?f?n4r.? 6.16. Let a be an expression of the fora f(x1. `?). for k ? 0. The function red(s) is defined inductively 256 on the degre? of e to nap e onto a set of nodes as follows. A node a ia defined to be in recl(e) whenever there is an eligible node a such ?hat m n. and m has the label f and operands p1. p2. ?k such that for each i c(l ... k). ?i e recl(x?). An expression cia said to be 5in the graph" wh.e?ever recl(e) is eonen?pty. T?ep?e 6.17. For any expression e. the set red(s) ia either cepty. or an equivalence class of the relation Proo?. If red(s) is empty. we are done. Suppose red(s) is none?pty. Th?n let n1 be a node in recl(e). and n, be a node such that n1 = Th eligible nod ti (see Definition 6.16) that guarantees --HN a1 5 recl(e) works equally well for a2, Therefore a2 5 red(s). The preccding argunent generalizes to show that if a1 5 red(s). the equivalence class of that contains n1 is a subset of red(s). Therefore re?l(e) must consist of the union of equivalence classes of The fol- lowing lemma denonstrates that red(s) contains at most one equivalence class. 0 le??a 6.18. For any nodes n1 and a2. if n1 and a2 are in red(s) then n1 ? n2 The proof is by induction on the degree of a. Let e be of the form f(x1. ?`k? for some IL ? 0. Let n1 and n2 be nodes in red(s). Then there must be eligible nodes m1 and `2 each with label f. such that =? n1 and m2 ? n2. and if p1. p2. Pk are the operands of m1 and q1. q?? are the operands of m2. both ?i and q1 are in red(s1) for all i in (I ... k). By induction. P1 ? q1. Then. by Theorem 6.15. `1 =N `2' gi?ing us a1 --H=N `1 --H=N m2 --H=N ?2 0 flef.a.?.nn 6.19. The domain of the equivalence relation is the set of expressions in the graph. that is. (e I recl(e) 6 ?J. For two aipressions o+i and e2 that nre In the graph. defias a1 =g e2 to mean racl(e1) reel(s2) 6.9 Invsrt.nrs Invariant 6.20 is the key to the proof of correctneaa of Algorithm ?q. It says that =--Hg the relatIon computed by ?qQuery. is essentially the same as =s. the relation determined by EQS. Tn?.ripnt 6.20. If expressions ai and e2 are in the graph. then ?l ?E ?2 if and only if a1 =s ?2 To establish Invariant 6.20. two less spectacular invarianta will be needed as well. inwiaL 6.21. For every node a there is an expression a such that a a recl(e). lwtArianL 6.22. 1 (e1. e2J is In EQS. then both ?l and e2 are In the graph. In the next fev sections. Invariants 6.20. 6.21. and 6.22 are proved to bold at the end of each critical region. Whe'n discussing the effect a critical region has on a graph. "graph a" will refer to the state of the graph after the critical region has been left. and "graph b" will refer to the state of the graph before the region has been entered. (A moemonic is "h? means "before" and ?s? means aafter.?) The function and relations that have been defined in terms of the graph will have the auperscripta "h" and "a" placed on them to distinguish which graph is meant. 6.10 itiIi1'??1 Critical Region I does not change the set tQS. and therefore does not change the relation :g. liowever. Critical Region I does add a node to the - 258 - grIp).. wI.jch adds more eapresslons tu the graph and estonds the domain 0 To prove Invariant 6.20. we must show that is extended to be con sistent with T??=?.jn? 6.23. 1 ToDo is empty. then and are the same rela- tion. P??o'. This invariant is proved by showing that it is a consequence of 1nvariants?6.2. 6.5. and 6.8. Let a and n be any two nodes. If o+ n. then. by Theorem 6.13. a --HIo+ ? Thus. it is only necessary to show that a n implies a We shall see. by induction on h. that m n implies a = h--H=N --Ha If b = 0. then a n, and clearly a n. For the induction step. eseune h > 0. By Lenma 6.10. it L's sufficient to show that a h??I n implies a n. Definition 6.l? admits three poasibilites. The first is that a =? n. which is what we need to prove. The second possibility. that (a. ni is in ToDo. is ruled out. since ToDo is assumed to be empty. The final possibility is that a and n are eligible nodes with identical labels and equivalent operanda. That is. if PI. P?k are the operands of a. and q1. q?? are the operands of q. then p? jj=N ?? for some < b. Then by induction. each ?i Z--Hg q? Since they are pointed to by operand links of a and n. nodes Pj and must both be representative nodes. by Invariant 6.8. Since ?i and =re both roots in the same tree (see Invariant 6.2). they must be the same node. Since a and n are both eligible. and have identical labels and operand links. by Invariant 6.5. a n. and hence ? n. 0 T?,ari=?r 6.24. If ToDo is empty. for any expression e. red(s) is either empty or contains e?actly one representative node (and possibly some nonrepresentative nodes). By Theorem 6.17. recl(e) is aithcr empty. or an equivalence class ef Since ToDo Is easuned e.pty. by Invariant 6.23. recl(e) La either empty or an equivalence class of ?. But by Invariant 6.2. an equivalence clans of =1 contains exactly one representative node. 0 Since is defined in terms of recl. the effect Critical legion I has on --H is determined by the effect it has on reci. For the rest of this section. "b" will refer to the graph before Critical Region I. and "a" viii refer to the graph aftervards. -Also. ni vill refer the node created at line 12 of Critical Region I. b 1r?i 6.2?. For every expression e. any node m that is in reci (a) is also in recl?(s). lismL. If 1 E reclb(e). it is because there are a collection of nodes with fields having values specified by Definition 6.16. Since the only difference between graphs b and a is the addition of the node n1. the b same nodes that guarantee m ? recl (a) also guarantee m recl5(e). 0 Lajeut6.26. For any expressions end node a such that a # n1 and m?e red5(s). a c reclb(e). liswL. The proof Is by Induction on the degree of e. The expressiom a will be be of the form f(x1. ?x?). Let m be a node other than n1 in red5(s). By Definition 6.16. there will be in graph a an eligible node p vith label f. and operands q1. q?? such that each q? 4 recl5(z?). end ? =--H: I. Since. by Theorem 6.?. T6Do is empty whenever EqAsacrt is called. by invariant 6.23. P =?5 m. Since 01 is not in grph b. no nodes in graph b can have any operend links pointing to it. Since no operand links pointing to n1 are added in Critical Region I. there can be no links to n1 in graph a. either. Since operand links of node p point in graph a to each q?. none of them can be n1. so that by induction. each 260 - a reclb(x.). Therefore to nhnw m a reclb(e) it is only necessary to show o+ --HR ? The only eff?ct Critical Region I baa on the relation is to add the equivalence class j0x? Since o+ S a1 by hypothesis. and m p. m ?=bg p El a b Th?o?em 6.27. For any expression e. either rtcl (5) reci (5) or reclb(e) # and recl5(e) P?no? Let e be some expression. If red5(s) reclb(e). we are done. so assume recl5(e) ? reclb(e) Suppose n1 is not in red5(s). Then. by Lemnas 6.25 nnd 6.26. for any node m. m $ reclb(e) if and only if I t recl5(e). contradicting the assumption red5(s) ? reclb(e). Therefore a1 a recl (a). But since ToDo is empty end recl5(e) is nonempty. by Theorem 6.17 and 1nvari?nt 6.?1. rtcl5(e) is an equi?alence class of Since n1 a recl8(e) and the equivalence class containing n1 is fn1). red5(s) (m1J. But by Lemma 6.25. reclb(e) is a subset of red(s). But cannot be in recib(e). since n is not in graph b. Therefore reclb(s) is empty. El Cc?oll,?rv. If ?1 is in graph b. it is in graph a as well. Thereforc Invariant 6.22 must hold at the end of Critical Region I. 1h???? 6.28. Invariant 6.21 holds at the end of Critical legion I. P?nnf. Let o+ be a node in graph a. We must exhibit an expression a such that ? a recl5(e). If m is in graph b. then by Inysriant 6.21. there is an expression e such that m a recib(a). and by Theorem 6.27, reclb(5) red5(s). The other possibility is that I n1. Let p1. p2. ?k be the nodes pointed to by the operand links of n. Since these nodes are located by line 6 of Eqinsert. before n1 was created. they cannot be n1, and must be in graph b. Using the same reasoning as before. there aust be expres- - 261 --H aLone `1. `2? 1k aucb that Pj E recl'(1k). Tben. if f is tbe label of m. by Definition 6.16. m ( recl5(f(x1. P:`k?? ? La,tiat 6.2?. If e? =? ?2 and ?l is La grapb b. a2 is in grapb b as `Bell. liaaL. If and a2 are expressions. let a1 p a2 mean that is in graph b implies e2 is in graph b. We must then prove that 5j =b5 ?2 implies ?l ? ?2 Because p is both reflexive and transitive. by Lemma 6.10. it suffices to prove. by induction of the degree of a1. that o+? ?b5 ?2 implies ?l ? b Suppose ?1 ?S ?2 and a1 is in graph b. By Lemma 6.12. either (a1. e21 are in zqsh. or a1 is of the form f(xj x2. ?? and a2 is of b the form f(y1. yy?) where for all i a (I ... )L). z1 ? y? In the first case e2 is in graph h by Invariant 6.22. Let us consider the second case. Because ej is in grapb b. tbers is in graph b an eligible node p with operanda m1. mmk such that eacb b mi a rscl (x?). Therefore each x is in graph b. Then. by induction. b each yi is ia?graph b. so that by Invarient 6.20. `i :E ?i But then : so that mi a reclb(y?). and p a recib There raclb(x,). (a2). fore a2 is La graph b. U Le??i ?.?. ?or any expressions Cl sad a2. if red5(s1) is equal to recl5(e2) sad contains a node in graph b. then a1 =? ?2' li22L. Let C recl5(a1) -recl5(e2). Because C contains a node that is in graph b. C cannot be (n11. Therefore by Theorem 6.27. reclb(51) rec15(e1) and reclb??2? recl5(e2). Then. since raclb(e1) c :racl5(a2). a1 =ht a2 and by Invariant 6.20. a1 :? ?2 ? Tb?prem 6.31. Invariant 6.20 holds at the cad of Critical Region I. LLwiL. Let 5j and a2 he two expreajons in raph a. We lust shov 2t2 - List o+? II a. I --Hs 2 --H? 2 .J u..ty 1 a First. suipusa that a1 o+5? e2. wl.l.'h mn?.s that recl5(e1) : reclC(52). Let C : reclO(e1) recl'(e2). if C contains a code in graph b. tben by Lemme 6.30. e1 :? e2 Suppose C contains no nodes from graph b. c cannot be empty. because e1 and e2 are by hypothesis in the graph. Therefore C must conajat of Just (n11. Let f be the label. and PI. P?k bo the operanda of node ei. Since recl5(e1) recl'(e2) (nij by Definition 6.16. Ci must be of the fori f(a1. `xk) where Pj recl5(x ). and a2 muat be of the form f(y1. yy?) where Pj ( racl5(y?). Since recl5(xj) and rael5(y?) have an element. ?i in common. by Theorem 6.17. recl5(xi) recl5(y?). low each of p1. p?k must be in graph b. since they are located by line 6 of ?qTnsrrt. before a was created. Thcrafore. by Lemma 6.30. i? :? Y? Each ?i can be substituted for Xi in a1 to yield e2. Therefore. by Lenma 6.11. Cj 5a2. Next we must show that ?1 a =? e2 implies a1 =? e2. Suppose that ?i =? a2. Now either one of ?l and a2 ia in graph b. or neither of them ia. Suppose one of Lien is in graph b. Then. by Lamma 6.29. both are in graph b. and by invariant 6.20. we have that a1 = a2 and hence --HE reclb b b (e1) racl (e2). Since a1 is in graph b racl (a1) is nonampty. and by Theorem 6.27. recib(e1) recl5(a1). Likewise. recib(s2) 5 reel5(s2). so that: recl'(e1) reclb(a1) reclb(e2) recl5(e2). which means that ?l --H e2. The other possibility is that neither e1 nor a2 is in graph b. nut both of them are in graph a. Since reelb(e1) is empty and reel5(s1) La not. by Theoram 6.27. reel (a1) (a1). Dy the same reasoning. raej5(e1) (sa1). Thetaruta a1 e?. U 6.11 The Cnrrectn?pp IL Before soving on to Critical legion II. we will pause to prove the correctnecs of ?qInsert. In this section. b and a vill refer to Lbe state of the graph before and after a call to Iqinsert(s). and `Lr ii the node returned by tie call. Tb?n?e 6.32. For any expresaion d. if d is in graph b. then reclb(d) rscl5(d). ZLIL. Eqtnsert o+odifies the graph only by repeated ezecutions of Critical Region I. If recl(d) is noneapty. by Theorsa 6.27. an sIecution of Critical Region I does not change recl(d). Therefore reclb(d) recl?(d). 0 Thpnreaa 6.33. Expression e Is in graph a and nr is a representa- tive node in recl5(e). ???. The proof is by induction on the degree of a. after the i'tb racursive call to Eqinsert at line 6. by induction and Theorea 6.?2. recl(?1) will be noneapty. and a(i) will be the representative nods in recl(x.). Then a node n with label f and operands a(l). a21. ... a(it? will be found on line 8 or created on lines 12-20. By tefinition 6.16. a a red5(s). The representative of n. 0r is returned as the value of Eqinsert. Sinte nr :g n. and tberefore nr :N n. nr a red(s). 0 6.12 Cr't'cai Awna IL Critical legion II aodifies both and E?. To prove Invariant 6.20 ho?ds at the end of CriticaL legion II. we must prove that both relations are updated in the seane fashion. In this section. `.b" will refer to the 26e - erapb b-fore?Critical Region LI is executed and "a? will refer to the graph afterwards. 1??--H 6.3?. For any nodes I and n. and any axnressione d and as if d b --Ha (6.6) e then d if ? =b ? then ? =a n (6.7) --HN --HN if n e reclb(e). then n c recl?(e). P?oof. Suppose d b ? Then there is a sequence of nubstitutions using expresajon pairs in EQSb that will transforss d to a. But every expression pair in tq?b is also in EQS5 so hat d a. Thus. (6.6) is established. A sinilar argunLnt will establish (6.7) and (6.8). If b b n (or n ? reci (e)). it is becsu?e of a collection of nodes and fields in graph b. Since the only difference between graphs b and a La the addition of a pair to ToDo and a pair to E?S. the sane collection of nodea and fields are in graph a. so that m n (or n a recl?(e)). 0 Theo-pn 6.35. Invariant 6.22 holds at the end of Critical Region II. XLm&L. We nust stww thnt 11 (a1 a2) e ????. then v1 and 02 are in graph a. Let (a1. a2) be a pair in EQSa, Then. either (e?. e2) a (xx yy) or (a1. a2) is in gQ5b In the first case. line 4 of Eqinsert and Theorems 6.33 and 6.32 guarantce that a1 and a2 are in graph b. In the second case. a1 and e2 are in graph b by Invariant 6.22. But if a1 is in graph b. there is a node n such that u a recib(e1). By Leama 6.34. the sane node n is in recl5(e1). Therefore e1 is in graph a. By the same reasoning. a2 is in graph b. (1 TI,.,r.?n 6.36. Invvrla?t 6.21 holds at the end of Critical Region 11. 265 Proof We must sbov for every noas u. there is an expression 0 such that m ( recl5(e). Let I be a node in graph a. By invariant 6.21. tberr is an expression 0 such that n ( reclb(e). 3y Lemma 6.3?. n a red5(s) as `.ell. 0 Thenrem 6.37. if expressions a1 and e2 are in graph a and Ci =--H: e25 then a1 =--H: e2 liaaL. For expreasiot?s d1 and d25 define the relation d1 p d2 to mean d1 is in graphs implies that d2 in in graph a and d1 ?; d2. To establish the theorem. it is sufficient to prove that a1 =? impliea --Hs ?2 ?l ? a2. But notice that p is both reflexive and transitive. Therefore. by Lemma 6.10. it suffices to prove that Cl e2 implies ?i ? a2. The proof vill be by induction on the sun of the degrees of ?i and Assume a1 is in the graph a. and Cj e2. By Lemma 6.12. either (a1. e21 is in EqSa. or all of the following: a1 is of the form f(x1. xxj) for some j ? 0 a2 in of the form f(y1. y2. Yj) (6.10) for sl1?i in (I ... ii. xi--H: yi (6.11) hold. if (a1. e2) is in EQS5. then either (a15 a2) in in BQ5b or (a1 o+2? (xa. yy). if (e1. a2) is in sO5b, then by invariant 6.22. both b and c2 are in graph b. and by invarlant 6.20. a1 --H=E ?2 By Lemma 6.3?. a2 is in graph a and a1 :--H; a2. Nov suppose (a1. a2) (xx. yy). We )Lnov by line ? of EqAssert and b b Theorema 6.33 and 6.32 that nx a reci (xx) and fly a recl (yy). so by Lemma 6.34. nx a racl0(xx) and ny a recl5(yy). Thcr?fora a2 is in graph a. Since (nx5 ny) is in ToDo5 by Thtortm 6.1?. nx :N5 fly. Then. by Theorem 6.1;. rccl?(xx) rt?l5(yy). an tl,?r.'iurt ?? a --HE yy. - 266 - rIally. cusider tIe tea I ?I,i?I (6.?). (?.l?). and (6.11) I.uld. Because e1 is in graph a. reci (e1) euat be nonciply. There `suit be an eligible node p with label f and operands o+?. `so+? such that e recl5(x?). Since each Xi =5s ??. by induction. Xi m?5 y? Thus. recl?(x.) a recl5(y?). so that Ii E recl'(yj). and p E red5(s2). We have established that p is in both recl5(e1) end red0(s2). fly Theoress 6.17. recl5(e1) recl5(e2). and thc-r?4ore e1 =? e2. U 1.??? 6.38. For two expressions a1 and ?2 if reclb(e1) II reclb(s2) is nonempty. then ?l =S ?2 P??f. fly Theorem 6.17. reclb(ej) and reclb(e2? are equivalence b classes and are therefore equal. Then. by Definition 6.19. Cj =5t recib b Since (e1) and recl (e2) are both no??mpty. by Invariant 6.20. b -5 I] ?l m? e2 and by Len?a 6.34. ?l ?2 ?A 6.39. Given two nodes n1 and n2 such that n1 :--H: n2. there are expressions a1 and --H2 such that n1 a reclb(a1). n2 a reclb(?2?? and e = a I --HS 2 lianL. By Invariant 6.21. there must be an expression d1 such that b a a n1 a recl (d1). Since n1 N n2, n1 h--H=N n2 for some h ? 0. We will now see. by induction on h. that a1 h=N n2 implies the existence of an a?pr?priate a1 and e2. If h 0 ?N5 is the identity relation. so that c? --H?n2. It suffices to choose e1 ?2 d1. For the induction step. assume h ? 0. If m1 and m2 are node.. define the relation m1 p o+2 to mean the existence of an expression x1 such b that ml a recl (x1) implies the existence of an expression x2 such that `2 ` reclb(12) and xi =5 x2. If we could just show that o+1 ?--H=? `2 iuplies `1 ? `2 vs would be done. because we have a1 h=N5 n2 and n1 a reclb(d1). But notice that p is both reflexive and transitive. Therefore. by - 267 - Leeca 6.10. it surtices Lo alww thsL 1? h??N5 12 iiplies 11 P s'2' Suppose that 11 12. and there is an expression `i such that 11d reclb(x1). Then. flefinition 6.14 aduits three possibilities: (l) m? =-; 12 (2) (Il. 12) is in Toflo (3) o+? and o+2 are eligible nodes with identical labels and equivalent operands. In each case. we will see how to find expressions `2 and Z3 such tbst e reclb(`3). o+2 ? reclb(x2). and ?? --Ha `2' Then. since is in both raclb(x1) snd reclb(?). by Leums 6.38, x? =? `3 Then x? =? `3 =? `2' In case (1). choose `2 ` - `1' Then trivially `3 =--H: `2' and 3- II C reci (x3). Siuce the reprlinks in graph a are the rane as the b b reprlinks in graph b. o+l a `2' and by Theoren 6.13. `I =N `2' Since by Theore. 6.17. reclb(?) is an equivalence class of ?. so that Un have `2 ? reclb(?). Since `3 `2' `2 ? raclb(x2). 1:ext consider case (?). Either ?1i' 12) is (nx. ny). the pair placed in ToDo at line 5 of EqAssert. or (lj. s2? is ao,e pair in Toflob. In the first subcsse. line 4 of EqAssert and Theoreus 6.33 and 6.32 b b guarantee that nx a recl (") and ny e recl (yy). Line 6 of `qAssert guarantees thst (xx. yy) 1Q5a, so that Xx yv. If ni and `2 ny. choose `2 to be yy and x? to be,'.' if I? ny and 12" nx, choose `2 to be xx end X3 to be yy. In either case. `i a recl (`3). `2 ? reclb(x2). and ? =--H: `? b In the second aubcaae. ?`l' `2? is a pair on ToDo . Than. by Invariant 6.21. there lust be expressions X3 and `2 such tbst 1b and a a reclb(x) b I rec . but since ?`l' `2? is on Toflo 1 a 2 2 b b 11 --H=N `2' and therefore `2 Eg `2' Then. by Invarian' 6.20. `re have - 268 and by Theorem 6?34. we have =n5 ?2' (Actually. tbis subcaae --Hc bolds vacuously. because ToDo must be empty before Critical Region 31 is entered. But because of the modifications made to Algorithm ?q in Chapter 7. it is i?rortant to prove Critical Region ii correct without the assump- tion that ToDu is empty.) Finally consider case (3). Then m1 and m2 are eligible codes with the sa?e label f. such that for some k ? 0, m1 has operands PI. P and has operands q1. qc'k' ?here for each i. p1 ji=?b? ni for some < b. Then by induction. there are expre.siona y1. y2 o+`. and 5j z2 o+. Zk sud that for each i in (1 ... k). ?i e recib(y?). q1 ( reclb(zi) and =-: 2? Let ?2 f(z1`52''''2k? and f(y1. yy?) By Lemma 6.11, x2 53. By Definition 6.16, m1 a rec1b(53) and m2 ? recib(x2). (1 b L:ina 6.63. For expressions e1 and e2. if reci ??l? n red5(s2) is nonempty. then e1 e2. P'oof. The proof is by induction on the degree of ?2' Let n be a node that reclb(e1) and recl5(e2) have in comeon. The expression ?2 will be of the form ???1 ?2' 5k? for some k ? 0. Because n a reci by Definition 6.16. there must be an eligible node p with label f and operands a1. mak such that each m1 e red5(s1). and ? a. Let y1. y?? be any expressions such that m. a rectb(y.); by invariant 6.21 such expressions must exist. Then. letting e3 f(y1. y we have. by Definition 6.16. p a rectb(53). Since recl???i? and reclb(yj) both ct?ntttin mi. by indttctiun. x? y1. anti by Lcema 6.11. t2 c3. Since p n. by L,'msa 6.39. ther ar? expression. e4 and e? such that p a reclb(54). n a rsclb(e3). and 54 =?a 53. Because p is in both recib(53) and reclb(54), by Lemma 6.38. e3 =5? 54. Likewise. since a is in both roclb(e5) and reclb(e1). e5 =: a? Tberefcra ye a a =a =a o+2 --H=5 e3 ?=? ?4 --Hs ?5 --Hs o+i Thppre= 6.41. If e1 and are in graph a and a1 :--H; e2. then el =9 e2. liflgL. Asaume Ci and e2 are in graph a. and a1 =: e2 Then ?ecl?(e1) recl'(e2) JE #. Let 0 be any node in recl'(e1). By Invariant b 6.21. there is an expreasion e3 auch that n a reci (a3). Since n is in both red5(s1) and recib(e3). by Lemma 6.40. ?1 =--H; a3. By the same rea- aoni?g. a3 =--H; e2. Therefore e1 =?6 a3 =--H: ?2. ? 6.42. In?ariant 6.20 holda at the end of Critical gagion 11. Proof. We must ahov that if a1, and e2 are in graph a. then e1 :--H; C? if and only if a1 a2. Assume e1 and e2 are in graph a. If a1 =?g ?2 by Theorem 6.41. ?1 :--H: a2. If a1 =? a2. by Theore. 6.37. e? a2. 0 6.13 Cr,tj?al Sp.jon TIT The change Critical Region III makes to the graph can be broken dova into a aeriea of actions. When describing an action. the superacript ?b? yill refer to the state of the graph before the action. and "a" to the atata of the graph after the action. Here are the four actions performed in Critical Region III: (1) A pair (x. y) is ramoved from ToDo. If necessary. a rapriink ia added so Unt x y (lines 9-15). (2) An oporend link pointing to y1 is changed to point to ??. `phere a and b =? y1. there are nodes `2 and y2 such that `1 --Ha `2' y b y1 --HR `2 and ?`2 y2) is on ToDo (line 19). - 270 (3) A node a is o+owed from one btcket to another (lines 22 and 28). (4) A node a is o+ade ineligible. end a pair (d. a) Is placed on Tollo. vhere d is eligible. and d and a have identical labels and operand links (lines 22 and 27). thore--H 6.43. Actions (1-4). can each be implemented by a sequence one or more of the following actions: b (5) Add (a. y) to ToDo or add a reprlink from a to y. where ` m? y (6) ?e?ove (a. y) from ToDo. or delete a reprlink from a to y. where b (7) Change an operand link pointing to a to point to y. where a =N 7 and a 7. (8) Set or clear the eligibility bit of a node a. if there is another eligible node with identical label and operand fields. (9) Change the bucket that a node a is in. ?. Action (I) is implemented by using action (5) to add a reprlink from a to y. if necessary to ?ake a y. and then using action (6) to delete the pair (a. y) from ToDo. Action (2) is implemented with action (7). Action (3) is implemented with action (9). Action (4) is implemented by first using action (8) to make a ineligible. and then using action (5) to add the pair to ToDo. U For the remainder of this section. nbn will refer to the state of the graph before one of actions (5-9) is performed. and SaWI will refer to the graph afterwarda. b a i??- 6.44. For any two nodes n1 and n2. n1 ? n2 implies n1 --H n2. b P?nof. We will prove. by induction on h. that n1 h--HTh ?2 implies m1 a n2. --H? The hase case. in which h 0. is trivial since is the idan- tity relation. For h ? 0. by Lemma 6.10. it La sufficient to prove that b ?l h?M ?2 implies Di ?11 n2. b Suppose ?l h??I ?2 From Definition 6.14. there are three posaibili- ties. the first of which ?? b t5g by a =R n2. The only way that n1 n2 is reprlink from x to y being deleted by action (3). But since the rep?t'ink La deleted only if 1 y n1 =5N n2. A similar argument is used for the second posaibility. that (n1. n2) is in ToDob. The final possibility is that n1 end n2 have identical labels and operand links PI. P2 ?k and q1. q?? such that each ?i ji=Nb q1. for Some ij < h. Then. by induction. ?1 q1. The operands of n1 and n2 may cot be ?i and in graph a: they could be changed by operation (7). But an operand link is changed from m1 to m2 only if m1 =-: m2. so that the corresponding operands of n1 and n2 will be equivalent in graph a. sod n1 n2. 0 `e?? 6.45. n1 =b? n2 if and only if --H: ?2 Proof Since. by Lemma 6.44. n1 b n2 it is only =N n2 implies n1 no?uflsary to j'rovt' n1 a 2 i.i?lLcn I'l .`2 Th?t is. wu m?.st eI??w thet --HN if n --H=M ?2 aftcr one of operations (3-9) is performed. then n1 n2 .1 beforehand. But since the inverse of every operation in (5-9) is among (5-9). this second implication is proved by Leema 6.44 as vell. 0 Lau6.46. For any node n. if a a reclb(e). then n a recl5(e). Proof The proof is by induction on the degree of e. The expressiom a will be of the for. f(x1. `1k? for some k ? 0. Assuming a reclb(e). 1 there is a node p that is eligible in graph b. with label f reclb end operenda ?1? ?2 mk such that each m? a ?`i?5 and ? =bM n. By Lemma 6.45. p N5 b. By induction. mi a recla(xi). As the result of action (7). an operand of p in graph a may no longer be mi. But if is the nev operand. q1 --H=: o+? so that q1 a recl5(xi). As the result of - v,, - action (7). node p say =10 long be eligible. Du there viii be an oust- ble node d with label and operand fields identical with those of p. By Theorem 6.15. d ? p. In either case. n , recl5(e). 0 L==L 6.4?. For any expression e, reclb(e) red5(s). b ?L. By Lemma 6.46. if n ( reci (e). then n a red5(s). There- fore we need only prove that if n a recl5(e). then n a recib(s). Since tbe inverse of every operation in (5-9) is among (5-9). Lemma 6.46 proves this implication as well. 0 Th??? 6.48. Critical ?egion Ill leaves ?. reci. ?. and invariant. ?iL. The change made to the graph by Critical Region III can be perforoed by a series of actions (5-9). each of which, by Lemmas 6.45 and 6.41. leaves --H=N and recl invariant. Therefore Critical Region 111 leaves and reci invariant. Since --H=E is defined in terms of recl. Critical Region Ill leaves invarinnt. Since Critical Region III does not change EQS. it leaves = invariant. --HS Co-niiarv. Invarianta 6.20. 6.22. and 6.21 hold at the end of Criti- cal Region lii. 6.I? Thp CiL All of the invariants have now been established. ?t i? now easy to establish the correctness routine Eqquery. and hence. of Algorithi ?q Th.,.rpa 6.49. E?Query compotes =? noaL. By Theorens 6.33 and 6.32. after lines 4-5 of Eqquery hsve been execoted expressions xx and yy will both be in the graph. nx will be a reresentarive node in rccl(xx). and ny will be a representative node in recl(yy). By Theorem 6.? and Invariant 6.24. nx and ny will be the only 273 --H representative nodes in recl(x:) and recl(yy). so that recl(xx) : recl(yy) if and only if nx fly. By Invariant 6.20. xx ? yy ii and only if xx ?as y. Therefore: xx =? yy iff xx =? yy iff recl(xx) recl(yy) iff a' ny. 0 6.13 Zhn LLw?ing lint aL Aisor?rhm ? Thepr?--H 6.30. If N ja the total si:e (the number of function sym bola) of all the expressions in a sequence of Aasert and query instruc- tions. that sequence can be processed by slgoritbm Eq in expected time o(N log ?). Proof I make the ueusl assumptions about baehing: that the nunber of buckets ie large with reepect to the number of nodes. and that the basb function distributes the nodes evenly among the buc?ets. so thet no bucket gets too full (331. In thia analysis. I will assume the searchea on line 8 of Eqineert and line 2A of EqAseert are performed in oCi) time. Another simplifying assumption made is that there is an upper bound X on the number of operande that any function can have. However. this assumption is not very restrictive. If functions with an unbounded nunber of operenda are desired. one needs on?y to re??rve two function ay?lole nconefl and "nil." Then the expression f(x1. ?xk) can be encoded as f(cuns(xj. cons(x2. ... c?ns(x? nil()) ... ))). ?ince this en?udin? increases the size of the input only by a linear factor. it does not effect the asymptotic running time of the algoritha. Only 0(N) time is spent outside Eqinsert and EqAssert. To prove the O(?i log N) running time. a scheme is presented for charging coaputation to function symbols in the input and nodes in the graph. We will see that the tima required to porform Eqinsert(e) can be accounted for by charging - 2?4 - U(L?g n) tiie to each ut the eym?ule in t.. iho Lime required to ucrforet TqAa.-rt(aa. yy) I. accounted for by charring O(Iog ?) to each of the cy.- bola in xx and vy. and charging ?ovcrtimc? to Come node. in the graph. Throughout all of the calla to EqA.sert. each node of the graph will ab.orb O(log M) overtime. Since every node in the graph can be aaaociated with a unique function Cymbol from the input. there con be at o+o.t N node. in tha graph. Therefor? the amount of overtime ia o(N log N). The loop on line II of Eqineert can require at moat log II itera- tiona. By Invariant 6.3. each iteration of the loop at lea.t double. n.reprcount. and aince 1 s n.reprcount ? N. n.reprcount can be doubled at suet log ? timea. Simila,rly. the loopa on linea 10 and II of tqAaaert cam require at moat log M iterationa. FqInnrt(e) charg-a O(log Tt) time to each of the function aymbol. im e. Let e be of the form f(x1. x2. . xk) for aome k?. ?qIneert firat recur.ively charge. O(log 11) time to each of the function. aymbol. in Then it perform. line. 6-21. which require O(log N) time. charging it to ?ext. conaider routine ?qA.aert(xi. ?y). As we have just .een. the calla to Eqlnsert(xx) and ?qInsert(yy) charge O(log M) to the aymbola in Ii and yy. The O(log ?I) time apent in line. 10-11 on the firat iteration of FqLoop can be charged any aymbol in xx or yy. All of the time apent in ConLoop ia overtime. and ia charged to tha node.. For each node. aeparate aubaccounta are kept for each operand field. ConLoop require. 0(1) time for each element on the container liat it ia aearching. and the time ia charged to each operand field updated at line 19. When an operand field ia updated on line 19. it Ia changed from y to x. its ratotiL In tIa? top?llnk fuie.t. flint's I ? v.tuj't-?uunt ? v.roprcotint can be doubled at must log M tises. sy Invarlant 6.3. the modification at least doubles v.rcprcount. Thcrcfore. throughout the entire computation. tbe aubaccount for each is charged O(log N). Since each node baa at most K operanda. each node La only charged O(log II) over- time. The O(log N) time spent on lines 10-11 of EqAssert in the second and subsequent iterstions of EqLoop is charged to y. The node y atiat bave been the node I on line 21 of a previous iterstiun. The node a is changed from eligible to ineligible on line 21. Since there is no place in the algorith. where an ineligible node is made eligible again. node a rcmaina ineligible. Therefore the node cannot be put back onto Toflo by subsequent executions of line 27. and cannot be charged O(lug fi) time again. U The running tias of klgorithe Eq can be improved uaing a technique called iipath compression.5 Each loop of the form: ihitat x.reprlink ? iii ii x S- z.reprlink at vh?ch traces a branch of a tree to its root. is replaced by the following: a :: a whie z.reprlink `I ic: a t= a.reprlink at : vh?ie a I ? t t z.reprlinkt r.reprlink : x? a :? t at After the root of the tree is found. the reprlinks of the nodes pssaed through to get to the root are updated to point directly to the root. Path compression preserves the correctness of Algoritba Eq. becausa it does not invalidate Invariants 6.2 or 6.3. and it does not change the relation Although path compression improves the asymptotic running Lime of 27? the V';Io5-PlND elsoritbi (3) it doea not i?prove the esymptotic rucnin? time of Algorithe P?. because it does not reducn tbe length of the con- tainer lists. As expisined in section 7.6 the Proof Checker does not use path co?pression. CWTRR 7 THE V-CODE INTERPRETER 7.1 i-t? Inatru-?Icna The V-code inatruciona introduced in Chapters 3 and ?. and be actions specified by then. are: PROCLAIM P Add P to the Assertion Table. REQUIRE P Report an error if P cannot be deduced via automatic :ulee - front forinulaa in the Aaaertion Table. NEW v Replace every occurrence of the variable , in the Aaaertion Table by a new variable v' that doea not appear in the Aaaertion Table or in aubacquent V-code inatructiona. OPEN Puah a copy of the Assertion Table onto a staclt. CLOSE Roplace tic aaa,'rtion table by the top of the stack. and pop tiie st??k. CLOSE-NIW Perform a CLOSE inatruction as above. aud re-execute every NEW inatruction that occurred between the CLOSE-NEW instruc--H Lion s?d its matt.hin? U1'l.?N ins'ruction. There are other V-code instruction? (VCOTO. for example). but fron the point of view of the V-code Interpreter. each of th?ae other inatructiona is juat an abbreviation for a aequence of the above six inatructiona. The deacriptions Siven above are intended as apecifications. and are not dcscripticns of the impl-m?ntetion. Tls? im?lementation ?E the V-cole lntrr???.'trr will be Je.cribed incremt?telly. In sections 7.2 and 7.3. an interpreter will be described that only executea PROCLA1N and REQUIRE inatructiona. Then in 5?ction 7., the NEW instruction ia added. linally. In sectiona 7.? s?d 1.6 the imple--H - 278 - r r (1. 2. 3) .1.3 P .013 P Q P'Q P'Q (4. 5. `) r&Q q q (7. 8) P?Q PIQ r P P->Q (9. 10. 11) P=)Q - Q p->q q?>r (12. 13. 14) P:>q Q?>p F-Q R(P//x) P--Q R(?llx) (15. 18. 17) I[Q#xJ R(Pllx) ?<->Q R(PllxJ ?<-->q 1(QllxJ (IS. 19. 20) a(Qll?1 R(?llx) rigure 7.1 The PLICV Autonatic Rulee nentation 0 the OPi2?. CLOSE. and CLOSE-N?W instructlone is discussed. 7.2 Th pRf>rIATM sal pFp?TRF ;??t??r,nns Were it not for t)e automatic rulee. PROCLAIN and REQUIRE could be leplemented uaing a simple table lookup scheme. The automatic rulee con--H siat of the rulee shown in Figur? 7.1 and the Transformation Axioms above in 7igures 5.1 and ?.2. The algorithm uaed to implement PROCLAIN and REQUIRE will be obtained by modifying algorith. Eq. which waa pre.ented in Chapter 6. Let ua review Algorith. Eq. Civen a set EQS of pairs of formulae - 279 - and twu urmulss ? and Q. the relation r ? Q La detined to hold whenever it La possible to transform r to Q using a sequence of substitution. of one element of a pair in EQS for the other element of that pair. Algo- rith. Eq maintains a Srspb o+tructurs in which each node r?'presents a ccl- lection of formulas. A formula is said to be "in the grspbfl whenever it is represented by some node in the graph. The relation EE iS defined over the set of formulas that are in the graph; ? :E Q is defined to hold when- ever P end Q are represented by the sane node. When a new pair is added to EQS. the rsph is updated so that and are the same relation (whom the domain of is restricted to the set o? formulas in the graph.) The set EQS is not used in the computation; it is an auxiliary vsrisble?used to argus the corrsctneaa of the algorithm. A node with label p and operands 01. n? represents all for--H mulas or expressions of the form p(x1. 12. ... 1k?? where for all i in (I ... ki. 0? represents x? An equivalence relation is defined over the set of nodes. A class C of i. said to represent a formula F when- ever there is a node n in C such that n represents P. Another equivalence relation which is also defined over the set of nodes is determined by the reprlinks of the nodes. The relation is always a refinement of the relation ?. In every equivalence class of there is exactly one node whose repriiok is a?1; this node is called the ?repreaentstiv's? of the class. A representative nods r represents not only the formulas or expressions defined abova. but also all fornulsa or expressions P for which there is a node n such that n represents P. and O r. Each operand field of every node points to a representative node. The V-coda interpreter will consider a formula P to be "proved" whenever ` ?l?L When a PROClAIM P instruction is processed. the fo? 280 (01) zqnAsaert(nx. ny): (02) ):tt? (03) Add (n?5 ny) to Toto ? Add (ix. yyj to EQS 1 (05) ?qLoop: (06) vh?l ToDo is not empty (07) ? Remove an element (x. y) fros ?oDo whilp x.reprlink ? nil ? x : ?.rspriimt ? (09) ?h?' y.reptlink `E ? y :-- y.reprlink aA (10) : iL x ? y (11) thpn jL y.reprtount > x.reprcount (12) th?n swap x and y Li (13) y.rt'prlink :-- x (14) x.r?prcount : x.reptcount + y.reprcount (15) C?Lo?p: (16) f'? t'vcry w on y.containers (1?) ga w.operand :-- x (IS) z :- a point?r to (is) z is eligible (20) ti?.n Rt'uuve z from the bucket it is ie , h :-- hash(z.lnbei. z.operanda) (22) Search bucket(h) for a node with (23) tht e?me label aud operands as a (24) a li the aearch finds a duplicate d (25) ?? Add (d. z) to ToDo (26) c?? Put r in b?cket(h) (2)) It (28) I (29) li (30) (31) ; Append y.Containers to x.containars (32) a (33) li (34) Ig (35) ?a'L the node containing v.o:erand FiLurs 1.2 Routine tqnAasert 281 mule P ia inserted into the graph. the pair (P. `l's) is added to ZQS. end the sraph is updated to keep the relatione ? and :s oonaistent. In this section. we will see bow to modify Algorithe Eq no that an it discovers flew formulas to be equivalent to .118. it applies proof rules to these formulas. and adds new pairs of formulas to EQS. A pair (r Q) is added to EQS only if the formula P Q or a <--? Q can be deduced from formulas that have already been proved. Before any V-code instructions are processed. the formulas 1111 and 1018 are inserted into the graph using the statements: TrueNode :-- EqlnaertL'l'BJ FalseNode I EqlnsertL'O'BJ (The double brackets are used to emphasize that formulas. not bits. are being passed to EqIn?rt.) Algorithm Eq `will be modified so tbat the two variables TrueNode end FalseNoda are updated as necessary so that they will always contain the pointers to nodes representing the for)tules Ills and 1018. The instruction PROClAl? a is then implemented by: EqnAssert(Eqinsert(P). TrueNode) The routine EqnAasert is obtained by modifying the routine EqAssert. which appears in Figure 6.10. FqAssert is first modifjed so that it takes pointers to nodes as arguments instead of formulas; the result of this modification is shown in Figure 7.2. Then the statements in Figures 7.3 end 7.4 are added so that deductions are performed. Some new fields are added to each ?ode so that all the members of each equivalence class of the relation can be put on a linked list called the ?reprlist." The head and tail of the reprlist containing all the ele.ents of a class are stored in the representative node for t),at class. It is necessary that both the head and tail of the reprilat be stored in the node. so Lhst reprliats can be concatenated in constant time. A bit field "established" is also sdded. If 0 is a node. c.estsblished will be LnLe whenever TrueNode is the representstive of u. Finally. a bit field "equiw" is added. This field is only signifi- cant when the label field of a node n is fl>5 If 11 and m2 are the operands of the node n. and n.equiv is t?.'? then `si --H=N 12 The converse of this stateeent is not true; n.equiv can be false when ml :N m2. This field is not necessary to obtain a correct slgorithm; its purnose is to reduce tht running tint of ti,e algorithm. Wen a node is created by Fqlnsert. it is put into a new equivalence class of fg. Ticrefore. its reprijat consists of just itself. and its established bit is set to Lliu. Uhen a node is created whose label is ?->". its equiv field is set to 1flw if its operands are identical. and liLa otherwise. Figures 7.3 and 7.4 contain the statements that must be added to IqAssert. If n is a node. the notation (u) is used in Figures 7.2-4 to denote Cone eapresajon such that n represents E(n). By Invariant 5.21. an appro-riate E(n) must exist for each node n. Here is a sunmary of what the statements in Figure 7.3 do. In lines (01-04) it is determined whether one of the two classes being merged is tbe class representing `l'B. and if so. a pointer to the representative of the other class is stored in the variable "merged.5 Lines (03-06) are used to maintain the invariant that TrueNode and FalseNode are pointers to the nodes representing the formulas ?l'B and `O'B. If one of the two (01) ( (02)1 (03) (04) (05)1 (06)? (07)1 (08) (09) (10) (11) (12) (13) (14) (15) (16) (I?) (18) (19) (20) (21) (22) (23) (24) (25) (26) (27) (28) (29) (30) (31) (32) li (33) Ii (34) (35) li (36) 1 Append y.reprlist to x.reprlist (37)) ??raed 1 niL IL x TrueNode ?hen o+erged :: y &LiL 7 TrueNode th?n ierged s: x li IL 7 TrucN?de Lhgn Trueflode :-- I IL y FalseNode tLLwL FalseNode I: z li il Ierged ? niL LaL every node z on merged.reprlis? ? :.established : t??P let z.opersnds be (n1s n 1 IL z.lahtl rh?n Add (n1. TrueNode) to ToDo ? Add (E(n1). `l's) to ?qs ? Add (n2. TrueNode) to ToDo ? Add (E(n2). `l's) to EQS ? )JIL z.label thwi Add (n1. Felfie??dt? to ToDo d Add (E(n1). `0's) to EQS ? plif ?.lahel ?? 0 z.label `bpn Add (n1. n2) to ToDo ? Add (E(n1). E(n2)) to ToDo ? lijL ?.lebel tiLca h hash(5->5. (n2. n1)) 1 Search bucket (h) for a node ?ith label ":>n and operands ??2' ?l? 1 iL such a node s is found the iL m.established flinn Add (01. ?2? to Toflo ? Add (E(n1). E(n2)) to ?s d s'.equiv I- `r?p s.equiv t? lija Figure 7.3 An Addition to loutina LqnAsaart ?Ol) ( i?r ?.oprenda be (n1. ?2? (02) I IL ?.label ?>? a?d z.establishad anA ?.equi? (03) ?h?n h :-- hnsh(?->". (n2. n1)) I Search hocket (hi for a node (03) ?ith label ???> and operands (n2, nj) (06) I iL the search finds a node r (ci) r??n jL r.c?tablished (08) lh.n Add (n1. n2) to ToDo (09) t Add (E(n1). E(n2)J to EQS ? (10) z.equiv (11) r.eqoiv :- ?re (12) li (13) li (I'.) li (13)) Wigur- ?.A An addition to F?nAssert elassee being o+erged represented o+i?a before the merge. tbs TaprIjet of the ether class is traversed by lines (08-3A). The "eatablisbed" bit of each node in the class being merged is set to ?. Deductions then are made on the basis of formulas that are newly discovered to be valid. After the reprifet of 5 or y has been traversed if necessary. the raprlist of y is appended to the reprlist of x by line (36). When an operand field of a nod? z le changed. the new node to which the field points represents a larger class of formulas or expressions. and hence the node z also represents a larger class of formulae or expres- sions. If z is in the class of nodes that repreeents the formula `I'D. sore new for?ulas have been estehlished. fle statements in Figure 7.A are used to perform deductions ba,cd on these newly established formulas. All of the chan?'es made to the graph by the statements in Figures 7.3 and 7.4 are oE the form: - 285 (1) add a pair or: formulas `??l ?2? to o+?S where and 52 sre both in the arapb. and (2) if n1 and o+2 are nodes representing Pj and ?2 add (iii. 02) to Toflo. The o+odification made to the graph is the same kind of modification per formed in Critical Region II of EqAssert. Because the proof in section 6.12 does not depend on the fact that TuDo is em?ty. the same proof can be used to show that the statements in Figures 7.3 and 7.4 maintain all the necessary invarianta discussed in Chapter 6. It is. however. necessary to convince ourselves that the pairs of formulas being added to EQS are in fact equivalent. when lines (13-15) of Figure 7.3 are executed. the formula 5 & Q. where 5 is t(n1) and Q is E(n2). is represented by node a. Since a is being merged into the class represented by True?Iode. we know that 5 & Q = `l'b. That is. the formula --HF 5 4 Q has been proved. Therefore the formulas 5 and Q sre both valid. and the pairs (5. ?l?Bi and (Q. `l's) nay be added to EQS. In a similar fashion. ? `C'S is being deduced from 5 in lines (17-18). 5=g Q is being deduced froi 5 Q or 5 <-? Q in lines (20-21). In lines (23-33). since a valid formola of the form 5 -) Q has been discovered. the graph is searched for a node representing the formula Q :> 5 If it is discovered that TrueMode rcpresenta Q :> 5 then 5 ? Q is deduced as a consequence. The statements in Figure 7.4 are executed whenever an the operand of a node a i. changed. and the class of formulas represented by a is thereby e?pended. If tho node a rcpre.ents a formula of the form 5 ? q. and --H=R TrueNode. a .earch is pcrformed for a node r representing 5 ) Q. If r =? TrueHode as well. then r =E Q is deduced as a consequence. The ?odifications made to Algoritha Eq do not i1)creass its expected - 286 e.7?rtu?it a?.?..ia,? LI--H, TI.. --Hsta a LIme asiulacal ly the steLseents Ia' Figure 7.3 to traverse the r?prlist and add a pair to TuDo can be charged to the nodes on the tcprlist. Fech extra pair put onto ToDo aa pert of tbs proceaaing of an element a of a reprijet vill require O(log ?) time to proceca when the pair Ia taken off ToDo. The 0(los N) time will be charzed to the node a. Beccuac a node can be merged into the class representing?'l'fl only once, only O(log N) extra time is charged to each node for the staSements in Figure 7.3. The pair added to ToDo in by the statements in Figure 7.4 will also require O(log N) time to process; this time is charged to the node a. The ?air is put onto ToDo only if z.equiv is itiLit:. and then a.equiv is set to ?flL?? and left unchanged thereafter. Therefore. this extra O(log II) time can be charged to each node at most once. npfin.r;nn 7.1. We will say that a formula P is 1.established" when- ever ? is in the graph and P =? T?en?? 7.2. Whenever ToD? is empty. the graph will have the fol- lowing closure properties: If F & Q is established then P = `I'S and q `I'S. (7.1) --H? If --HP is established then P --H `D'S. (7.2) If P q is established, tnen P q. (7.3) If 5 ?--> Q is established, then ? =E q. (7.4) If P --> Q and Q > 5 are established, then 5 =g li??L. Let us first establish that the graph has property (7.1). Suppose 5 & Q is in the graph and 5 & Q : `l'? Then thers must be an eligible node a whose label is "?" and whose operands are two nodes Ij and a2 representing 5 and Q. Likewise, there must be an eligible node t with no operands whose label is 1.al?S1.. and it must be the case that a m? t By Iivaa lest O.??. ir Ttl? is e.rty. LIes ???? --HM are the same relatium. fl?reforo. I L --HeR TrurNode. Therefore. at some point during the computation. the equivalence class of eg containing z must have been o+erged with the equivalence class representing 1i0B. The superacript "m? will be used to denote the state the graph was in just aftor this m?rge was performed. Let Yi end Y2 be the operends ` had in graph m. Lines (12) and (15) in Figure 7.4 guaran- tee that y1 =? TrueNode' end y2 =? TrueNode'. Because the operends of z could have been changed by line (17) of Figure 7.2 at some time after the merge wee performed. y1 and y2 nay :ot be the same nodes as `Li and x2. And since the variable TrueNode could bave been changed by line (05) of Figure 7.3. TrueNode? may not be tbe same node as TrueNode. But since: (1) an operand is changed from p to q only if p :N q. (2) TrueNode is changed from p to q only if p o+? q. and (3) the only changes made to =--HN make the relation coarser we can conclude that `? =N y1. `2 --H=N y2. and TrueNode = TrueNode. --HM Tberefore. by treneitivity. `1 =N TrueNoda. and `2 =N TrueNode. if follows from the definition of ?. that ? =--HE `?`n and Q =? Similar arguments can be used to establish closure properties (7.2-4). But property (7.5) is more subtle. Suppose p -? q and Q :? ? are both established. Then there is an eligible node y with label ?:)? and operands (`?. `?) where `i represents P and `2 represents Q. Likewise there is an eligible node I with label "??? and oparends ?`2 `1? Furth- ermore. y E1 : :g TrueNode. At some point in the computation. the following two events must bave occurred: 288 (I) The the clans 0 =g co:i?aining the node y van merged into tbe clean representing ?i? (2) The the class of =g containing the node a wan merged in?o the class r?preaenting ?l'D. Further. if at the time the node y or a (whichever was created second) was created. the operands of y were not the operanda of a in reverse order. tbe following event must have taken placet (3) Au operand field of y or z is updated as to make the operanda of 7 the a,me 55 the operands of a in reverse order. Let m be the state of the graph just after the last of the above three events occursed. Let (v1. W2) be the operanda y had in graph o+. and (w25 v1) be the operands a had in graph m. ?ither lines (28-29) of Figure 7.3 or lines (08-09) of Figure 7.4 (depending on whether the last of the three events Was (3)) must have be?'n executed to establish ?1 ?2 ?? the sane reasoning used above. ?l --H=N WI =N ?2 --H? x2. and therefore ? mE Q One final subtlety should be mentioned. When the loop in lines (08-34) of Figure 7.3 is being executed. it is possible for there to be on the reprlist being traversed a node a With lebel "->" and operends (n1. n2). and for there to be a node m with label ??>? and operanda (n2. n1) such that m --H=g Tru?Node. but to have the node m be missed by lines (27-31). This situation can arise whtn m also appears on the reprlist. and m follows a. Wben a Is being processed. m.established will not yet have been set to LL??. liowcver. vhen m is processed by the loops a.establisht,d will have bc.? at to lii1? and (n1. n2) will be added to TuDo. 0 a. r??? ut. the IttitisI LastIon ul the V--Hcodt' Intetl'retar We - 28? - insert tbe for.ula `l'D a `l's into the graph. and aesert that it is aquivalent to `I'D a' follows: EqnAssert(EqlnsertL'l'fl & `l'sJ. TrueNode) Then. if the for.ulas P and Q are established. we bsve ? =? `I'D and Q =? `I'D. so that P & ? (`I'D & `l's) =?? `I'D. and P & Q is eata- blished. Rule (A) can be japlesented in this fashion. Sl.ilarly. rule (7) could be impleIcoted by inserting all for.ulae of the for. `I'D I P in the graph. and asserting the. equivalent to `I'D. Dnt to use this approach. it `rould be necessary to insert infinitely -any nodes into the graph. Even if we could initialize the graph to contain infinitely -any nodes. it would be foolish to do so. since the altorith. could only inspect finitely -any of thee. Suppose the hashed search operation that appears st lines (07-09) of Eqinsert. lines (fl-23) of Figure 7.2. lines (23-25) of Figure 7.3. and lines (03-05) of Figure 7.4- were .odified so that when it searched for a node whose label is "I" and first operand is TrueNode. and did not find one. it would create such a node. set its reprlink to TrueNode. and set its "established" bit to liiL?. The effect would be the asee as If the infinite initialization wcre t,rformed. But it is not necessary for the hashed search to actually crests a new node. Whon the seercl, is perforeed in Eqlnsert and in Figure 7.2. only the representative of the located node is used. And when the search is perfors'ed in Figures 7.3 and 7.4. only the established bit of the located node is used. Therefore. when searching for a node n. there is no her. in returning so"e node 5'. whcre n 1. The hashed sc'arch can be o+odlfied so ihnt when sc?rching for a node whose label is "1n and whose first o?erand is T?utNude. Truetude can s..piy be returned. 290 ?le tibsI sujitIcaLion to be sade to Algoritbe Eq to to build the ollowius equivalences: `c's (7.6) `l'B ? `?`? --H=g `?`? (7.7) `I'D 1 P = `l's (7A) --HE P I `I'D `I'D (7.9) ? ? --HE q (7.10) sO's > q = `l's (7.11) --HI r --? ? `j'? . (7.12) r --H? `l's (7.13) r <--? r `l's (7.14) into the hasbed search. Falsellode is returned when searching for a node whose label is ?-" and whose operand is Tru?Nodc. TrueNode is returned when searching for a node whose label to ?&? end both of whose operands are TrueNode. end ao on. If. for example. a node a whose label is .`I" baa an operend changed to be Truet.?de by line (17) of Figure 7.2. the modified search operation at lines (22-23) must .`finde a simulated duplicate. The node r is made ineligble. and (r. TrueNode) is put on ToDo. Similar aorta of subterfuge must be performed by search operations in Figures 7.3 and 7.4. Once the equivaleoces (1.6-14) have been built into the heabed search. the distinction between formulas that are in the graph and not in the graph becomes somewhat fuzzy. So that we do not have to worry about tbe donain of =` let us redefine the relation slightly. If P and Q are fornulas. define ? :E Q to o+een that after executing: m1 :: Eqlnsert(s) 5 02 1= Eqinaert(Q) --H 291 m1 and n2 wuuid have the `aso value. Then aud ale identical rela- tions. Define a foriula P to be "established" whenever ? ?=g Trueflode. Because the equivalences (7.6-14) were not established by qntsaert. to preserve the correetness of Theorem 7.2. it is necessary that tbs set of formulas that are established by the simulation perforned by the hasbed search obeys closure properties (7.1-5). But these properties are easy to verify by inspection. - Thetun 7.3. If Toflo is empty. then for each of the automatic rules in Figure 7.1 except rule (2). if all the hypotheses of the rule are esta- blished. then the conclusion of the rule must be established as well. LagL. For each rule. the conclusion follows from simple applica- tions of closure properties (7.1-5). equivalences (7.6-14). and the follow- ing substitution property: if flR/?x1 Et Q(R/?x). end g 5 or 5 I. then P(Sllx) =? Q(Sll?1. The substitution property follows from the fact that --H--HE and are identical relations. The numbering of the following cases is consistent with the numbering of Figure 7.1. (1) Trivially o+15B =--HE 51'S. (3) Since --HP =? `1'S. by cLosure property (7.2). P `O5B. By hypothesis. P `l'B. so that `0'S = `15B. --HE (4) If P =?? `l'B. and Q =? `I'S. then by substitution. ? & ? ?=E 11'B & `1'S and by equivalence (7.7). `1'S & `I'S = `l's. Therefjre P & q :E 1I1B. (5) If ? & ? ?=? `l'B5 then by closure property (7.1). ? =? `I'S. (6) If P & ? =? `1'S. then by closure property (7.1). Q =? `I'S. (7) If? =1 `l'B. then by substitution. (P I Q) ?? (`l'B 1 Q). fly equivalence (7A). (`I'S I Q) = `15B. --HI (S) If Q = `I'S. then by substitution. (p I q) = (p I ?l'S). By 292 --H quivalenca (7.o)? (p I `I?B) =E (0) if P :E `l'B. then P v .??? and by nquiv?lenc? (7.6). `i1n --H o+o'n. Therefore ? > ? o+O?fl :? Q end by equivalence (7.11) `o'n --? q ? ?l1B. (10) if --H? --H=E `?`? then by closure property (7.2). P o+O'B. Then by `O'R --> autbiltution. ? --HE Q. and by by equivalence (7.11). ?o'n --> q =E (11) If P =E 111B and (P -> Q) ZE `1'B. then by substitution. :> Q) --H=E (`l'B -> Q). By equivalence (7.10). `I'S --> Q ?H ? Therefore q (`I's --> Q) ?? > ?? --HE --HE =E = (12) if P --? q =E `?`? and Q -> I =E `I'B. then by closure property ????? ? =E ? By equiv?lence (7.14). I <--> I --H `I'D Substitut--H ing Q for I. we obt?in I <--> q --H `11B. (13) If I q --H=E `I1B. thun ? =E q by closure property (7.4). We have I --> ? :E `I'D by equivalence (7.12). Substituting Q for I. we obtain I --> ? --HE `I1B. (14) If I <--> Q ? `I'D. then I =E Q by closure property (7.4). We have > ? --H=E `1'S by equivalence (7.12). Substituting Q for I. we obtain Q -? I = --HE (j?) p ? =E `I'S by equivalence (7.13). (16) If I q --H=E `?`B then by closure property (7.3). I "? Q. If RErlIxi `I'S. tItn R(?llx] =E `I'D by substitution. (17) If I Q ? `I'D. then by closure property (7.3). ? --H=E q. if R(Q//x) --H=E `I'D. then R(?llx1 =E `I'S by substitution. (18) I I =--HE 111B by t'quivalence (7.14). (19) If I <--> ? --H=E `l'B. then by closure property (7.4). I = Q. if R?PllxJ :E 1115 thn !([Q//xJ --HE `I'n by a,batjtution. 293 - (20) If P <:? Q :? ?l'fl. hen by cloeure property (7.?. ? ? Q. If i(qf/xJ =? .1.1. then g(Plli? =?? `I'D by au?stitution. U Suppose that for each I in (1 ... a) the instructions PsOCLAIN P. has been executed. so that ?i --H `1.5. Also suppose that is possible to --5 derive the formula Q from the formulas P1. FS? uaing the rules in Figure 7.1. except for rule (2). Then by repeated applications of Theorem 7.3. we obtain q = `I'D. --H5 Nov suppose that rule Q can be derived fron ?l? ?2 `a using all the rules in Figure 7.1. It is easy to sea that if a proof uses rule (2). it must contain a subproof of ,??fl that does not use rule (2). by induc- Lion on the size of the proof. Therefore. by Theorem 7.3. `0'S a? `I'D. so that True?Iude FalseNode. The instruction RE0UlRE P is therefore implemented by: jL Trueflode V FalatNode rhpn jL Eqlnsert(P) V TrueNode ?hen Report an error li li. .3 Transrorm?:iona The equivalences (7.6-7.14) that are built into the hashed saarcb are each instances of one of the Transformation Azious in Figures 5.1 and 5.2. Ilowever. not all the Transformation Axioms can be built into the hashed search. For example. consider the Associativity Axiom: (a o+ b) + c : a + (b + c) - 294 It wn.sld h--H njr? If th? hash?d s?-rrh cw?Id b? ?ndIfj--Hd to r?turu tiw saDe node for (a o+ b) + c as for a + (b + c). But suppose the bach function is aiven the label 5+" and pointera to two operanda. The nodea to which the operand links point each represent a class of expressions. and there ia no aimple way to tell fro. that representative node if one of those claaaea contains an expresajon whose main connective is + Krafft (57) cites a number of theoretical results that indicate that an efficient algoritba that cart deduce all consequencea of the Tranaforma- tion Axions and the rules in Figure 7.1 Is infeasible. The problem is with the substitution rules (16. 17. 19. 20). If the first hypotheses of these rules are restricted to come from some finite set. Algoritha Eq can be used to find all consequencee of the substitution rules. If hypotheses are restricted to be Transformation Axions. the normalization function described in Chapter 5 can be used to find all consequences of the substi- tution rules. The problem of efficiently finding all consequences of the Tranafornation Axioms plus some finite set has not been solved. A less ambitious goal is to obtain all consequences of the Transfor- mation Axioms and the rules in Figure 7.1. where the substitution rules are restricted to use Transformation Axioms as their first hypothesis. Deductions in this class will be referred to as being "substitution-free." The current implementation of the Proof Checker almost achieves this goa?. Here is how transformations are incorporated into the V-code inter- preter. A hash table called the Normalization Table is maintained that maps formulas onto nodes in the graph. As the routine tqlnsert adds a formula P to the graph. it normalizes all the subformulas and aubexpres- siocs of r and adds these normal forms to the Normalization Table. The routi?e ?qInsert and the routine that computes nor.al forms have a similar struct..re. Civen a formula of the fer. p(x1.xk)i EqIn--H sert produces a representative node by recuraively finding represeotatives for each Xii and then combining these representatives with p to find or create a node that represents the entire formula. Likewise. the normeli--H :ation function are computed by first finding normal forms for eac.? Xj. and then combining p with the normal forma to obtain a normal form for the entire formula. The two computations re performed in tandem. so that a representa--H Live node r and normal form n are computed for each subfornula and aubex--H pression of P, As each pair (r. n) is obtained. the noreal form n is looked up In the Normalixation Table. If n is not present. it is added to the table. so that n is mapped to r. The other possibility is that n already appears in the table. If the table maps n to r'. then XqnAsaert(r. r') is called. As a result of these extra calls to EqnAssert. the set of formulas in the graph has the following closure property: ?f P and Q are aubtormulas or aubexpressions of formulas appearing in PROGLAIN or REQUIRE instructions. and ? =T ?? then P =? Q. (7.15) The relation :T was defined in Chapter 6; ? =T Q is deficed to hold when- ever Q can be obtained by applying a series of transformstiona to P. lots that for such a d?duction to be performed automatically by the V-Code Interpreter. it is not necessary that the intermediate atepa between P and Q be subformulsa or subexpressions of formulas in the proof. but both ends of the chain must be. Let us consider the form that substitution-free deductions must take. The proof rules in Jigure 7.1. except for rule (2). are divided into - 296 - three classesa o+intr*duction.n ?elimination." end "s?bstitution" rules. Rulee (16 17. 19 20) are the substitution rule?. The introduction rulea are the ones `tith the property that every hypothesis is a subformula 0 the conclusion (note that rules that have no hypotheses are vacuously introduction rules). The elisinatiun rules arc the ones with the property that conclusion is a subformula of one of the hypotheses. Rules (10) and (12) are classified as introduction rules. and rules (13) and (14) are classifitd as elimination rules even thougl they do not. strictly speak--H ins. have the necessary subfcrmula properties. If a formula P appe?rs in a substitution-free deduction. define P to he a 5maxioue" formula uhenever: (1) 5 is the conclusion of an introduction rule and the major hypothesis of an elimination rule, or (2) 5 is the conclusion of an introduction rule. snd the major hypothesis of a substitution rule. or (3) 5 is the conclusion of a substitution rule and the major hypothesin of an elimination rule. If a rule has only one hypothesis. that hypothesis is the major hypothesis. If a rule hab two hypotheses, the major hypothesis is the second one shown in Figure 7.1. A minor hypothesis is one that is not ? ma:or hypothesis. A substitution-free deduction of 5 is dufined to be in nnoreai for," whenever, (I) The proof contains no maximum formulas. and (2) Rule (2) is used at most once. at the root of the proof tree to conclude 5. 297 Tbis definition of normal form is similar to the definition given b? Pravit: (6SJ for ?atural Deduction proofs. The difference between the two definitions is that there are no substitution rules in ?Iatural Deduction. If substitution rule. are used in a proof that is in normal form. they must be used as part of a chain of reasoning that looks like tbia elimination substitution introduction rules rules rules p Q R s where P is a leaf in the proof tree. and S is either the root of the proof tree. or the minor hypothesis of rule (3) or (11). Because Q is obtained froi P by a chain of elimination rules. Q is a aubformula of P. Likewise. since S is obtained from a by a sequence of introduction rules. 1 is a aubformula of S. (The technical problem of rules (10. 12. 13. 14). which are not strictly speaking introduction and elimination rules. is being ignored here.) If S is a minor hypothesis of rule (3) or (11). then the major hypothesis. either ? :? T or S. is on a chain of eliminations that begins at a leaf L. In that case. S must be a subfornula of L. Therefore, if a proof tree is in normal form. both ends of any chain of substitutions are aubformulaa of a leaf or?the root of the proof tree. It follows from property (7.l?) that if the instruction PIOCLAIN `i has been executed for each i in (1 ... k). and there is a subatitution-free deduction of Q from ?l r?k that is in normal form. then the instruction REQUIRE Q will s?tcceed. Therefore we are intereated in determining whether every substitution-free deduction can be put into normal form. If a prcof tree uses Rule (2). it Is a simple matter to transform it so that it usca lule (2) only once to conclude the root. The clifficult part of conv.rt?nt a r r & ? I ? r Q I I + (a) P(sllx) ? q(sllx) P(sllx) ? Q(S//x) r1II?1 & qEilIxi 1-9 + rEall Q(Sllx) /X\1 PElfix) QE?x) PE1llx? 1-9 qERI/x? 1:9 I I I PEsllx) P(Sllx) pEsllz) + pEnI/,?J ?n;e & qEsaxi PEillil & QEIlI') j:9 FEMlIx) & qEalla) I I Figure 7.5 The eli1joation of laxilul for.ulas proof ?ree to norsal fo?n is the eliajuetion of eaxinun foraulas. a? ever. scat nazilun fornulas can be elininated frou proof trees. Souc eiaa?les of bow this is done are shown in Figure 7.5. In parts (a). (b). (? I q) a (r I Q) I a 0 invariant, it ja necessary to prove that 1 + 1 > 0 follows from 1 > 0. This is a simple deduction. but it cannot be proved using normalization, because the two formulas are not equivalent. One possible mtthod for attackin? this problem is to loolt for a partial ordering ? defined over normal forms that has the property that s NLqJ implies a > 7.4 Th IrA jnat?nctinn A strji?htlorwa?d method of implessentln? Lha Nl:w instruction would 301 - involve modifyins tbe data structures discussed in sections 7.2 and 7.3. Titis approach is not used in the V-code Interpreter. Suppose we have implementationa of two operations: Assert(P). vbicb adds P to the Assertion Table, and Query(F), which determines whether P can be deduced via automatic rules from formulas in the Assertion Table. The algorithm for processing PROCLAIM and REQUIRE instructions discussed in sections 7.2 and 7.3 ia one possible implenentation of Assert and Query. For the sake of simplicity. we will assume in this section that Assert is implemented as described above. and Query is implenented by cots- suIting an oracle. Given any implementation of Assert and Query. there is a simple technique by which a V-code interpreter that will process PE? CLAIM. REQUIRE. and NEW instructions can be constructed. fl?F.n.tjnn 7.?. If 5 is a set of formulas, and I is a formula. define tile relation 5 ? P to be the result of the operation Query(P) when tic A.s?rtlun Table contains 5. The substitution notation is extended to sets of formulas and V-code instructions in the obvious fashion. n?fi',?t'?? 7.5. If a is a set of formulas. define S(v'llv) to be (P(v'llv) 1 P c 5). If I is a V-coda instruction. define 1(v'llv) to be: (1) PROCLAIM P(w'flv) if I is PROCLAIM P. (2) REQUIRE P(v'llv) if I is REQUIRE I. (3) NEW w if I is NEW wand w is distinct from v5 and (4) NEW v' if I is NEW v. The automatic rules do not depend on names of variables. That is. if v' is a variable that does not occur In 5 or 5. thcn a ? 5 if and only if S(v'I/v) ? F(v'llvl. This fact can be used to prove tba following theorem. - 302 1he?? 7.6. Sjppose the execution of a sequence of V-code instruc- tions is interrupted at 5010 point. Let S0 be the contents of the Asser- tion table. and Ij. 12. 1n be the remaining V-code instructions. Let v' be a variable that does not occur in any of the formulas in S or in any cf the V-code instructions Ii. I1n If the Assertion Table is replaced by S0(v'llv). and for each j in (1 ... n). I. is replaced by I,.Ev'llvJ. the output (that is. the sequence of successes and failures of lEQUIRE instructions) of this modified V-code sequence will be the same as the output of the original sequence. ??aL. For j in (I ... n). let S. be the contents of the Assertion Table after the execution of I.. and let t. be the contents of the asser- J 3 tion table after the execution of I?(v'llvJ. Let be Clearly 3 T0 S0(v'llv). the success or failure of REQUIRE instructions does not depend on the names of the variables chosen by NEW instructions to substitute into the Assertion Table. as long as each variable chosen does not appear in the Assertion Table or in any subsequent V-code instruction. Therefore. assume without loss of generality that if I. end I,(v??v) are NEW instruc- 3 3 tions tbe t?o instructions choose the same variable to substitute into the Asaerticn Table. and neither v nor v' is cboaen. For all j in (0 ... n). t. S.(v'llv) can be established using 3 3 induction on 3. the base case. that t0 S0(v'llv). holds by definition of t0. For the induction step. suppose tj?1 S??1(v'llv). there are three cases. depending on the what Itind of instruction I? is. If I is PIOCLAIM ?. then Sj : Sj?1 U (P) and tj = tj?1 U (P?v'llv)). We tberefore havea 303 - Tj o+ Tj?j u (PEv'llv)) o+ Sj.1Ev1IIv) u (P?v'llv)) o+ ?Sj-i U (r))Ev'll?) o+ S.(v'I/v) If Ij is REQUIRI P. then S? o+ 5j?? and Tj o+ Tj?1. Therefore Tj : Tj?1 S??1(v'llv) : S?(v1??v). If I. is n?i? v. and v and v are distinct variables. then Sj o+ S??j(v'I?v) and Tj o+ Tj.1Uv'llvl. Since v v. v' # v. and v' # v, for any P. Pv'flv)(v'llv) : P(v'llv)Ev'llv). Therefore: Tj o+ T??1(v'llv) o+ S??j(v'ilv)(v'liv) o+ Sj?iEv'llv)(v'llv) The final case is that I is a NEW v instruction. Then I.Cv'llv) is i J the instruction NEW v', so that Sj o+ Sj?1(v"llv) and Tj I T??1Ev"#v'). If the fornula P contains no occurrences of v'. then: flv'llv)(v"#v') = P(v"#v) since the set of'occurrences of v' in Pv'llv) is exactly the set of occurrences introduced by substituting v' for v. Since the variable v' vas chosen so that it did not apoear in or any of the instructions Ii 12. 1n and no NEW instructions selects v'. there can be no occurrences of v0 in Sj--Hl Therefore vs have: - 30A - Tj T ?v?llv') i--Hi S1?1Lv'llv3v?ll?) - 5j-l??"11?1 5. Since S? S??1(v"llv). there can be no occurrences 0 v in Sj. Therefore Tj : 5? The Lnduction is no', complete ?e bave established that for each j in (0 ... ni, T. S.(v'llvl. If the instruction I. is REQUIRE ?. it will succeed if and only if: 5. ? P . (7.19) But then the instruction l.(v'llv) is REQUIRE P(v?llv1. and it it will succeed if and only if: S?(v'llv) ? P(v'llv) . (7.20) Since v' cannot occur in S? or P. formulas (7.19) and (7.20) are equivalent. Therefore the two REQUIRE instructions must have the asee result. 0 The follcvina strategy can be used to implement the NEW instruction. Suppose a sequence of V-code instructions has been partially executed. and the instruction NEW v is about to be executed. Interrupt the execution at this point. select some variable v' that does not appear in the Aasertion Table or subsequent V-cod?. and replace every occurrence of v in the Asser- tion Table and subsequent V-code instructions by v'. By Theorem 7.6. this operation will not change the output of the subsequent REQUiRE instruc- tions. The abuve global rtplscemcnt operatiun will change the NL? v ln.ttu?ti.'n tu ?LW v'. TI??. in.Lturt L?n a?ia,ts a v?L jabla v" that ducs 3o? - not appear anyvbere Lu the Aaaertion Table or subsequent V-code and ?.eplsces every occurrence of vt in the Assertion Table with v". flecause. the global replacement baa just gotten rid of every occurrence of v Le the Assertion Table end V-code (and replaced each one with an occurrence of v'). the NEW inatruction ja free to chooce v" v. Then executing the NEW v' will put the Assertion Table back the `ray it was before the global replacement. The net result of the global replacement and the NEW instruction is to leave the Assertion Table unchanged. and to replace every occurrence of v in the subsequent V--Hcode with an occurrence of v'. The NEW instruction will be implemented so that the unique names selected by each NEW v instruction will be of the form v$k. where k is an integer. The first NEW v instruction will use the name v?1. the second will used v?2, and so on. For every sequence of V-code instructions containing NEW instructions there is an equivalent sequence of instructions that does not have any N? instructions. to obtain this sequence. modify each FROClAIN P or SEQUIRE P instruction as follows. For each program variable v in P. if k is the number of NEW v instructions that precedes the FROCLAIK or REQUItE instruction replace every occurrence of v in F by v$k. After all the FI? CLAIM and REQUIRE instructions are so modified. the NEW instructions are deleted. The V-code Interpreter could operate in two passes. In the first pass. the NEW instructions would be eliminated as just described. The resulting sequcuce of FROCLAIM and REQUIRE instructions would he executed in the second pnss. lluw?Ve(. tt?n ettect ut LI?eet t'ru ?aflfles can be cumbined as tc,)jews. - 306 ?or each progra. variable v. an integer ltiatenceEv? is Isintained in a table known as the 1Instance Table." Initially. Instance(v) Ia sero for every v. The instruction NEW v is jiplemented by: Instsnce(vj :--H- InatanceEvi o+ I When building representations of formulas. the pareer used by the Local Context Checker represents each program variable v by v$O. The function S?h?tInt(r) locates every program variable of the form v$j in P. 53d replaces it by v$lt. where k j + InstanceEvi. The ?aoci?i? P instruc- tion is then ixplemented by: Assert(Substlnst(F)) and 1I?UIB? P is inplenented by: Query(Substlnst(F)) In section 4? the V-code generated for the assignment statement v :-- t was presented as: ???? t PROCLAIN v where v? is the variable selected by the N:W v instruction. Let us con- sider what the implementation of hEW that updates the V-code rather them the Aaser:ion Table would do for the shove V-code instructions. Suppose the hEW v generated for the assignment statement is the j'tb NEW v instruction. At the time the above V-code is executed. the previous j-l SEW v instructions will have changed it to: D??tAIN t(v$(j-l)ivj h?A v$(j-l) PROCLAIM v$(j-l) (t?v?llvj) Just before the shove NEW instruction is executed. the execution is inter- - 307 rupted. and every occurrence cf w$(j--Hi) La the Aeeextton Table end La the aubeequent V-code La changed to v$js DONAIM t(v$(j-l)#vl NEW v$j PROCLAIM v$j (t(v'11v3) Then the NEW instruction is executed. The variable v$(j-l) is selected as v'. o+o that aubetituting v' for every occurrence of v$j in the Assertion Table cancels out the previouc aubetitution. Therefore. the effect of the PROCLAIM inetruction ehould be to add the foraula: v?j (t(v$(j-i)iv)) (7.21) to the Aeaertion Table. Intuitively. what La going on here La that the inetance of v on the left aide of foraula (7.21) astches instances of v that will spoear in subsequent PROCLAIM instructions (the 5new" value of v). whereas the instance. of v on the right side of fornule (7.21) aatcb the instances of v that are currently in the Assertion Table (the 5old5 value of v). When using the Instance Table. Instance(v) has the value j-l before the NEW v Ls executed. and Instsnce(v) han the value j after the NEW v instruction La executed. Since the function Substlnst(?) replaces v$k by v$n. where a k o+ Instance(v). the two V-coda sequences: DOMAIN t NEW v PROCLAIM v$O : endI DOMAIN t PROCLAIM vSl t(w$Ollv) NEW v each result in foraula (7.21) being added to the Assertion Table. fleceuse 308 tbe ?srser substitutes vCO for v. the eecon? sequenca is easier to ser- er?te. and therefore it is usso. Similar tecbniquee are used ?hen?an- erating tbe V-code for procedure calle. 7.5 The ? CtOSP, and ?-? In.rrucriona A straightforward implementation of OPEN and CLOS? would be fcr OPE? to push a copy of the data structure used to implement the other instruc- tions onto a stack. and for CLOSE to restore the data structure from the top of the stack. and pop the stack. The components of the data structure that would have to be saved and restored are: (1) the graph maintained by Eqinsert and EqnAsaert. which is a collec- tion ?f nodss and a hash tahle used to locate those nodes. (2) the variables TrwNode and alseNode. (3) the Normalixation Table. end (A') the Instance Table. Saving and restoring the entire date structure would be an ineffi- cient use of both ti?e and space. The following etrategy is used inetead. When an OPEN instruction is executed. a special `ssrker is pushed onto a "backup stack.? Then as changes are made to the data structure. these changes are recorded in a "backup record". and this record is puahed onto the backup stack. When a CLOSE or CLOSE-hEW instruction is executed. all the tack,?? records era popped off ti, backup tack until tha inarker is reached. As each record is popped off the stack. the indicated change is undone. When an OPEN instruction is encountered. the value of the variable ?slaeNode is put Into a backup record end pushed onto the backup stack. S'.hee1uent m?jifL?at?ona of th,s va,jnhla ne?d out be recu,dnd. ?09 All the modifications that are made to be g?sph and the variable TrueModa by Eqinsert and aqnAssert are collected into a number of "tram- sections.5 A transaction is a function f that is applied to the graph to yield a new graph. The backup record for the transaction f contains wbat- ever information is necessary to compute the inverse of f. An important design decision is how to define the transactions. There is a general approach that works no matter what?slgoritbns are used used to update the graph. Just two transactions are used: "Create" and "Modify." The Create transaction is used to allocate a new node. To invert this transaction. it is necessary to save the address and si:e of the node. The Modify transaction is used to upd?te a node. To invert this transaction. it is?Pecessary to save the address of the node and a copy of the node before it was updated. This technique was used in an early Veraion of the V-code Inter prater. hut it was abandoned because too much storage was needed for the backup stack. A better pair of transactions is "Create" and "Xerge." where Create is the operation performed by Critical fregion I in Eqinsert. and Merge is the operation performed by lines (13-32) of Figure 7.2. To invert a Create transaction, it is only necessary to bays a pointer to the cresttd nude. It Ia important to realize that when the backup record is being popped off the stack. before the inverse of ?be transaction is applied. the graph will be in whatever stats it wss in just after the transaction being inverted was performed. The Create tra?sactlon hns three steps: (1) A ncw node n is created with operend fields 5(1). a2). ... elk). (2) A bucket in the hash table Is selected. and the node n is placed in that ?ckut. - 3i0 (3) For each i in (I ... kI. a point?r to the i1th oterand field of n La put at the beginning of the container list of atii. to invert the transaction. the following steps ?ra perforiedt (I) For each i in (I ... ki. delete the firet olemont of the container list of atil. Mote that there may be duplicates among the liet sEll. at21. ... sEkI. If a(jJ appears in the list I ti?a. I ele--H Cents are deleted fro, the front of its container list. (2) the node n is removed from the bucket it is in. Since the bucket lists are doubly linked. this opecatio? is simple to perform. (3) the node n is returned to free storage. to invert a Merge. which is performed by lines (13-32) of Figure 7.2. it is it is necessary to haval (1) a pointer to the node y. (2) the value of trueNode before the Merge transaction. and (3) a list of addresses of the "eligible" and "equiv" fields that ware changed by the transaction. Civen a pointer to y. a pointer to x may be found in y.reprlink. the reprljok and reprcount fields that were nodified by the transaction can be restored by e1ecuti?g: ( y.reprlink 1- nil 1.reprcount 1 z.reprcount - y.reprcount When a Merge is executed. y.containers is appended to z.contsinere. and y.reprlist is appended to x.reprlist. It is possible to iipleo+ent these operations so that they can be easily inverted. flefore y.containera is appended to x.containers in a Merge treneac- - JLI - Figure 7.7 Appending container lists Figure 7.8 Appending reprijata' tion. the container list is traversed. so the last element in the list will be known. The append opcrLLtion is perf?rmcJ by chanaing the point?re as shown in Figure 7.7; ?he dotted lines indicste the new values of pointer fields. The field of y that formerly conteined a pointer to the head of its container list is changed to contain a pointer to the tail of that list. There is no harm in this. becsuae y is no longer a representative. and its container list is no longer used. The updated fields of x and y contain sufficient information to locate and restore all the fields that need to be changed to invert the concatenation operation. Both the head and the tail of the reprlist are stored in each representative node. The reprijat of y Is appended to the reprlist of x by changing the pointers shown as in Figure 7.8. The heed of the reprlist of y is replaced by the tail of the reprlist of x so that the concatenation ?l2 operation can be invarte?. A? ?as the case with r?o container Lists5 there is no harm in ch?nging t?i? field because 7 is no longer a representative. Once the reprijeta of : and y have been restored. the variable TrueNode is restored from the backup record. If either 1 or y is TrueNode. the reprlist of the other list is traversed. and the "eats--H blished" bits of the nodes on t?Lat list are set heck to lilli. Finally. the operation perforeed by ConLoop must be inverted. Every time ConLoop nakes a node ineligible or sets its "equiv" bit to ligft. the a?dress of the modified bit field is saved in the backup record for the transaction. When the transaction is inverted. these bit fields are re?tored. Te reconstructed ctnteiner list of y is then traversed. Every operand field to which there is a pointer on the reconstructed container list of y is changed from x hack to y. and if the node containing that operand field is eligible. the hash function is applied to the nods and the node is moved to the proper buck?t. The inveraion of the Nerge transaction is then complete. When a ow entry is added to the Normalization Table. it is also recor?ed in a backup record. When that backup record is popped off the stack. the corresponding entry in the Norejlization Table is deleted. The processing discussed so far is performed for both the CLOSE and the CLPSE-NL?U instructions. The difference between tie two instructions is their effect on the Instance Table. The CLOSE instruction must restore the Instance Table to the atatc it was in when the matching OPEN instruc- tion was performed. fl?at is. the inLervening NtW instructions must be undone. ihe specification for thc CLOSE-r?EW instruction is to unjo all the NFW instructinns perforn?d since the eatchins OPF?. p?rform a Ci,OSF and 313 thou perform the NEW imotructiono again. But there is no poing in undoiq the NEW instructions just to perform then again. But suppose. however. there is a netching pair of OPEN and CLOSE instructions coated botweon the OPEN and matching CLOSE-NEW instructions. Any NEW instructions between the OPEN and CLOSE `viii get undone when the CLOSE instruction is encoun- tered. and must be performed again when the CLOSE-ZEW instruction is encountered. Recall that a "nest" is defined as 5 region of V-code delimited by matching OPEN and CLOSE(-NEW) instructions. Define a C-nest to be a nest that is terminated by a CLOSE instruction. and an 5-nest to be a neat that it terminated by a CLOSE-NEW instruction. When an OPEN instruction is generated by the Local Context Checker it is marked to indicate whether it begins a C-nost or an N-nest. In the following discussion. the two dif- ferent kinds of OPEN instructions will be referred to as C-OPEN and ?`-OPEN instructions. Note that implicit instructions inserted by increcenting the count field, of an OPEN instruction are always N-OPEN instructions. Two stocks of lists of variable names. the C-stack and the I-stack, are maintained. The empty list is pushed onto C-stack when a C-OPEN instruction is encountered. end the ecpty list is pushed onto the Il-stack when on N-OPEN instruction is encountered. When a CLOSE or CLOSE-NEW instruction is encountered. tlac list on the tup of C-stack or N-sta?k (respectively) is processed. end the stack is popped. Because the V-coda generated for each routine begins with an OPEN instruction end ends with a CLOSE i?struction. the C-stsck is never emj'Ly wI?en pro?cssiu? the V-code for a routine. When a NEW v instruction is performed. it must be recorded so thet It can he undone when the smallest C-nest r?ntaInlna t?,p NIW 1.ns1r?c'inn is closed. The variable v is added to the list on the top of the C-stsck. and Instance(vJ is incremented by one. When a CLOSE instruction is perfursed. the NEW instructions recorded on the top of the C-ptack must be undone; for each variable v on this list. Instance(v) is decreased by one. Nowever. if the C-nest is contained in an ?-nest. the NEW instructions that are being undone must be performed again when the smallest N-nest containing the C-nest is closed. Therefore if tbe N-stsck is not empty. the list on top of the C-atack is appended to the list on top of the N-stack. In either event. the C-ateck is popped. When a CLOSE-NEW instruction is performed. the NEW instructions that have been accumulated on the top of the N-teck must be performed. For every variable v on the list on top of the N-stsck. a NEW v instruction is performed. That is. Instsnce(v) is increased by one. and v is added to the list on top of the C-atack. The N-etack is then popped. Bccause of the CLOSE-NEW instruction. the Local Context Checker is alnost freed fron the task of keeping track of w?icb variables can be modified by compound statements. Nowever. the Lcc must still keep track of which variable can be modified in a loop body so that it can insert NEW instructions for those variables at the top of the loop body. If a new V--H code instruction. NEW-OPEN. were introduced. the bookkeeping that is requirtd of the LCC could be simplified. The NEW-OPEN instruction is defined to be the reverse of the CLOSE-NEW instruction. The effect of the N?-OPEN instruction is to first perform a NEW v operation for every NEW instruction appearing in the nest begun by the NEW-OPEN. and then perform an OPEN operation. If the NEW-OPEN instruction were added. the V-code interpreter would have to make two passes through the V-coda. Tbe extra pass vould be - JI) --H required to compute the list of ?EU onerations that would have to be per- formed for each NEW-O?E?I instruction. nut the use of this instruction would simplify the LCC sufficiently to justify adding th? eatra pass. 7.6 Zha aL ? iluti. ClflSF AwL S?SL-flfl?? I'- The amount of extra storage required to implement the OPEN, CLOSE, and CLOSE-NEW instructions is O(N + T + P + w). where II the number of nodes in Uie graph. T is the number of entries in the Normalization Table. and P is the number of OPEN instructions in the V-code. and W is the number of NEW instructions in the V-codt. One backup record for a Create transaction is put on the backup stack for each node in the graph. The stack will also contain one backup record for every formula stored in tie Normalization Table. and 01'c record for every OPEN statement for which the matching CLnsE(-?r.w) has not been encountered. The backup record for a Nerge transaction contains ? pointer to a node that is made a nonrepresentative by the transaction. and to nodes for which the neligiblen bit is set to Lalli or the o+`equivn bit is set to tr.?. by the transaction. The only way a nonrepresentative node can become a representative. an ineligible node can b'come eli&ible. or the o+equiv" bit can become Lnli: is by means of a CLOSE(-NEW) instruction. Therefore. at most 0(N) space is used on the backup stack to record Nerge transactions. The total size of all the lists on the N-stack and C-stack cannot exceed the number of NEW instructions in the V-code. Let 5 be the state of the data structure when an OPEN instruction encountered. and T be the state of the data structure when the matching CLOSE(-NEW) instruction is encountered. and let N be the nest delimitad by these two instructions. Only as much time is spent by a CLOSE instruction - 3iG - `hanging t?e data structure from ?tate T to ststa 5 0S ?aa spent chanatna the data structure from atate 3 ro state T by the PROCLAIM. REQUIRE. e:id ?EW instructions that are contained in the nest N but no smaller nest, The CLOSE-NEW inetruction uses no more time than corresponding the CLOSE and NEW instructions would require. and usually uses less time. if the amount of tiTne spent on each PROCLAIM instruction were uni- form. OPEN and CLOSE would only increase the running time of the V-code interpreter by a linear factor, Unfortunately, the time spent on the PR? CLAIM instructions is not unifurm. in the absence of the OPEN and CLOSE instructions. the executicn of any one PROC?AIM instruction 10 can take a comparatively long time. but the the succeeding PROCLAIM instructions Ii 12. 1n will each be executed quickly to compensate for the time spent processing i0. The sequence of instructions: OPLI CLOSE OPIN ic CLOSE can force the ?-code interpreter to execute the lengthy Instruction 1o5 then spend just as much time undoing the effect of the instruction. end repeat the process over and over without getting the diluting effect of the instructions Ii I1n it is for this reason that path compression. a method for o+peeding up the UNION-PIND algorithm mentioned in section 6.15. is not used in the V-code interpreter. if path compression were used. extra work would be done when processing some PROCLAiM and REQUiRE instructions to allow sub- 317 --H ?equent instructions to be ercecuted faster But the beneficiaL effect of this extra vork vould last only until a cLosE(-NEw) instruction is e2Le cuted. and then extra vork vould have to be perforned to undo the path compression. Because the addition of path compression vould increase con- plexity of the already complex backup mechanisa. it is not used in the V- code Interpreter. t??AI.Trli 8 SONE FINAL InIARKS ?.i A ?i&iL?X aL Lk? Ikior ??? The notion of formula graphs prcsentcd in Chapter 2 provides a ei? pie o+odcl for quantified formulas that eliminates the problem 0 capture. Tte quantificr count representation for bound variables is an implementa- tion of this mod?l. rormulas repr?aented in this fashion arc easy to copy. instantiste. combine. and decompose. The proof of equivalence of PL/CV predicata calculus and Gcntzcn's Natural Deduction in Chipter 3 assurca us that the PL/CV predicete calculus rules are sound sod complete. The tree structure attributed to PL?CV proofs is a useful notion in its own right. it provides a clear model that can be used to visualize the concept of accessibility. and forms the basis of Proof Checker. The organization of the Proof Checker is independent of the PL?CS prograoming language. Different versions of the Proof Checker for dif- ferent programming languages could all share the same V-code interpreter. Because all the automatic rules are built into the V-code interpreter. they can be changed without modifying the LCC. Because the LCC is similar to a compiler. well-understood techniques could be used to construct it. It wo,ld be fairly simple to construct a version of the Proof Checker based on PASCAL. for example. by using a com- piler compiler such as YACC (51) to build an LCC. (Unfortunately the predicate calculus rules. which would not change appreciably from one sys- te1 to the next. have not been partitioned into their own module.) Theorem ?.l5 could be used to derive the V-code that must be generated for --H 318 - 3I? - ?eriu?s t?ntIui cullatrutta. Tie ?r.U i??etIu?L?un ?uulti be usel t* mudel various quLrks in the len?ua?n. ?r)' a. diffcrent m?Ihods of naraictor pesaing. I much Lho samo way they are ssdclcI by pr?gram vcrjficr. based on symbolic execution (56). The omnibus statement provides for multiple-exit loops of the type that can be vritt?n uain? Zehn?s construct (?3). Th stat.'m??t has a relatively simple proof rule. but is flexible enough that it can be used for many different programming tasks. The methods of jichner (40) and tianna and Waldinger (59) are well-suited for deriving programs written using the omnibus statement. One of the problems with the statement as it is presented in section 4.20 is that it does not have en?ugh syntactic redundancy. fle algorithm presented in Chapter 5 is a fore?litation of the pencil-and-paper methods often used to apply such axioxa as commutativity and distrihutivity. The slgorithm makes use of a replacement system simi- lar to that used by AFFIRM (60). but in the PLICY system. the replacement rules are applied in a controlled fashion to ensure a quadratic running time. An advantage of the AFFIRM system is that additional replacenent rules can added by the ueer. whereas the replacement rules used in the PLICV system are built into the system. But FLICY's the replacement rules are more general than those allowed by AFFIRM. Algorithm Eq. the algorithm presented in Chapter 6 for deducing equalities. is similar to the Fast Congruence Closure Aigorithm (FCCA) of flowney. Sethi. and Tarian (30). The proof of Algorithm gq is much more complicated than the proof of FCCA. for two reasons: (I) The input to FCCA is a single graph and a relation on the verticas of the graph. vhereas Algorithm Eq processes a stream of instruc- - =20 ?ione each of which add vertices 10 the greph or updates the rela- tion (2) Downey, Sethi. and Terjan?s proof ie Tiore abstract. They prove that FCCA finds the congruence closure of a relation defined over the vertices of a graph. The proof in Chapter 6 makes explicit the relationship between the graph and the represented expressions. Tht proof in Chapter 6 could serve as a guide to producing a vans- tio? cn Al?orithm Eq. Whtn this modified slgorithm determined the existence of a sequence of substitutions that transforms one expression te another. it would output one such sequence. Such an algorithe could be us?ful in an interactive program verification environment. such as the one being developed by Krefft (58) or in an LCE tact?cal (32). in which high--H level proofs are monitored for currectness by a kernel. Alg?rithn Eq ?ay be used in applications other than program verifi- catLon. It can be nad in comiltra to locate cnstm?s snbexpr?'ssiona. Downey. Setbi. and Tarian (30) eho? how FCCA can be used to test lossless- ness of joins in relationsI data bases. Al?urithm Eq is the foundation of the impletsentstion of the V-code interpreter. The V-code interpreter uses that algorithm to deduce all censequences of substitutions er? tht PL/CV automatic propositional rules. Transfor?tions can be combined with propositional reasoning. but not with complete g?'?rality. The NEW instruction and the OPEN. CLOSE. end CLOSE- ?tFW ia¶trnctjons can be ef ficiently ivnplemented using an instance table mechanism and an audit trail. 8.2 The L'ti)ir? ??f L/? Wh.?n eVaIuatin?' IL/CY as 5 p?ugr?wain? iu?i?. people often ask the 3.fl question. "vhat is the ratio of proof lines to progra.. lines in a typical PLlcv progran?" The anewer to this question varies widely with `type of. progran. In the program proofs that have been written to date. the ratio varies fron 15:1 for a complez example that manipulates arrays to 1:1 for Euclid's division sigorithi. The number of examples that have been writ--H ten is too s.all to give any isaningiul statistics. But I claim that asking about the ratio of proof lines to program lines is asking the wrong question. Consider. for example. the problen of determining whether the verticea of a graph can be coicred vith k colors so that no edge connects vertices of the sane color. Since this problem is ?IP-conplete (4J. there is interest in efficient algorithas to solve this problem. Recently. a quite simple polynomial time algoritha was discovered for a special case of this problem. the case in which the graph is planar and k ? 4. The algoritha is very short. simply: itr.njgN(`I'B)s but the shortest known proof of the correctness of this algorithu is over 500 pa?es long. The proof was prod??ced with the nid of a computer. and it is estimated that no human reader could ponsibly verify its correctness ES). The point of this somewhat frivoloua example is that some short pro- grams are going to have long proofs. and no program verification system is going to alter this fact. Therefore. a more suitable metric to use to ovaluets a program verification system is the ratio of si:. of (ha forms) proof accepted by the Proof Checker to a corresponding inform?l proof. By this metric. I reel the predicate calculus pnrt of rL,CV has bce. quite successful. It is a very natural notation in which to express proofs. P?oufs of simple programe can also be expressed fsjrly easily. ilow?ier. we have already seen one trouble spot: the array assign- nent statelent. As discussed in section 4.9. the notion of accessibility is not powerful enough to correspond to prograMmer'a intuition when rca- soning about programs that modify arrays. And of course. the set of pro--H Irems that aodL'fy arrays includes the vast majority of interesting pro- grams. Another stumbling block encountered when attempLing to tra?elste informal reasoning into PL?cv is the limited expreesibility 0 the asser- tion language. Suppose we wish to prove a program that takes the sum of the firet N elements of the array. An informal loop invariant would be "the variable 5 contains the sum of the elements A(1). A(2). ... This loop invariant is not particularly easy to express in the PL?cv 555Cr- tion language. The simplest method of expressing the notion of "the sum of the elements A(l). A(2). ... A(J-I)" in PL/CV is to write a program that calculates the sum. In fact. there is a builtin SUM function in PL?I. This particular problem would be solved if the SUM function. end axioms to reason about it. were added to rL?cv. But it is impossible to add enough primitives to the assertion language to build in evtry concept anyone might want to use to prove a program. A better solution is to make the assertion language extensible. The DEFINE statement already provides a degree of extensibil- ity. but the definitions allowed are not expressive enough. The assertion language at least ought to be extended to include finite sets. user-defined data types. and recuraive definitions. These extensiona are planned in PL?CV3 (231. 8.3 Thp Npxr Sren The PLICV rroof Checker is an i.provement over its predecessor in tbat ebbrevisLiot's and autu.atic rules an be used to reduce tbe amount of proof text required to prove a prograM. ilow much more improvenent of this type is possible? The ultimate goal of such improvements would be a program verifica- Lion system for which one need only supply a specification and a program. and the system would indicate whether the program meets the specification. Such a system would solve what I call the CSTA (Computer Science Teaching Assistant) problem. The CSTA problem ia in general undecidable. ?ven if the problem is made eaaier by adding a few comments to the program. and we as-a willing to accept systems that cannot solve every instance of CSTA. we are still faced with an extremely difficult problem in artificial intelligence. If the reader doubts the accuracy of this statement. he is referred to any graduate student who has graded programs for a sophomore level Computer Science course. To attack CSTA it is necesasry to make hypotheses. die- card them. and in general bring as much intuition and experience to bear as one can muster. Traditionally computers have excelled at task. requir- ing calculation and bookkeeping and have been rather iuept at tasks requi? ing intuition. Attempts?to advance the state of the art of program verification by pusting it ?n the direction of solving CSTA are likely to be quite diffi- cult. And intuitively I feel that approximations to CSTA are the wrong direction for program verification research to take. When I write a pro- grgu. I know how it works. A program verification system should not have to waste computer resources guessing how my program works; it should be ?esible for me to er?lain in a formal way bow t'.Le program vor?e. tucb an explana?ion ougbt 0 be useful to the human reader p? well. Y-t all Loo often. formal proofs of programs degenerate into a vast sea of aseertions in ubich program statements drift about like bite of flotsa,. Proofs of this nature. as is eloquently pointed out by DeMillo? Lipton and Ptrlis (28). are of little value to the human reader. A common complaint about complex program proofa written in PL/CV is o+How can I ?nderataid this program whtn it is obscured by all these aseertions?5 The most ambitious example to date of a PL?Cv proof is a collection of nunber theory proofs. culminating in the proof of the fundanental theorem of arithmetic (16). The proof is long (l4?7 lines). yet it is legible to a reader familiar with PL/CV because it is divided into a col- lection of small theorens. each of which can be individually digested. ?o program proofs of the magnitude of the proof of the fundamental tbeorem of arithmetic have beta attempted. Why is this? What is the difference between proofa of programs and proofs of mathematical theoreme? The proof of the fundamental theoren of arithmetic begins with some simple leemas. such as `aif a divides b and b divides c. then a divides c.0 These simple lenses are used to prove more complex lemmas. such as "the logarithm function is monotonically increasing." When the fundamental tbeoren is finally proved. these lemmas are used. Noreover. it should be possible to use these low-level lemmas to prove other high-level theorems. This hierrrchicsl organiration does not seem possible in program proofs. The state of a program it modified by a sequence of assignment statements; each assignment statement updates one word of the state. Backus (9) cal Is this thenomen?n the nvnn N??eann bottleneck." Attempts at waitiaag high-l?v I pt 5 ni pa `? a I all ha,?aaaau tlae pauaala taa 1.25 - dreiged down to the Iov level of the program. An assertion must be vrit- ten (or synthesized by the verification system) to describe the state before and after each word is pushed through the von ?eumann bottleneck. And unlike the lo?level lemmas in the proof of the fundamental tbeorem of arithmetic. these low-level assertions are of no value whatsoever when proving other programs. Procedures are supposed to be a tool used to form bigh-level pro- grams from low-level ones. but they do not seem to be general enough. Consider the following example. Let some program text containing a free variable x be denoted by S(x). and let P(z) be a predicate. Further. sup- pose P and S are related as follows: (1) after the execution of S(x). P(x) must hold. and (2) if y A x. and P(y) holds before the execution of S(x). then P(y) still holds afterwards. Tben. after tha execution of the following loop: DC I :-- L TO U BY Ii the predicate: ALL I FIXED. (L r(X)) must hold. The majority of PL/CV proofs of indexed loops have this fla- vor. And every time one of these proofs is written in PL,CV. the foll? ing theoren is reproved: fl?eqrem 8.1 If there is a program with properties (I) and (2)? there is a program whose execution will make formuls (8.1) true. Thtre is no way this thcorcm can be ab?trscted into a subrout?ne in 1L,C?. I?. .e tit u?u8?at? t?sL J(a) o+caL I'ua. a ?arsmtt?r. - 326 - teflillo. Lipton and rerlis argue that prograM proofs are worthless because they are detailed and tedious. and no one would ever want to read one. But one of the motivationa for research in program verification ia that prugrams (sane proof) are detailed and tedious. and no one would ever Vent to read one. A typical journal article describing a new slgorithm does Dot contain a liating of a complete operational program? such a list- ing would contain far too much grubby detail. Instead the author of the article attempts to convince the reader that such a progran can in princi--H pie be created. I propose that program develo?mert systems that operate in the same fas?icn be developed and studied. Rnth?r than exhibit a program in all its gory detail. and then prove that each gory detail has been correctly supplied. the user constructively argues that a program exists. using theorens like Theorem 8.1. end leaves details of actually producing a pro- Iram to the verification systen. One such system is described by Bates ?lO3. Beca?se the proof does not have to be tied to assertions about the state of the machine at each step of the program. it should be possible to write high-level proofs similar in form to proofs of mathematical th?ore.s. I am not proposing a system that will magically produce a progral from a specification; this problem is even harder than CSTA. The user of this proposed system must specify which theorems are to be used. end how they are combined to prove that an appropriate program exists. Because the proof is constructive. the program can be derived from the proof in a strictly mechanical fashion. Let us not forget that a program is in actuality a sequence of bits. Once upon a time. people programmed computers by writing out such bit - 32? --H anquences. fl?e Inventton of assemblers made it possible to program com- puters without paying any attention to the actual sequence of bits the pro--H gram comprised. Instead. programs could be viewed as sequences of inatructions. In the same manner. high lcvel languages have made it pos- sible to program computers without paying attention to individual instruc- tiona; programa are now viewed as sequences of statements. The next step in this progression ia to atop paying attention to the individual state- menta a program. and instead concentrata on the logic used to derive what those statements should be. REl?Rn?r?e. Alfred ?. Aho. John E. 6.opco?t. and Jeffrey ?. l1ll?am. __ nd An?1y,,s ? ??? Al?prirhms Addison-'?esley, l97?. (1) Pages 77-84. t2) P?ges 84-86. [3i Pages 124-139. ?4) Pages 377--H393. (51 Alfred V. Aho. R.?vi Sethi, and Jeffrey D. Uliman. Code o?tinization nd finite Church-Rosaer Theorems. I P. stin. .?dit?r. Th's;en and ????2L ?ai?? pases 89-10,. Prentice-jail. 1972. Cited by Sethi (691. (61 Alfred V. Abc and Jtffrey D. Uliman. li?a???i? IlL Csiu?ilc't fl?s.??n. Addi.oc-??sle>. 1977. (71 Attritan .\`ational Standards Institote. St.?'?1d Fr'.T?.?.. A:Sl :?3.9. 1966. (81 Tf..ni.'?I!I Ap?el and Wolfgan?, jiakcn. The Four-Color Problem. In Lynn Arrhur Stee?. editor, Nstbe,,?ricp Today pa?as 153-180. Vie- t3? 8joks. 1918. (91 John lackus. Cai Pro'?ranoine Be Liberated from the von Neumann Style? A Fume t I.?n?l Styl.' and Its A1gtbra of Prngra?s. IlL I' ACM XXI(8):613-64l, August 1918. (101 Jose L. Bates. ? lot itttect ?ttam fl???1o???L. ?IID tI,e.i,. C?.u?II UII???tsIty. An?u,t 19?9. (11) Th?cas Bishop and Richard Conway U?er1? Guide to Release 2. PLICS. Coepter Science Technical Report 17-313. Cornell University. 1977. (121 Ii. Boehm, A. Demcr?. and J. Donahue. An lnfor?.l latroduction to Rneael 1. Coo?uter t ience Tethnical lteporL 8O-,30. Cornell UnIversity. Sep- t. b'?r 1()?o (131 Robert C.irtwr iLilt and Derek C. Oppen. i(.1 1.`ire `a Ia ill II'?"Ire1a 1.ejtlc L.Qli1'tLL?? it?'otl ?L L1&? FiltLi ?u?&A At2i Lywu??liwo tw 1lit?da1?? IlL c??r??eiet L?e?'??. l97ki. iris 131-14(1. 1. .. A?t? lnL?tw?Li?a a. ?II., "e? ..? All?nine." I It 32qo+ - 141 Tat-flung Cbac. An Algoritbi for Checkin8 PLlCV Arithmetic Inferences. Computer Science Technical Report 77-326. Cornell University. October 1977. 15) Edmund Melson Clarke. Proving Correctnesa of Coroutines Without History Variables. Acta Infp?--Hprica XIII(2):l69-188. 1980. 16) Robert L. Constable The Fundamental Theorem of Arithmetic in PL/CYl. Computer Science Technical Report 80-424. Cornell University. 1980. 17) Robert L. Constable. Scott 0. Johnson. and Carl Eichenlsub? Depart- ment of Computer Science. Cornell University. Witl Ref.????c ??-?n'??1. Second edition. in preparation. October 1980. (18) Robert L. Conatable and Michael J. O'Donnell. A 1iw??atiic Lagii'. Winthrop. 1978. 19) Pates 10-46. 20) Pages 121-122. 21] Pages 234-249. 22) Robert Constable. Michael O5flonnell. Scott Johnson5 end Carl lisuser. Uscr's Cuide for the PL/CV Program Verifier. Unpublished memorandum. Department of Computer Science Corn?ll University. 1976. 23) Robert L. Constable and Daniel Ilatin. Department of Computer Sci- ence. Cornell University. ?.`po?t on fli?? ???? In preparation. October 1980. 24) Richard Coiway and Robert L. Constable. PL/CS. a Disciplind Sheet of pL?C. Computer Science Technical Report 76-273 CorneLl University. 1976. (25) Rich:ird Conway and Onvid Cries. on Introduction ?? 2tt??ii1?: ? Spi Annroach usine ??? and peers 117-1)8. Winthrop. third edition 1979. 26) St.-'j'heE' A. t?ouk. Soundness and Completeness of an Axio. System for Proaran Verifics- 21i1i on ws?ilia& VJl(1):70-90. February 1976. 27) J4'luI t' an. Willjam Irank. and 1li?hacl Maloney. String 1h?ory. Jusinal uL i.?mLuli& 1u&i& X5sIX(?)if.,'?, ?,l7 I.. .?L?. )97? - 330 - (28) Pichard A. (-Nil In. Ricb?rd J. Liplon. ind AIsn J. PerIls. ?u?&il ?tu"??.?s i I I'ruu?b ot Tl??'ttss aid ??ugt?i.s. Cc?--Hni?irin?s ? th- AC? XX11(5):27l--H28O? Nay 1919. (29) Eds?er W. Dijk?tra. ? _______ ii Prentice-all. 19)6. (30) Peter j. tiowney. Mevi Sethi. and Mobt'rt Modre Tarjan. Variations on the Comoon Subexpression Problea. To Appear in J??-?pl ? t'La Assoription LaL a????? Na?h.n?rv. (31) ?trbtrt a. F.nd?iton. & 11iLLL?J1ti??3otaa??L?i& La tnt'I? pagen 79-86. Acadmic Preis. 1912. (32) Nichael J. Cordon. Arthur J. Nilncr end Christopher P. Wadevortli. L?????? LC. I'?'?'" `???.s ? Sci?nc? ? Sprinter-Verlag. 1979. (33) Dav?? Cries. C??-?"I?' L?????? for flieitnl Comnurern John Wiley & Sons. 1971. (34) Pj?cs 49-71. 98. (35) Pagts 8?-lOl. (36) Itiges 225-229. (37) lages 377--H379. (38) 1. E. Crisvold. J. F. Poage. and 1. P. Polonsky. ILL' ?IA rn???)igi' Prentice-?sll. 1971. (39) David larel. On E?',? TI??orems. IL ___ &t21 u111t1):379-389. July 1980. (40) Eric C. It. Hehr.er `La C?nsid'r?d ad: A Contribution to the Progrs.ining Calculus. ?? Ir'.r??t?ca Xl(4):287-304. 1979. (41) C. A. It. lloare. An Axio?ati c fasis for Computer ?rogramming. 1u--???liiL??? IL ? &C1i xIl(lO)i516-581. October 1969. (42) J&?n It. Nolo. Prn?ram Correcrnpsa Proofs PhO thesis. Cornell University. 1980. (43) Shigeru Igarasshi. It. L. London. and D. C. Luckham. Autocitic Program Verification I A Logical Basis and Its 1.ple.en--H tation. iV(2):l4?-l82. 1975. 331 - (44) In: `miti?)?P1 nuaisq??? Mac??lnes Cnrp?ration. 111:' idi ?iu????? ? (?L)r Co.?iiera: LnuLtg:i 5?f,r?.?r. N'???? paP.cs M2. `.14-475. Fifth tdition. 1976. (45) Intern:.tional Bueiness Ilachines Corporation. 3L'i () Lan?.???ee Ref?rence ?4an???l Fourth edition. 1910. (4?) Inge 161. (47) Pages 205-213. (48) lage 331. (49) Pages 374-315. (50) Xatble.n Jensen and Nikisuc Wirti'. U,?,?r l'????i Lnii__ Springer-Verlag. second ?tiition 1974. (51) 5. C. Jolmeon end N. E. Leak. Language Development Tools. T1;? l1?lL ??uL?m ichL??L??1 JmLLnaL LVll(6):2l55-2l751 July-A.?ust 1918 (52) Brian W. -Kernighan and Dennis M. Ritchie. Tlie ? ??????? Prentice-llall. 1978. (53) Donald E. Knuth. Structured Programming with ? La Statements. Aili Snryeva VI(4):261-30I, December 1974. (34) __________ Volume 1: flLadaa?:tJi Donald E. Knuth. Thn ?L ? ?nmaL&Li:L Prneram?ine. pages 332-345. Addison-Wesley. 1968. (55) Donald E. Knuth. Thn Art ? ???? Proing. pages 506-549. Addison-Wceley. 1973. (56) James C. King. Symbolic Execution and Program Testing. Volume 3: and IL La: aili 1tY.?..35?-3?4. July 1976. (57) Dean 5. Krafft. The Assertion Table System for the rL/CV2 Program Verifier. Comput?r Scienca Technical Report 78-337. Cornell University. April 1978. Dean 5. Itrafft. Department of Computer Science. Cornell University. AVID: A Syatem for the interactive Developient of Verifiably Ccrract Programs. In preparation. October 1980. (5B)