protect evaluates a protected expression and guarantees that its cleanup body runs whenever control leaves the protected expression.
Syntax
(protect ⟨protected-expr⟩
⟨cleanup-body-element⟩*
⟨cleanup-expr⟩)
Semantics
⟨protected-expr⟩is evaluated first, followed by the cleanup body(⟨cleanup-body-element⟩* ⟨cleanup-expr⟩).- The cleanup body runs both when
⟨protected-expr⟩returns normally and when control exits⟨protected-expr⟩non-locally viathrow,return,break,continue, orresume-to. - When
⟨protected-expr⟩returns normally, theprotectexpression returns the value(s) of⟨protected-expr⟩(which may be a single value,Void, or multiple values). - The cleanup body is an implicit
progn(supporting multiple expressions and shorthandletbindings), and all values produced by the cleanup body are discarded. (As elsewhere in Coalton, discarding aResultemits a compiler warning unless explicitly bound with(let _ = ...).) - If a cleanup form throws an exception or performs a non-local exit, that new control transfer supersedes the original exit.
- Neither
⟨protected-expr⟩nor the cleanup body is in tail position.
Examples
(coalton-toplevel
(declare with-temp-counter ((coalton/cell:Cell UFix) * (Void -> :a) -> :a))
(define (with-temp-counter active-count action)
(coalton/cell:increment! active-count)
(protect (action)
(coalton/cell:decrement! active-count))))
Other Notes
protectcompiles directly to Common Lispcl:unwind-protect.- When a
handlebranch runs at athrowsite inside⟨protected-expr⟩, the cleanup forms ofprotecthave not yet run while thehandlebranch is executing; they run as soon as thehandlebranch either returns normally (unwinding tohandle) or invokesresume-toto aresumableoutside theprotect. - See
catch,handle, andthrow.