home *** CD-ROM | disk | FTP | other *** search
/ Amiga ISO Collection / AmigaUtilCD2.iso / Programming / Misc / M2V11-1.LHA / modula / ansi-c / SetJmp.def < prev    next >
Encoding:
Text File  |  1993-11-19  |  2.1 KB  |  68 lines

  1. DEFINITION FOR C MODULE SetJmp ;
  2.  
  3. (* Set jump allows you to jump out of a deeply nested procedures call chain  *)
  4. (* Although not as elegant as an exception handling mechanism it is capable  *)
  5. (* of giving you the same functionality. longjump can be considered as         *)
  6. (* raising the exception and setjmp can be considered as catching it.         *)
  7.  
  8. TYPE
  9.   JumpBuffer    = ARRAY [0..15] OF LONGINT ;
  10.   JumpBufferPtr = POINTER TO JumpBuffer ;
  11.  
  12. PROCEDURE setjmp ( VAR jb : JumpBuffer ) : LONGINT ;
  13. (* loads jb with the current register state. setjmp always returns 0 *)
  14.  
  15. PROCEDURE longjmp( VAR jb : JumpBuffer ; int : LONGINT ) ;
  16. (* returns just after the setjump that loaded JumpBuffer, as if setjmp had    *)
  17. (* just returned int.                                   *)
  18.  
  19. END SetJmp.
  20.  
  21. (* The compiler allocates local variables into registers, therefore if          *)
  22. (*  you are using SetJmp, dont modify any locals between setjmp and the       *)
  23. (* subsequent procedure call or otherwise use the (* @O *) comment to stop    *)
  24. (* the compiler from allocating registers.                      *)
  25. (*                                          *)
  26. (* (* @O *)                                      *)
  27. (* PROCEDURE foo(..);(* foo will not allocate any registers to local vars  *) *)
  28. (*  VAR ...         (* & parameters therefore its always safe to call     *) *)
  29. (*             (*  setjmp from inside it.                   *) *)
  30.  
  31. (* Heres an example of how to use the functions in SetJmp
  32.  
  33. MODULE testJmp ;
  34.  
  35. IMPORT SetJmp , StdIO ;
  36.  
  37. VAR
  38.   buff : SetJmp.JumpBuffer ;
  39.  
  40. PROCEDURE b( x : LONGINT ) ;
  41. BEGIN
  42.   StdIO.printf("%d\n",x);
  43.   IF x = 0 THEN
  44.     SetJmp.longjmp( buff , 10 ) ;
  45.     (* This call jumps directly back to the CASE statement in a( )          *)
  46.     (* The CASE index will be the second parameter of longjmp in this case 10 *)
  47.   END;
  48.   b(x-1)
  49. END b ;
  50.  
  51. PROCEDURE a( ) ;
  52.   VAR foo : LONGINT ;
  53. BEGIN
  54.   foo := 1 ;
  55.   CASE SetJmp.setjmp( buff ) OF
  56.   |0 : (* If we modified foo here then its value will be undefined when we  *)
  57.        (* we lonjmp. Using the (* @O *) comment does not cause            *)
  58.        (* this problem as foo definitely WONT be in a register.             *)
  59.        b(10) ;
  60.   |10: StdIO.puts("back from b()")
  61.   END ;
  62. END a ;
  63.  
  64. BEGIN a( ) ;
  65. END testJmp.
  66.  
  67. *)
  68.