rust-bindgen icon indicating copy to clipboard operation
rust-bindgen copied to clipboard

What is a good strategy to extract information out of `ParseCallbacks`?

Open N3xed opened this issue 3 years ago • 3 comments

I'd like to extract information from ParseCallbacks so that it can be used later in the build script.

For example:

I have three C macros:

  • VERSION_MAJOR
  • VERSION_MINOR
  • VERSION_PATCH

which all define a number and so get forwarded to ParseCallbacks::int_macro. Now in my implementation of that callback, I want to capture these integers for use later in the build script.

Currently, as I see it, the only option is to use Atomic* or Mutex as the bound on ParseCallbacks specifies UnwindSafe which references to types with interior mutability are not, and the callbacks themselves only get a shared reference to self. This works but is not pretty and may incur performance penalties for Mutex.

So my questions are:

  • What is the preferred strategy for doing something like that? (More so with a less trivial example that requires more complex data e.g. ParseCallbacks::func_macro)
  • Why do these functions not get a mutable reference to self if the callbacks don't need to be Send/Sync?

N3xed avatar Dec 30 '21 18:12 N3xed

Generally interior mutability is the way we've been doing this, yeah. So a RefCell or so perhaps.

The callbacks don't take mutable references because the BindgenContext they are stored in is immutable as well. We could internally use RefCell<Box<ParseCallbacks>> or so to allow that and move the burden to bindgen.

emilio avatar Jan 29 '22 10:01 emilio

Thanks for the response.

It seems like I missed RefCell (I only tried Cell and because that's not UnwindSafe thought that all *Cell types wouldn't work).

We could internally use RefCell<Box<ParseCallbacks>> or so to allow that and move the burden to bindgen.

That would be nice.

Until then I'll make a PR to mention this in the docs (if that's okay), because I didn't find this mentioned even though ParseCallbacks::func_macro exists only to extract information out of bindgen.

N3xed avatar Jan 29 '22 11:01 N3xed

Yeah, a PR mentioning that seems great.

emilio avatar Feb 04 '22 10:02 emilio

You cannot use RefCell either because it contains a Cell<isize> field. and as you already mentioned Cell does not implement RefUnwindSafe.

I opened #2317 which removes this restriction and uses panic hooks in the CLI. I'm not sure if anyone relies on catch_unwind to run bindgen and do something else if it panics but they should be able to achieve the same using threads anyway iiuc.

pvdrz avatar Oct 21 '22 18:10 pvdrz