facebook / facebook/hhvm

defer statement

Open
#8,604 2 comments 0 reactions 0 assignees View on GitHub
feature request hack
Dominant language
C++
Stars
18.7k
Forks
3.1k
Avg merge
1h 47m
Merged PRs (30d)
2

Description

# Defer

A defer statement pushes a function call onto a list. The list of saved calls is executed exactly once after the surrounding function returns.

Defer is commonly used to simplify functions that perform various clean-up actions.

```hack
use namespace HH\Lib\Experimental\{File, IO};

async function copy(
IO\ReadHandle $from, IO\WriteHandle $to, int $bytes = 8046
): Awaitable {}

async function copy_file(
string $from, string $to, int $bytes = 8046
): Awaitable {
$from = File\open_read_nd($from);
defer await $from->closyAsync();
$to = File\open_write_nd($to);
defer await $to->closeAsync();

await copy($from, $to, $bytes);
}
```

The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

```hack
function world(): string {
print 'hello';

return Str\format('world.%s', "\n");
}

<<__EntryPoint>>
async function main(): Awaitable {
// - function call is not executed until
// | the the surrounding function returns.
// | - arguments are evaluated immediately
// | |
// v v
defer print(world());

print ', ';
}
```

Output :

```console
$ hhvm defer.hack
hello, world.
```

see : https://play.golang.org/p/hvrio81Dn4h

# Stacking defers

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

```hack
<<__EntryPoint>>
async function main(): Awaitable {
print(Str\format('counting%s', "\n"));

for ($i := 0; $i < 10; $i++) {
defer print(Str\format('%d%s', $i, "\n"));
}

print(Str\format('done%s', "\n"));
}
```

output :
```console
$ hhvm defer_stack.hack
counting
done
9
8
7
6
5
4
3
2
1
0
```

Contributor guide

Open the contributing guide

Research direction

The issue defines a proposed Hack defer statement through examples, including argument evaluation, execution on return, and last-in-first-out ordering. Start by locating the HHVM implementation for Hack statement parsing and function-return behavior; done means the examples work with the documented output and deferred calls execute exactly once in reverse order.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.