leanprover / leanprover/lean4

IR eta-expansion through trivial structure

Open
#13,685 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug code-generator P-medium
Dominant language
Lean
Stars
9.2k
Forks
990
Avg merge
1d 17h
Merged PRs (30d)
175

Description

Prerequisites
Description

Eta-expansion doesn't appear to work through Subtype, even though it's a trivial structure.

Steps to Reproduce

Run the following program:

abbrev StackedM := ReaderT String (StateM Nat)

variable {α : Type} {m : Type → Type} [Monad m]

instance [Nonempty (m β)] : Nonempty {_v : m β // True} :=
  ⟨⟨Classical.choice inferInstance, trivial⟩⟩

@[specialize] partial def whileSub [Nonempty (m β)]
    (f : α → m (α ⊕ β)) (a : α) : {_v : m β // True} :=
  ⟨do match ← f a with
      | .inl a' => (whileSub f a').val
      | .inr b  => pure b,
   trivial⟩

@[inline] def whileViaSub [Nonempty (m β)] (f : α → m (α ⊕ β)) (a : α) : m β :=
  (whileSub f a).val

@[specialize] partial def whileDirect [Nonempty (m β)]
    (f : α → m (α ⊕ β)) (a : α) : m β := do
  match ← f a with
  | .inl a' => whileDirect f a'
  | .inr b  => pure b

set_option trace.Compiler.result true

def testSub (n : Nat) : StackedM Nat :=
  whileViaSub (fun i => pure (if i < n then .inl (i + 1) else .inr i)) 0

def testDirect (n : Nat) : StackedM Nat :=
  whileDirect (fun i => pure (if i < n then .inl (i + 1) else .inr i)) 0

Expected behavior: testSub and testDirect optimize to the same code

Actual behavior: testSub allocates a PAP in the recursive case

Versions

Lean 4.30.0-rc2
Target: x86_64-unknown-linux-gnu

Impact

Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Run the self-contained program with trace.Compiler.result enabled and compare the generated code for testSub and testDirect. Investigate the compiler IR handling of Subtype and eta-expansion, using the whileSub recursive case as the failing example. Done means both definitions optimize to the same code without a recursive-case PAP.

Written by the indexing model from the issue text.

Assessment

Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.