Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2024] 「if let の一時スコープ」を翻訳 #122

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@
- [Rust 2024](rust-2024/index.md)
- [言語](rust-2024/language.md)
- [RPIT lifetime capture rules](rust-2024/rpit-lifetime-capture.md)
- [`if let` temporary scope](rust-2024/temporary-if-let-scope.md)
- [`if let` の一時スコープ](rust-2024/temporary-if-let-scope.md)
- [Tail expression temporary scope](rust-2024/temporary-tail-expr-scope.md)
- [Match ergonomics reservations](rust-2024/match-ergonomics.md)
- [Unsafe `extern` blocks](rust-2024/unsafe-extern.md)
Expand Down
152 changes: 150 additions & 2 deletions src/rust-2024/temporary-if-let-scope.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,41 @@
> **Rust Edition Guide は現在 Rust 2024 のアップデート作業に向けて翻訳作業中です。本ページはある時点での英語版をコピーしていますが、一部のリンクが動作しない場合や、最新情報が更新されていない場合があります。問題が発生した場合は、[原文(英語版)](https://doc.rust-lang.org/nightly/edition-guide/introduction.html)をご参照ください。**

<!--
# `if let` temporary scope
-->

# `if let` の一時スコープ

<!--
## Summary
-->

## 概要

<!--
- In an `if let $pat = $expr { .. } else { .. }` expression, the temporary values generated from evaluating `$expr` will be dropped before the program enters the `else` branch instead of after.
-->

- 式 `if let $pat = $expr { .. } else { .. }` において `$expr`を評価する際に作られる一時値は、`else` 節以降が実行された後ではなく、実行される前にドロップされます。

<!--
## Details
-->

## 詳細

<!--
The 2024 Edition changes the drop scope of [temporary values] in the scrutinee[^scrutinee] of an `if let` expression. This is intended to help reduce the potentially unexpected behavior involved with the temporary living for too long.
-->

2024 エディションでは、`if let` 式の被検査体 (scurtinee)[^scurtinee]における[一時値 (temporary value)] のドロップスコープが変わります。
これは、一時値の生存期間が長すぎることによる、ときに想定外の挙動を避けるためのものです。

<!--
Before 2024, the temporaries could be extended beyond the `if let` expression itself. For example:
-->

2024 より前は、以下のように、一時値が `if let` 式自体の末尾まで生存し続けていました。

<!--
```rust,edition2021
// Before 2024
# use std::sync::RwLock;
Expand All @@ -28,11 +52,39 @@ fn f(value: &RwLock<Option<bool>>) {
// <--- Read lock is dropped here in 2021
}
```
-->

```rust,edition2021
// 2024 より前
# use std::sync::RwLock;

fn f(value: &RwLock<Option<bool>>) {
if let Some(x) = *value.read().unwrap() {
println!("value is {x}");
} else {
let mut v = value.write().unwrap();
if v.is_none() {
*v = Some(true);
}
}
// <--- 読み取りロックはここでドロップされる
}
```

<!--
In this example, the temporary read lock generated by the call to `value.read()` will not be dropped until after the `if let` expression (that is, after the `else` block). In the case where the `else` block is executed, this causes a deadlock when it attempts to acquire a write lock.
-->

この例では、`value.read()` によって生成された一時的な読み取りロックが、`if let` 式の末尾まで(`else` 節の末尾まで)ドロップされません。
`else` 節が実行された場合、書き込みロックを取得しようとしてデッドロックが発生してしまいます。

<!--
The 2024 Edition shortens the lifetime of the temporaries to the point where the then-block is completely evaluated or the program control enters the `else` block.
-->

2024 エディションでは、一時値の生存期間は then 節(`if let` の直後の `{ }` ブロック)の評価が完了したとき、あるいは `else` 節が開始するときに打ち切られます。

<!--
```rust,edition2024
// Starting with 2024
# use std::sync::RwLock;
Expand All @@ -50,22 +102,70 @@ fn f(value: &RwLock<Option<bool>>) {
}
}
```
-->

```rust,edition2024
// 2024 以降
# use std::sync::RwLock;

fn f(value: &RwLock<Option<bool>>) {
if let Some(x) = *value.read().unwrap() {
println!("value is {x}");
}
// <--- 2024 では、読み取りロックはここでドロップされる
else {
let mut s = value.write().unwrap();
if s.is_none() {
*s = Some(true);
}
}
}
```

<!--
See the [temporary scope rules] for more information about how temporary scopes are extended. See the [tail expression temporary scope] chapter for a similar change made to tail expressions.
-->

一時スコープの範囲に関しての詳細は、[一時値のスコープ規則]をご参照ください。
[末尾式の一時スコープ]の節では、末尾式に対する同様の変更について説明しています。

<!--
[^scrutinee]: The [scrutinee] is the expression being matched on in the `if let` expression.
-->

[^scurtinee]: [被検査体 (scurtinee)] とは、`if let` 式でマッチするかを検査される式(`=` 以降の式)のことです。

<!--
[scrutinee]: ../../reference/glossary.html#scrutinee
[temporary values]: ../../reference/expressions.html#temporaries
[temporary scope rules]: ../../reference/destructors.html#temporary-scopes
[tail expression temporary scope]: temporary-tail-expr-scope.md
-->

[被検査体 (scurtinee)]: https://doc.rust-lang.org/reference/glossary.html#scrutinee
[一時値 (temporary value)]: https://doc.rust-lang.org/reference/expressions.html#temporaries
[一時値のスコープ規則]: https://doc.rust-lang.org/reference/destructors.html#temporary-scopes
[末尾式の一時スコープ]: temporary-tail-expr-scope.md

<!--
## Migration
-->

## 移行

<!--
It is always safe to rewrite `if let` with a `match`. The temporaries of the `match` scrutinee are extended past the end of the `match` expression (typically to the end of the statement), which is the same as the 2021 behavior of `if let`.
-->
`if let` はいつでも `match` に安全に書き換えられます。
`match` の被検査体で生成される一時値は、2021 における `if let` の挙動と同様、少なくとも `match` 式の末尾まで(多くの場合、文の末尾まで)生存します。

<!--
The [`if_let_rescope`] lint suggests a fix when a lifetime issue arises due to this change or the lint detects that a temporary value with a custom, non-trivial `Drop` destructor is generated from the scrutinee of the `if let`. For instance, the earlier example may be rewritten into the following when the suggestion from `cargo fix` is accepted:
-->
[`if_let_rescope`] リントは、本変更によってライフタイムの問題が発生する場合や、`if let` の被検査体で生成される一時値が独自の非自明な `Drop` デストラクタをもつ場合に、修正案を提示します。
例えば、前述の例に対して `cargo fix` の提案を適用した場合、以下のように書き換えられます。

<!--
```rust
# use std::sync::RwLock;
fn f(value: &RwLock<Option<bool>>) {
Expand All @@ -83,22 +183,70 @@ fn f(value: &RwLock<Option<bool>>) {
// <--- Read lock is dropped here in both 2021 and 2024
}
```
-->

```rust
# use std::sync::RwLock;
fn f(value: &RwLock<Option<bool>>) {
match *value.read().unwrap() {
Some(x) => {
println!("value is {x}");
}
_ => {
let mut s = value.write().unwrap();
if s.is_none() {
*s = Some(true);
}
}
}
// <--- Rust 2021 でも 2024 でも、読み取りロックはここでドロップされる
}
```

<!--
In this particular example, that's probably not what you want due to the aforementioned deadlock! However, some scenarios may be assuming that the temporaries are held past the `else` clause, in which case you may want to retain the old behavior.
-->

特に上記のコードでは、前述の通りデッドロックが起こるため望む挙動ではないでしょうが、場合によっては従来の挙動そのままに、一時値が `else` 節以降も生き延びることを意図することもあるでしょう。

<!--
The [`if_let_rescope`] lint is part of the `rust-2024-compatibility` lint group which is included in the automatic edition migration. In order to migrate your code to be Rust 2024 Edition compatible, run:
-->

[`if_let_rescope`] リントは、自動エディション移行に含まれる `rust-2024-compatibility` リントグループの一部です。
コードを Rust 2024 に移行するには、以下を実行します。

```sh
cargo fix --edition
```

<!--
After the migration, it is recommended that you review all of the changes of `if let` to `match` and decide what is the behavior that you need with respect to when temporaries are dropped. If you determine that the change is unnecessary, then you can revert the change back to `if let`.
-->

移行後、`if let` から `match` へ変更された箇所をチェックし、一時値がドロップされるタイミングを再確認することを推奨します。
変更が不要と判断した場合は、`if let` へ戻すとよいでしょう。

<!--
If you want to manually inspect these warnings without performing the edition migration, you can enable the lint with:
-->

エディション移行ツールを使わずに手動で確認したい場合は、以下のリントをオンにしてください。

<!--
```rust
// Add this to the root of your crate to do a manual migration.
#![warn(if_let_rescope)]
```
-->

```rust
// クレートのトップレベルに以下を追加すると手動移行できる
#![warn(if_let_rescope)]
```

<!--
[`if_let_rescope`]: ../../rustc/lints/listing/allowed-by-default.html#if-let-rescope
-->

[`if_let_rescope`]: https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html#if-let-rescope