# 6.8 Cleanups with Defer

> `Defer` notes down something to do when leaving the current block, whatever happens: closing a file, switching off a light, leaving things as they were.

Web page: https://pseudolearn.app/en/spec/control/diferir

> **In one sentence**
>
> `Defer` notes down something to do when leaving the current block, whatever happens: closing a file, switching off a light, leaving things as they were.

## 6.8.1 How to write it

```pseudolearn
Defer
  «instrucciones»
EndDefer
```

> **Parts**
>
> - `Defer` opens the cleanup.
> - «statements» is what will be done on leaving. It does not run now.
> - `EndDefer` closes the cleanup.

## 6.8.2 How it works

When execution reaches `Defer`, the body **does not run**: it is pushed onto a stack. When leaving the block that holds the `Defer` —through the end, `Exit`, `Return` or a propagated error— the noted cleanups run, **from the last to the first**.

### Program: The last thing opened is the first one closed

```pseudolearn
Algorithm Ordenado
  Write "abro la puerta";
  Defer
    Write "cierro la puerta";
  EndDefer
  Write "enciendo la luz";
  Defer
    Write "apago la luz";
  EndDefer
  Write "leo un rato";
EndAlgorithm
```

**Output**

```text
abro la puerta
enciendo la luz
leo un rato
apago la luz
cierro la puerta
```

*The program finishes normally.*

**Figure 6.8-1: The cleanup stack**

A stack: first cierro la puerta goes in and apago la luz on top. On leaving, apago la luz runs first and then cierro la puerta.

Cleanups are stacked when reached and run in reverse when leaving the block.

1. Step 1: The first `Defer` is reached: "cierro la puerta" goes onto the stack.
2. Step 2: The second one is reached: "apago la luz" sits on top.
3. Step 3: When the block ends the top one comes off first, "apago la luz", and then "cierro la puerta".

Only what is **reached** counts: a `Defer` in a branch not taken notes nothing. Inside a loop, every round notes its own cleanups and runs them when that round ends:

### Program: Cleanups per round

```pseudolearn
Algorithm Vueltas
  For i <- 1 To 3 Do
    Defer
      Write "fin de la vuelta ", i;
    EndDefer
    If i = 2 Then
      Break;
    EndIf
    Write "vuelta ", i;
  EndFor
EndAlgorithm
```

**Output**

```text
vuelta 1
fin de la vuelta 1
fin de la vuelta 2
```

*The program finishes normally.*

> **Limit**
>
> - Inside a cleanup, `Return`, `Exit`, `Propagate` and another `Defer` are not allowed.
> - If the program fails with a trap, it ends at once **without** running the pending cleanups.
> - `Return` computes its result before the cleanups: a cleanup cannot hide the value or the error being returned.

> **Common mistakes**
>
> ### Program: Exit inside a cleanup
>
> ```pseudolearn
> Algorithm LimpiezaMala
>   For i <- 1 To 2 Do
>     Defer
>       Break;
>     EndDefer
>   EndFor
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `controlTransferInsideCleanup` (error, 4:7): A cleanup cannot transfer control or register another cleanup
>
> *The program finishes with an error.*

> **Under the hood**
>
> The engine copies the body of every cleanup into every exit of the block, in reverse order. That is why the intermediate representation of `puerta-luz` has the two final writes after "leo un rato".
>
> **Intermediate representation**
>
> ```text
> module Ordenado en
> func suspendible @main() -> unit {
> b0() mass 5:
>   stmt.enter @2:3-2:25
>   %0 = const.str "abro la puerta" @2:9-2:25
>   out.write %0, newline @2:3-2:25
>   stmt.exit @2:3-2:25
>   stmt.enter @6:3-6:26
>   %1 = const.str "enciendo la luz" @6:9-6:26
>   out.write %1, newline @6:3-6:26
>   stmt.exit @6:3-6:26
>   stmt.enter @10:3-10:22
>   %2 = const.str "leo un rato" @10:9-10:22
>   out.write %2, newline @10:3-10:22
>   stmt.exit @10:3-10:22
>   stmt.enter @8:5-8:25
>   %3 = const.str "apago la luz" @8:11-8:25
>   out.write %3, newline @8:5-8:25
>   stmt.exit @8:5-8:25
>   stmt.enter @4:5-4:29
>   %4 = const.str "cierro la puerta" @4:11-4:29
>   out.write %4, newline @4:5-4:29
>   stmt.exit @4:5-4:29
>   return @11:1-11:13
> }
> ```

> **Note**
>
> A stack of plates helps: the last one put down is the first one taken off. Predict the output of `vueltas-diferir` before running it: round 2 cleans up even though it leaves with `Exit`.

**In short**
- `Defer` notes a cleanup for when the block is left.
- Cleanups run in the reverse of the order they were reached.
- They run when leaving through the end, `Exit`, `Return` or a propagated error.
- A trap ends the program without running them.

**See also**
- [6.7 Leaving a loop](https://pseudolearn.app/en/spec/control/salir.md)
- [12.7 Files and folders](https://pseudolearn.app/en/spec/biblioteca/archivos.md)
- [7.5 Returning a value with Return](https://pseudolearn.app/en/spec/subprogramas/retornar.md)
