Zulip Chat Archive

Stream: lean4

Topic: FFI bitflags


Thomas Vigouroux (Nov 04 2024 at 12:26):

Hey there,

I am trying to map a C bitflag construct to Lean.

What it the recommended way to do so ?

Let's assume the C side looks like so:

enum Foo {
  A = 1
  B = 2
  C = 4
}

Thomas Vigouroux (Nov 04 2024 at 12:28):

I have tried making an inductive on the Lean side, a marking constructors as extern:

inductive Foo where
| A
| B
| C

attribute [extern "A"] Foo.A;

Henrik Böving (Nov 04 2024 at 12:28):

I would probably write

inductive Foo where
| A
| B
| C

together with code to convert from and to Foo, https://github.com/tydeu/lean4-alloy has some machinery to make this more convenient. If that conversion function is your bottleneck you're going to have solved a lot of other problems already :D

Mario Carneiro (Nov 04 2024 at 12:29):

a bitflag does not have the same semantics as a lean inductive

Mario Carneiro (Nov 04 2024 at 12:29):

for example 7 is a legal value of enum Foo

Thomas Vigouroux (Nov 04 2024 at 12:29):

Henrik Böving said:

I would probably write

inductive Foo where
| A
| B
| C

together with code to convert from and to Foo, https://github.com/tydeu/lean4-alloy has some machinery to make this more convenient. If that conversion function is your bottleneck you're going to have solved a lot of other problems already :D

I'll look into that, i'll be probably easier this way

Thomas Vigouroux (Nov 04 2024 at 12:30):

Mario Carneiro said:

a bitflag does not have the same semantics as a lean inductive

How would you do it then ?

Henrik Böving (Nov 04 2024 at 12:30):

Yeah Mario is right, if you decide to | them together you porbably want to use UInt8 constants with some additional machinery

Mario Carneiro (Nov 04 2024 at 12:30):

so a more accurate lean representation would be

structure foo where
  A : Bool
  B : Bool
  C : Bool

Thomas Vigouroux (Nov 04 2024 at 12:30):

Oh, and have some conversion machinery on the C side ?

Henrik Böving (Nov 04 2024 at 12:31):

Though that would actually need to allocate unlike a UInt8 no?

Mario Carneiro (Nov 04 2024 at 12:31):

if you want to save space on the lean side you can use UIntN but there will be overhead regardless


Last updated: May 02 2025 at 03:31 UTC