leanprover / leanprover/lean4

Spurious coercion insertion when elaborating binops

Open
#12,728 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Prerequisites
Description

Binop elaboration (in that case ++) introduces non-sensical coercions, that do not appear when using hAppend directly.

In the following example:

set_option pp.coercions true

namespace Out.Functions

instance : CoeDep (BitVec n) x (BitVec m) where
  coe := x.setWidth m

def mask (n : Nat) (x : BitVec w) : BitVec n := sorry

def good : String :=
    if HAppend.hAppend (mask 1 0x0#4) (mask 5 0x1E#8) = mask 6 0x1E#8
    then "ok"
    else "bad"

def bad : String :=
    if (mask 1 0x0#4) ++ (mask 5 0x1E#8) = mask 6 0x1E#8
    then "ok"
    else "bad"

#print good
#print bad

the bad example has the following corections on the RHS of the equality BitVec.setWidth (1 + 5) (BitVec.setWidth 1 (mask 6 30#8)).

This seems to come from the fact that binop elaboration tries the homogeneous case HAppend (BitVec 1) (BitVec 1) (BitVec 1), and introcuces a coercion from BitVec 6 to BitVec 1 in the process, which is not removed when no such typeclass instance is found.

Context

This happens in the output of the lean backend of the sail compiler. cf https://github.com/rems-project/sail/issues/1630

Steps to Reproduce
  1. Add coercion instances
  2. Use them together with builtin binops such as ++

Expected behavior:
No unnecessary coercions are inserted.

Actual behavior:
Unnecessary coercions are inserted.

Versions

"4.28.0-nightly-2026-01-22" and the current live version.

Additional Information

[Additional information, configuration or data that might be necessary to reproduce the issue]

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

Start by running the minimal reproducer and comparing the ++ expression with direct HAppend.hAppend elaboration, inspecting the binop elaboration path. The fix is complete when the bad example no longer contains unnecessary BitVec.setWidth coercions in its printed core output, while direct hAppend behavior remains unchanged.

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
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.