lean4 icon indicating copy to clipboard operation
lean4 copied to clipboard

`deriving` does not handle `unsafe` (or `noncomputable`)

Open eric-wieser opened this issue 2 years ago • 4 comments

Prerequisites

  • [X] Put an X between the brackets on this line if you have done all of the following:
    • Check that your issue is not already filed.
    • Reduce the issue to a minimal, self-contained, reproducible test case. Avoid dependencies to mathlib4 or std4.

Description

The deriving mechanism does not copy across unsafe attributes, and so cannot be used in the presence of unsafe code.

Perhaps erroring here is deliberate to avoid accidental creation of unsafe code; in which case, deriving unsafe Repr, unsafe BEq might be an acceptable solution.

Note that the same problem also occurs for noncomputable, though that can be handled with noncomputable section

Context

Zulip message

Steps to Reproduce

  1. Run the following
    structure Foo
    
    unsafe instance : Repr Foo where
      reprPrec f n := "foo"
    
    unsafe instance : BEq Foo where
      beq f₁ f₂ := true
    
    structure Bar where
      foo : Foo
    deriving Repr, BEq
    

Expected behavior: unsafe instance : BEq Bar and unsafe instance : Repr Bar are created

Actual behavior: (kernel) invalid declaration, it uses unsafe declaration 'instReprFoo'

Versions

4.6.0-rc1

Impact

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

eric-wieser avatar Feb 25 '24 21:02 eric-wieser

Can you point to situations where this is needed?

kim-em avatar Apr 22 '24 06:04 kim-em

Anything like this?

unsafe inductive Foo where
  | default : Foo
  | io : IO Foo → Foo
  deriving Inhabited

Or:

opaque bar : NonemptyType
def Bar : Type := bar.type
noncomputable instance : Inhabited Bar := Classical.inhabited_of_nonempty bar.2

inductive Foo where
  | default : Bar → Foo
  deriving Inhabited
-- failed to compile definition, consider marking it as 'noncomputable' because it depends on
-- 'instInhabitedBar', and it does not have executable code

More concretely, this issue comes up when using deriving Repr on anything containing mathlib's Real type, which has an unsafe Repr instance.

digama0 avatar Apr 22 '24 06:04 digama0

Checked the examples in this thread against 4.35.0-nightly-2026-09-04 and stable 4.33.1. Current status is split — the noncomputable half is largely fixed, the unsafe half is not.

noncomputable — fixed via the standalone command. This now works:

opaque bar : NonemptyType
def Bar : Type := bar.type
noncomputable instance : Inhabited Bar := Classical.inhabited_of_nonempty bar.2

inductive Foo where
  | default : Bar → Foo

deriving noncomputable instance Inhabited for Foo

But there is no equivalent for the inline deriving clause, which takes no modifier, so @digama0's second example still fails with no way to opt in:

error(lean.dependsOnNoncomputable): failed to compile definition, consider marking it as
'noncomputable' because it depends on 'instInhabitedBar', which is 'noncomputable'

unsafe — not fixed, in either form. @eric-wieser's original example and @digama0's unsafe inductive both still fail, and there is no deriving unsafe instance counterpart to deriving noncomputable instance:

error: (kernel) invalid declaration, it uses unsafe declaration 'instReprFoo'

The unsafe structure case additionally panics the compiler. Five chained PANICs starting at ExplicitBoxing.tryCorrectLetDeclType, on both stable and nightly. Writing the same instance by hand errors cleanly, so it is specific to the deriving path. That looks like the unsafe counterpart of the panic fixed for noncomputable in #14125, and I have filed it separately as #15033 since it seems distinct from the feature gap discussed here.

So what remains under this issue is, I think, two things:

  1. no way to derive over unsafe at all — whether that should be deriving unsafe instance, or inferred as @eric-wieser suggested;
  2. the inline deriving clause accepts no noncomputable (or unsafe) modifier, unlike the standalone command.

Happy to leave this open, split it, or close (1) or (2) if either is deliberate — just wanted to record that the noncomputable half is mostly done so the issue title is no longer accurate.

Investigation assisted by Claude; all repros run and checked manually.

keithadler avatar Sep 04 '26 19:09 keithadler

I followed up locally on the remaining cases in this issue and on the related #15033 panic. I now have a staged patch against 51e162cdd6fa22825089f2b518101f702a9f66eb; I have not opened a PR.

The patch adds:

  • inline unsafe deriving, including deriving unsafe Repr, unsafe BEq;
  • standalone deriving unsafe instance Repr, BEq for T;
  • inline deriving noncomputable Inhabited;
  • propagation of unsafe status through both registered deriving handlers and delta deriving.

The patch also fixes #15033 through the generic addDecl fallback path rather than special-casing deriving.

After kernel rejection, addDecl installs a fallback axiom so elaboration can continue. A later declaration could therefore pass kernel checking but still enter code generation with a dependency that never had compilable IR.

The change records a successfully inserted kernel-error fallback in the existing noncomputable environment extension for compiler dependency checking. Lean’s existing dependency check then rejects direct or transitive executable use before IR/LCNF processing, while preserving the fallback declaration for elaboration error recovery.

Before/after results:

  • general zero-arity reproducer, async: 5 panics → 0; 1 IR failure → 0;
  • general zero-arity reproducer, synchronous: 5 panics → 0; 1 IR failure → 0;
  • derived Repr + BEq reproducers: 10 panics → 0; 2 IR failures → 0.

The original kernel errors remain, followed where applicable by a clean lean.dependsOnNoncomputable diagnostic.

Validation completed:

  • full stage1 build passed;
  • the new unsafe/noncomputable deriving regression file passed;
  • existing derivingDelta.lean and derivingInhabited.lean passed;
  • git diff --check passed.

The CTest wrapper for the focused test did not execute Lean in this Windows-mounted checkout because tests/util.sh has CRLF line endings, so I am not counting that wrapper as passing. Invoking the exact underlying test directly with the rebuilt stage1 compiler passes.

Prior-work attribution: eric-wieser supplied the original unsafe reproducer and inference suggestion; digama0 supplied the additional noncomputable and unsafe-inductive examples; keithadler isolated and filed the compiler panic as #15033.

The implementation is ready locally, but I’m leaving it without a PR unless a maintainer requests one or confirms the desired contribution route.

cjc0013 avatar Sep 27 '26 16:09 cjc0013