Skip to content

docs: document the exhaustiveness vs. generics trade-off in match constructs#85

Merged
valbeat merged 2 commits into
mainfrom
docs/exhaustiveness-match-method
Jun 18, 2026
Merged

docs: document the exhaustiveness vs. generics trade-off in match constructs#85
valbeat merged 2 commits into
mainfrom
docs/exhaustiveness-match-method

Conversation

@valbeat

@valbeat valbeat commented Jun 18, 2026

Copy link
Copy Markdown
Owner

概要

Type Safety セクションの Sealed interface の記述を、match (true) における「厳密な網羅性チェック」と「ジェネリクス保持」のトレードオフを正確に説明する内容へ更新しました。

背景(PHPStan 2.2.2 で実測)

3つ目の variant を sealed に追加して「未対応ハンドラが静的解析エラーになるか(=厳密な網羅性)」を検証した結果:

手法 厳密な網羅性
(variant 追加で自動エラー)
型引数の保持
match (true) + instanceof ✅ 「does not handle remaining value」で検出 Okunwrap()mixed
isOk()/isErr() アーム ❌(default 必須で variant 追加を吸収) Ok<int>
match() メソッド ❌ variant 追加を黙って取りこぼす(呼び出し側は無傷) U|V

厳密な(enforced)網羅性が得られるのは match (true) + instanceof だけで、それは型引数を失うことが確定しました。match() メソッドは「現在の2アリティに対して total」ではあるものの、variant 追加に対する自動検出は行いません。

変更内容

  • Sealed interface の段落に「enforced exhaustiveness と generics 保持は二者択一」というトレードオフを明記
  • Result は実際には Ok|Err の2値固定なので、match() メソッドが実用上は全ケースを賄える点も補足

当初コミットの「match() is exhaustive by construction」は厳密には誤りだったため訂正しています。

ドキュメントのみの変更です。

@valbeat valbeat self-assigned this Jun 18, 2026
@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@valbeat, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 28 minutes and 37 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ea6d5ea3-8588-4030-9b7a-431cfce37591

📥 Commits

Reviewing files that changed from the base of the PR and between cf2262f and 3a7ba38.

📒 Files selected for processing (1)
  • README.md

Walkthrough

README.md の Type Safety セクションで、PHPStan が instanceof による型引き締め時に型引数を保持しないため unwrap()mixed になるという制限の後続説明を拡張。instanceof の用途を match(true) の網羅性確認に限定し、値が必要な場合の推奨パターンを明示した。

Changes

README Type Safety ガイダンス更新

Layer / File(s) Summary
Type Safety ガイダンスの拡張
README.md
instanceofmatch(true) の網羅性確認のみに使う旨を明示。値が必要な場合は match()(両アーム必須)を優先、または isOk()/isErr() で絞り込む方法を追記。さらに match(true) 内の isOk()/isErr() は PHPStan 上では網羅扱いされないため default が必要である点を明確化。

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Possibly related PRs

  • valbeat/php-result#82: 同じ instanceof 型引き締め制限と isOk()/isErr() による値取得に関する README ドキュメントを対象としており、今回の変更と直接重複している。
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PRタイトルは「docs: document the exhaustiveness vs. generics trade-off in match constructs」であり、README.mdの「Type Safety」セクションにおいて、match(true)match() メソッドの使い分け、及び instanceofisOk()/isErr() の型安全性トレードオフについて詳細化した変更内容を適切に要約している。タイトルはこのPRの主要な変更(ドキュメントの型安全性ガイダンス向上)を明確に反映している。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch docs/exhaustiveness-match-method

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request updates the README.md to clarify PHPStan's behavior regarding type narrowing and exhaustiveness checks, specifically comparing the use of instanceof in match (true) against the match() method and isOk()/isErr(). The reviewer suggested a minor phrasing improvement to use "preserves the type arguments" instead of "keeps T/E" for better terminology consistency with the rest of the text.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread README.md Outdated
plain `Ok`, so `unwrap()` becomes `mixed`), so use `instanceof` in a
`match (true)` purely for exhaustiveness. When you also need the values, prefer
the `match()` method — it is exhaustive by construction (both arms are required)
and keeps `T`/`E` — or narrow with `isOk()`/`isErr()`. (`isOk()`/`isErr()` arms

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

直前の文で loses the type arguments と表現されているため、こちらでも keeps T/E ではなく preserves the type arguments(または keeps the type arguments)と表現する方が、用語の一貫性と正確性の観点からより適切です。

Suggested change
and keeps `T`/`E` — or narrow with `isOk()`/`isErr()`. (`isOk()`/`isErr()` arms
and preserves the type arguments — or narrow with `isOk()`/`isErr()`. (`isOk()`/`isErr()` arms

@codecov

codecov Bot commented Jun 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (27470ee) to head (3a7ba38).
⚠️ Report is 3 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@             Coverage Diff             @@
##                main       #85   +/-   ##
===========================================
  Coverage     100.00%   100.00%           
  Complexity        40        40           
===========================================
  Files              2         2           
  Lines             80        80           
===========================================
  Hits              80        80           
Flag Coverage Δ
unittests 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@valbeat valbeat changed the title docs: recommend match() method for exhaustiveness with generics preserved docs: document the exhaustiveness vs. generics trade-off in match constructs Jun 18, 2026
@valbeat valbeat marked this pull request as ready for review June 18, 2026 13:43
Copilot AI review requested due to automatic review settings June 18, 2026 13:43
@valbeat valbeat merged commit fbc851b into main Jun 18, 2026
9 checks passed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Updates the README’s “Type Safety” section to more precisely explain the PHPStan trade-off between (1) enforced exhaustiveness checking when using match (true) + instanceof, and (2) preserving generic type arguments when using match() or isOk()/isErr().

Changes:

  • Rewrites the “Sealed interface” paragraph to clarify that enforced exhaustiveness and preserved generics are currently mutually exclusive in PHPStan 2.2.2.
  • Documents that the match() method preserves T/E and requires both success/error handlers.
  • Adds context that Result is practically fixed to Ok|Err, so match() is total for real cases.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread README.md
Comment on lines +152 to +162
`match (true)` purely for exhaustiveness. When you also need the values, the
`match()` method handles both cases and keeps `T`/`E` (it requires both an `ok`
and an `err` arm), or narrow with `isOk()`/`isErr()`. These two goals are a
trade-off in PHPStan 2.2.2: *enforced* exhaustiveness — where adding a new
`Result` variant would turn every unhandled site into an analysis error — comes
only from `instanceof` in a `match (true)`, which is exactly the form that drops
the type arguments. The `match()` method and `isOk()`/`isErr()` keep the generics
but are not checked against variant additions (`isOk()`/`isErr()` arms in a
`match (true)` also need a `default`). So per call site you currently pick one:
enforced exhaustiveness *or* preserved generics. (In practice `Result` is fixed
at `Ok|Err`, so the `match()` method covering both is total for all real cases.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants