12.07.2015 Views

Exception Handling in FORTH - Forth, Inc.

Exception Handling in FORTH - Forth, Inc.

Exception Handling in FORTH - Forth, Inc.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Exception</strong> <strong>Handl<strong>in</strong>g</strong> <strong>in</strong> <strong>FORTH</strong>Clifton Guy and Terry RayburnBremson Data Systems, <strong>Inc</strong>.1169I w: 85th St.Lenexa, KS 66214Abstract<strong>FORTH</strong> relies on the discipl<strong>in</strong>e of the progranuner to provide the benefits of structuredlanguages: readability, predictability and modularity. A difficult class of problem for structuredsoftware is the handl<strong>in</strong>g ofexceptions to the control flow, <strong>in</strong>clud<strong>in</strong>g errors. Even <strong>in</strong> properly designedsoftware, a low level module may detect a condition whose proper resolution resides on a higher level.We describe a general implementation for exception handl<strong>in</strong>g <strong>in</strong> <strong>FORTH</strong> that hides the <strong>in</strong>herentstructure violation with<strong>in</strong> a readable control structure which allows return from any nest<strong>in</strong>g depth of<strong>FORTH</strong> words and control structures. Further, this structure is itself nestable to any arbitrary depth.<strong>Exception</strong> <strong>Handl<strong>in</strong>g</strong> <strong>in</strong> Structured ProgramsThe goals of structured programm<strong>in</strong>g are to improve the clarity of presentation of the controlflow and to standardize style. A limited number of control structures have been described as theprimitives <strong>in</strong> whose terms all algorithms can be expressed. These primitives are the sequence, theDO-WH HE and the I F-THEN-E LSE structures. Various camps now support the <strong>in</strong>clusion of theCASE construct, the BEGIN-UNTI L, the BREAK and the LEAVE <strong>in</strong> the legitimate set [SH083]. Allconsistently plead that the use of GOTO be m<strong>in</strong>imized.A common problem for structured programmers is the handl<strong>in</strong>g of control flow exceptions suchas error conditions. In a well-structured program, there may be several layers of code between theuser and the lowest level utility that may detect an error.A typical approach is to pass flags back from the layer <strong>in</strong> which an error is detected. Each layer<strong>in</strong> the path looks at the flag and decides whether to exit or cont<strong>in</strong>ue. A more sophisticated approachis to use a vectored abort, register<strong>in</strong>g an error handler before the descent <strong>in</strong>to the lower layers. Uponerror detection, the code may execute an ABORT which will pass control to the registered handler.Although the former technique is technically structured, neither approach meets the goals ofstructured programm<strong>in</strong>g. We believe an exception handl<strong>in</strong>g construct should preserve the clarity ofthe control flow while provid<strong>in</strong>g a direct path from exception detection to the handler. Our goal isto present such a construct that can be added to a <strong>FORTH</strong> system without modify<strong>in</strong>g the kernel.Theory ofthe SolutionThe solution to the problem of exception handl<strong>in</strong>g <strong>in</strong> a structured program ultimately <strong>in</strong>volvesunw<strong>in</strong>d<strong>in</strong>g the thread of execution as represented by the return stack. When an exception is raised,the mechanism could pop the return stack by some preset number of levels or unw<strong>in</strong>d through theexits of the <strong>in</strong>terven<strong>in</strong>g words. In either case the return stack po<strong>in</strong>ter is restored to the level of theexception handler. Therefore, it is possible to build a general denester by sav<strong>in</strong>g and restor<strong>in</strong>g thereturn stack po<strong>in</strong>ter. S<strong>in</strong>ce the parameter stack has been used by <strong>in</strong>terven<strong>in</strong>g words, its po<strong>in</strong>tershould also be restored. This is essentially sav<strong>in</strong>g and restor<strong>in</strong>g the context of the upper level.The most useful version of the solution would be molded <strong>in</strong>to the form of common controlstructures with which the programmer is already familiar. This new control structure would conta<strong>in</strong>Journal of <strong>Forth</strong> Application and Research Volume 3, Number 4J7


38 The Journal of <strong>Forth</strong> Application and Research Volume 3 Number 4a clause for handl<strong>in</strong>g the exception which we call the except clause. As execution beg<strong>in</strong>s its descentto lower layers, we wish to save a projected "future context" that will exist if an exception occurs.We must save the <strong>FORTH</strong> <strong>in</strong>terpreter po<strong>in</strong>ter modified to po<strong>in</strong>t to the except clause, which we callthe exception address. Exist<strong>in</strong>g control structures such as I F work <strong>in</strong> just this way.The future context may be saved on a stack to allow nest<strong>in</strong>g of the structure. We call this stackthe exceptions stack. With this implementation, exception handlers themselves may generateexceptions. Three items are saved on the stack <strong>in</strong> our implementation: the parameter stack po<strong>in</strong>ter,the return stack po<strong>in</strong>ter and the exception address. Other context items important to the applicationmay also need to be saved. These would <strong>in</strong>clude a str<strong>in</strong>g stack po<strong>in</strong>ter or user stack po<strong>in</strong>ter, ifimplemented.ALERT-EXCEPT-RESUMEThe proposed control structure is:ALERT (ALERT cLause> EXCEPT (EXCEPT cLause> RESUMEESCAPEThe exception control structure looks like a familiar I F- ELSE- THE N or BEG I N- WHILE­REP EAT. Like the BEG I N- WHILE- REP EAT, all three elements are required for the structure.ALERT registers the EXCEPT clause as the exception handler. Ifan error is detected, ESCAPE raisesthe exception which passes control to the handler. If ESCAPE is not executed, the ALERT clause willcomplete normally and execution will cont<strong>in</strong>ue follow<strong>in</strong>g RESUME.ImplementationOn screens I and 2 we present an implementation of ALE RT- EXCEPT- RES UME forpoly<strong>FORTH</strong> II on a Digital Equipment Corp. PDP-II. The <strong>FORTH</strong> <strong>in</strong>terpreter po<strong>in</strong>ter is kept <strong>in</strong>a register named I. S is the parameter stack po<strong>in</strong>ter and R is the return stack po<strong>in</strong>ter. NEXTassembles the <strong>in</strong>ner <strong>in</strong>terpreter as two <strong>in</strong>structions. The standard word END-CODE is not used toterm<strong>in</strong>ate a CODE def<strong>in</strong>ition. Unlike the FlG model, poly<strong>FORTH</strong> does not <strong>in</strong>sure that conditionalsare paired.0000 PREALERT0002 (ALERT>0004 0026 (exception address)0006 alert clause0020 POP0022 Branch to 00500026 except clause0050 execution cont<strong>in</strong>uesFigure 1. ALERT-EXCEPT-RESUME Memory Model


40 The Journal of <strong>Forth</strong> Application and Research Volume 3 Number 4261224102282061841614---2o2426lengthpo<strong>in</strong>terEXCEPTIONS STACK before (ALERT)26 paramo stk. ptr. 1224 return stk. ptr. 1022 exception addr. 820181614 L~EXCEPTIONS STACK after (ALERT)2420lengthpo<strong>in</strong>ter26paramo stk. ptr.1224return stk. ptr.1022exception addr.82061841614'-2o2426lengthpo<strong>in</strong>terEXCEPTIONS STACK after ESCAPE or POPFigure 2. <strong>Exception</strong>s Stack Diagrams


<strong>Exception</strong> <strong>Handl<strong>in</strong>g</strong> <strong>in</strong> <strong>Forth</strong> 41We have referred to our process as exception handl<strong>in</strong>g and have given an example of the specialcase of handl<strong>in</strong>g errors. A colleague has suggested that the mechanism could be used to implementa forgiv<strong>in</strong>g user <strong>in</strong>terface. Such an <strong>in</strong>terface would allow the user to escape from the current modeby press<strong>in</strong>g a particular key, perhaps the ASCII "escape". An ESCAPE would return control to somepredictable level no matter how convoluted a path the user had taken to his current predicament.Comparison to Other SolutionsOther solutions to the general problem ofexception handl<strong>in</strong>g have been described <strong>in</strong> the <strong>FORTH</strong>literature. Joosten [JO082] and Nieuwenhuijzen [NIE82] describe a modification to ABORT thatcauses it to search the compiled code of each word <strong>in</strong> the call<strong>in</strong>g sequence look<strong>in</strong>g for an errorrecovery marker. When the marker is found, ABORT causes execution to resume at the follow<strong>in</strong>glocation. This marker is the compilation address of a synonym for EXIT. So, if the marker isreached dur<strong>in</strong>g normal execution, the result is an exit. QU I T has been modified to conta<strong>in</strong> an errorhandler of this type. If no <strong>in</strong>terven<strong>in</strong>g handler is found, the handler <strong>in</strong> QU I T will be found andexecuted.This solution has several features to commend it. It is easy to use and highly readable. Putt<strong>in</strong>gan error handler <strong>in</strong>to QUIT is a good idea. ALERT-EXCEPT-RESUME could make use of this ideato <strong>in</strong>sure that a handler is always registered. One elegant characteristic of this solution is that it doesnot require explicit registration of error handlers. However, unless ABORT is very smart, themechanism is subject to failure. One problem area is that data such as loop <strong>in</strong>dices kept on the returnstack are <strong>in</strong>dist<strong>in</strong>guishable from return addresses. This can cause a search for an error recoverymarker <strong>in</strong> an area of memory unrelated to the thread ofexecution. The second problem area is thatdata <strong>in</strong> colon def<strong>in</strong>itions other than compilation addresses may be mistaken for the error recoverymarker. Examples of such data are literals, str<strong>in</strong>gs, branch offsets and whatever <strong>in</strong>-l<strong>in</strong>e extensionsthe user may add. This last item makes it hard to provide a general solution by mak<strong>in</strong>g ABORTsmart. Joosten reports that these problems do not appear to matter <strong>in</strong> practice.Schleisiek [SCH83] provides a def<strong>in</strong><strong>in</strong>g word for writ<strong>in</strong>g named exception handlers which whenexecuted will return control to a higher level. Register<strong>in</strong>g a named handler has two effects. It enablesthe execution of the handler if the exception occurs and it marles the place where execution willresume afterwards. This solution is portable because it is implemented entirely <strong>in</strong> high level <strong>FORTH</strong>.Hav<strong>in</strong>g a named handler for a specific exception is an attractive idea. In our solution, a specificexception condition is not bound to a specific handler. Ifthe programmer were to <strong>in</strong>sert an ALE RT­EXCEPT-RESUME block between the layers of an ESCAPE and an exist<strong>in</strong>g exception handl<strong>in</strong>gblock, that new block does not handle the newly def<strong>in</strong>ed exceptions alone. Instead, the exist<strong>in</strong>g lowerlevel exceptions will pass control to the new EXCEPT clause. These must be detected and sent on.Despite the benefits of tightly coupl<strong>in</strong>g the exception and its handler, we believe that the ultimatedisadvantage of Schleisiek's syntax is that it places all of the responsibility for an understandablestructure on the application programmer when this could be easily assumed by the underly<strong>in</strong>gmechanism.Schleisiek puts the exception <strong>in</strong>formation <strong>in</strong> l<strong>in</strong>ked return stack frames. We agree that "thereturn stack is the proper place to store <strong>in</strong>formation which has a limited lifetime correspond<strong>in</strong>g toa certa<strong>in</strong> execution level" [SCH84]. A better implementation of ALERT-EXCEPT-RESUME woulduse return stack frames <strong>in</strong>stead of the exceptions stack. The separate data structure is unnecessary.Colburn [COL83] describes an approach to error handl<strong>in</strong>g that vectors the behavior of ABORT"via a frame on the return stack. In a way similar to ALERT-EXCEPT-RESUME, his approach codesand registers the exception handler <strong>in</strong>-l<strong>in</strong>e. An ABORT" occur<strong>in</strong>g with<strong>in</strong> the scope of this def<strong>in</strong>itionwill branch to the registered handler. Execution resumes follow<strong>in</strong>g the exception handler, which isco<strong>in</strong>cidently the code that caused the exception to occur <strong>in</strong> the first place. This provides an automaticretry mechanism.'


42 The Journal of <strong>Forth</strong> Application and Research Volume 3 Number 4While we restricted ourselves to a solution that could be layered onto an exist<strong>in</strong>g <strong>FORTH</strong>,Colburn modified ABORT" to his benefit. First, ABORT" raises the exception, perform<strong>in</strong>g thefunction of our ESCAPE without add<strong>in</strong>g a new word. Second, ABORT" behaves as usual if nohandler is registered. We like the idea of hav<strong>in</strong>g a default error handl<strong>in</strong>g behavior and hav<strong>in</strong>g itcoded <strong>in</strong>-l<strong>in</strong>e. This allows the word detect<strong>in</strong>g the error condition to be written and tested withoutany external scaffold<strong>in</strong>g.The problem with Colburn's approach is that it results <strong>in</strong> code that is unnecessarily difficult toread because it does not resemble any familiar structure. The <strong>in</strong>herent retry mechanism seems at firsta benefit that would compensate for the loss of readability. However, the complexity that seems tobe saved must be <strong>in</strong>serted <strong>in</strong> order to make the mechanism stop retry<strong>in</strong>g. Plac<strong>in</strong>g an ALE RT­EXCEPT-RESUME with<strong>in</strong> a BEGIN-UNTI L block provides an explicit retry loop that is easier tounderstand.A F<strong>in</strong>al WordWe have described a general solution to the problem of exception handl<strong>in</strong>g <strong>in</strong> <strong>FORTH</strong>. Itdef<strong>in</strong>es the words ALERT, EXCEPT, RESUME and ESCAPE. We have also compared our solutionto several others which have been described <strong>in</strong> the literature. We like the simple syntax describedby Joosten and Nieuwenhuijzen but are concerned by the frailties of the approach. There are alsosome attractive aspects of the solutions described by Schleisiek and Colburn but both suffer froma lack of readability. S<strong>in</strong>ce ALERT-EXCEPT-RESUME follows the form ofother control structures,it can be easily-comb<strong>in</strong>ed with them to provide any general control flow and exception behavior. Weregret that the implementation we present does not use the return stack frame model for stor<strong>in</strong>gexception <strong>in</strong>formation. However, modify<strong>in</strong>g the code we have given to use the return stack shouldnot be too difficult. We hope that the reader will f<strong>in</strong>d this structure a useful extention to his <strong>FORTH</strong>system.References[COL83][J0082][NIE82][SCH83][SCH84][SH083]Don Colburn, "User Specified Error Recovery <strong>in</strong> <strong>FORTH</strong>," 1983 FORMLConference Proceed<strong>in</strong>gs.Rieks Joosten, ''Techniques Work<strong>in</strong>g Group (report)," 1982 Rochester <strong>FORTH</strong>Conference Proceed<strong>in</strong>gs.Hans Nieuwenhuijzen, "The Importance of the Rout<strong>in</strong>e QUIT," 1982 Rochester<strong>FORTH</strong> Conference Proceed<strong>in</strong>gs.Klaus Schleisiek, "Error Trapp<strong>in</strong>g: A Mechanism for Resum<strong>in</strong>g Execution at aHigher Level," 1983 FORML Conference Proceed<strong>in</strong>gs.Klaus Schleisiek, "Error Trapp<strong>in</strong>g and Local Variables," 1984 FORML ConferenceProceed<strong>in</strong>gs.Mart<strong>in</strong> L. Shooman, "Software Eng<strong>in</strong>eer<strong>in</strong>g Design/Reliability/Management,"McGraw-Hill, <strong>Inc</strong>., 1983.Manuscript received October 1985.Terry Rayburn received the BS <strong>in</strong> Physics from Texas A&l University <strong>in</strong> 1971 and the MSEEfrom the University of Missouri <strong>in</strong> 1983. He has used <strong>FORTH</strong> as a consultant <strong>in</strong> a variety ofapplications and is currently a Software Eng<strong>in</strong>eer with Bremson Data Systems <strong>in</strong> Lenexa, Kansas.Clifton Guy received the BS <strong>in</strong> Computer Eng<strong>in</strong>eer<strong>in</strong>g from Iowa State University <strong>in</strong> 1984. ASystems Design Eng<strong>in</strong>eer at Bremson Data Systems, his <strong>in</strong>terests <strong>in</strong>clude software eng<strong>in</strong>eer<strong>in</strong>g, datastructures, and communications.


<strong>Exception</strong> <strong>Handl<strong>in</strong>g</strong> <strong>in</strong> <strong>Forth</strong> 43Glossary(A LERT> is the execution-time code of ALE RT. It pushes three values onto the exceptions stack.These are the parameter stack po<strong>in</strong>ter, the return stack po<strong>in</strong>ter and the "future" <strong>FORTH</strong><strong>in</strong>struction po<strong>in</strong>ter.ALERT is an IMMEDIATE word which beg<strong>in</strong>s an exception handl<strong>in</strong>g control structure term<strong>in</strong>atedby RESUME. Besides compil<strong>in</strong>g PREALERT and (ALERT>, it has effects similar to IF. Itleaves an empty cell <strong>in</strong> the dictionary to be filled <strong>in</strong> by EXCEPT which will conta<strong>in</strong> the addressof the EXCEPT clause.ESCAPE restores the parameter and return stack po<strong>in</strong>ters, and resets the <strong>in</strong>terpreter po<strong>in</strong>ter (I) topo<strong>in</strong>t to the EX CEPT clause.EXCEPT is an IMMED I ATE word which compiles POP <strong>in</strong> order to pop the exceptions stack if theALE RT clause completes normally. It uses ELSE which fills <strong>in</strong> the empty cell left by ALE RTand leaves an empty cell to be filled <strong>in</strong> by RESUME.EXCEPTIONS is a data structure that conta<strong>in</strong>s a stack po<strong>in</strong>ter at EXCEPTIONS+O, the stack depthat EXCEPTIONS+2, and a stack at EXCEPTIONS+4. This stack is used to hold <strong>in</strong>formationneeded at the time ESC APE is executed. The stack allows nest<strong>in</strong>g of ALE RT- EXCEPT­RESUME blocks up to 4 levels deep (3 words per level is 24 bytes).POP pops three items off the exceptions stack.PRE ALE RT verifies there is enough room on the exceptions stack for (A LERT> to push its threevalues.RESUME is an IMMEDIATE word which is a synonym for THEN. It fills <strong>in</strong> the empty cell left byEX CEPT and marks the end of the control structure.


44 The Journal of <strong>Forth</strong> Application and Research Volume 3 Number 4SCREEN 1<strong>Exception</strong> handl<strong>in</strong>g by Clifton Guy and Terry Rayburn is <strong>in</strong>the public doma<strong>in</strong> and may be reproduced with this notice)VARIABLE EXCEPTIONS 24 DUP, ALLOT HERE EXCEPTIONS !PREALERTEXCEPTIONS @ EXCEPTIONS 10 +EXCEPTIONS DUP 2+ @ + 41 ABORT" <strong>Exception</strong>s stackTHEN< IF+ EXCEPTIONSoverf low"CODE(ALERT)o EXCEPTIONS MOVo -) I )+ MOVNEXTo -) S MOVEXCEPTIONS 0 MOV0 -) R MOVSCREEN 2(ESCAPE ALERT EXCEPT RESUME)CODE ESCAPEo EXCEPTIONSS 0 )+ MOVNEXTMOV I 0 )+ MOVEXCEPTIONS 0 MOVR 0 )+ MOVALERT COMPILE PREALERT COMPILE (ALERT) HERE 0 ,IMMEDIATEPOP 6 EXCEPTIONS +! ;EXCEPT COMPILE POP [COMPILE] ELSE IMMEDIATERESUME [COMPILE] THEN; IMMEDIATESCREEN 3( ALERT-EXCEPT-RESUME example)VARIABLE RSTATUS VARIABLE WSTATUSREAD ( read block ) RSTATUS @ NOT IF ESCAPE THENWRITE ( write block) WSTATUS @ NOT IF ESCAPE THENCOPIES ( n - ) o DO READ ( process ) WRITE LOOPexample ALERT 3 COPIES CR II Copy successful."EXCEPT CR ." Error <strong>in</strong> COPY."RESUME ." Done."EXAMPLE 2 0 DO 2 0 DOI RSTATUS! J WSTATUSLOOP LOOP; EXAMPLEexample

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!