fish-shell/fish-rust/src/ffi.rs

429 lines
12 KiB
Rust
Raw Normal View History

use crate::wchar_ffi::WCharToFFI;
#[rustfmt::skip]
use ::std::pin::Pin;
#[rustfmt::skip]
use ::std::slice;
use crate::env::{EnvMode, EnvStackRef, EnvStackRefFFI};
use crate::job_group::JobGroup;
pub use crate::wait_handle::{
WaitHandleRef, WaitHandleRefFFI, WaitHandleStore, WaitHandleStoreFFI,
};
2023-08-09 06:16:04 +08:00
use crate::wchar::prelude::*;
use crate::wchar_ffi::WCharFromFFI;
2023-01-15 06:56:24 +08:00
use autocxx::prelude::*;
use cxx::SharedPtr;
use libc::pid_t;
2023-01-15 06:56:24 +08:00
// autocxx has been hacked up to know about this.
pub type wchar_t = u32;
include_cpp! {
#include "autoload.h"
#include "builtin.h"
#include "color.h"
#include "common.h"
#include "complete.h"
#include "env.h"
#include "env_universal_common.h"
#include "event.h"
2023-06-17 05:38:08 +08:00
#include "exec.h"
#include "fallback.h"
2023-01-15 06:56:24 +08:00
#include "fds.h"
Port AST to Rust The translation is fairly direct though it adds some duplication, for example there are multiple "match" statements that mimic function overloading. Rust has no overloading, and we cannot have generic methods in the Node trait (due to a Rust limitation, the error is like "cannot be made into an object") so we include the type name in method names. Give clients like "indent_visitor_t" a Rust companion ("IndentVisitor") that takes care of the AST traversal while the AST consumption remains in C++ for now. In future, "IndentVisitor" should absorb the entirety of "indent_visitor_t". This pattern requires that "fish_indent" be exposed includable header to the CXX bridge. Alternatively, we could define FFI wrappers for recursive AST traversal. Rust requires we separate the AST visitors for "mut" and "const" scenarios. Take this opportunity to concretize both visitors: The only client that requires mutable access is the populator. To match the structure of the C++ populator which makes heavy use of function overloading, we need to add a bunch of functions to the trait. Since there is no other mutable visit, this seems acceptable. The "const" visitors never use "will_visit_fields_of()" or "did_visit_fields_of()", so remove them (though this is debatable). Like in the C++ implementation, the AST nodes themselves are largely defined via macros. Union fields like "Statement" and "ArgumentOrRedirection" do currently not use macros but may in future. This commit also introduces a precedent for a type that is defined in one CXX bridge and used in another one - "ParseErrorList". To make this work we need to manually define "ExternType". There is one annoyance with CXX: functions that take explicit lifetime parameters require to be marked as unsafe. This makes little sense because functions that return `&Foo` with implicit lifetime can be misused the same way on the C++ side. One notable change is that we cannot directly port "find_block_open_keyword()" (which is used to compute an error) because it relies on the stack of visited nodes. We cannot modify a stack of node references while we do the "mut" walk. Happily, an idiomatic solution is easy: we can tell the AST visitor to backtrack to the parent node and create the error there. Since "node_t::accept_base" is no longer a template we don't need the "node_visitation_t" trampoline anymore. The added copying at the FFI boundary makes things slower (memcpy dominates the profile) but it's not unusable, which is good news: $ hyperfine ./fish.{old,new}" -c 'source ../share/completions/git.fish'" Benchmark 1: ./fish.old -c 'source ../share/completions/git.fish' Time (mean ± σ): 195.5 ms ± 2.9 ms [User: 190.1 ms, System: 4.4 ms] Range (min … max): 193.2 ms … 205.1 ms 15 runs Benchmark 2: ./fish.new -c 'source ../share/completions/git.fish' Time (mean ± σ): 677.5 ms ± 62.0 ms [User: 665.4 ms, System: 10.0 ms] Range (min … max): 611.7 ms … 805.5 ms 10 runs Summary './fish.old -c 'source ../share/completions/git.fish'' ran 3.47 ± 0.32 times faster than './fish.new -c 'source ../share/completions/git.fish'' Leftovers: - Enum variants are still snakecase; I didn't get around to changing this yet. - "ast_type_to_string()" still returns a snakecase name. This could be changed since it's not user visible.
2023-04-02 22:42:59 +08:00
#include "fish_indent_common.h"
2023-01-15 06:56:24 +08:00
#include "flog.h"
2023-04-11 01:49:50 +08:00
#include "function.h"
#include "highlight.h"
#include "history.h"
2023-01-15 06:56:24 +08:00
#include "io.h"
#include "input_common.h"
#include "input.h"
#include "parse_constants.h"
2023-01-15 06:56:24 +08:00
#include "parser.h"
#include "parse_util.h"
2023-02-25 04:14:13 +08:00
#include "path.h"
2023-01-15 06:56:24 +08:00
#include "proc.h"
#include "reader.h"
#include "screen.h"
#include "tokenizer.h"
#include "wildcard.h"
#include "wutil.h"
2023-01-15 06:56:24 +08:00
// We need to block these types so when exposing C++ to Rust.
block!("WaitHandleStoreFFI")
block!("WaitHandleRefFFI")
2023-01-15 06:56:24 +08:00
safety!(unsafe_ffi)
generate_pod!("wcharz_t")
generate!("wcstring_list_ffi_t")
2023-01-15 06:56:24 +08:00
generate!("wperror")
generate!("set_inheriteds_ffi")
generate!("init_input")
2023-01-15 06:56:24 +08:00
generate_pod!("pipes_ffi_t")
generate!("environment_t")
generate!("env_stack_t")
generate!("env_var_t")
generate!("env_universal_t")
generate!("env_universal_sync_result_t")
generate!("callback_data_t")
generate!("universal_notifier_t")
generate!("var_table_ffi_t")
generate!("event_list_ffi_t")
2023-01-15 06:56:24 +08:00
generate!("make_pipes_ffi")
2023-03-28 23:59:51 +08:00
generate!("log_extra_to_flog_file")
2023-01-15 06:56:24 +08:00
2023-02-05 16:35:06 +08:00
generate!("fish_wcwidth")
generate!("fish_wcswidth")
2023-01-15 06:56:24 +08:00
generate!("wildcard_match")
generate!("wgettext_ptr")
2023-01-15 06:56:24 +08:00
generate!("block_t")
generate!("parser_t")
generate!("job_t")
generate!("job_control_t")
generate!("get_job_control_mode")
generate!("set_job_control_mode")
generate!("get_login")
generate!("process_t")
2023-02-19 00:13:58 +08:00
generate!("library_data_t")
generate_pod!("library_data_pod_t")
Port AST to Rust The translation is fairly direct though it adds some duplication, for example there are multiple "match" statements that mimic function overloading. Rust has no overloading, and we cannot have generic methods in the Node trait (due to a Rust limitation, the error is like "cannot be made into an object") so we include the type name in method names. Give clients like "indent_visitor_t" a Rust companion ("IndentVisitor") that takes care of the AST traversal while the AST consumption remains in C++ for now. In future, "IndentVisitor" should absorb the entirety of "indent_visitor_t". This pattern requires that "fish_indent" be exposed includable header to the CXX bridge. Alternatively, we could define FFI wrappers for recursive AST traversal. Rust requires we separate the AST visitors for "mut" and "const" scenarios. Take this opportunity to concretize both visitors: The only client that requires mutable access is the populator. To match the structure of the C++ populator which makes heavy use of function overloading, we need to add a bunch of functions to the trait. Since there is no other mutable visit, this seems acceptable. The "const" visitors never use "will_visit_fields_of()" or "did_visit_fields_of()", so remove them (though this is debatable). Like in the C++ implementation, the AST nodes themselves are largely defined via macros. Union fields like "Statement" and "ArgumentOrRedirection" do currently not use macros but may in future. This commit also introduces a precedent for a type that is defined in one CXX bridge and used in another one - "ParseErrorList". To make this work we need to manually define "ExternType". There is one annoyance with CXX: functions that take explicit lifetime parameters require to be marked as unsafe. This makes little sense because functions that return `&Foo` with implicit lifetime can be misused the same way on the C++ side. One notable change is that we cannot directly port "find_block_open_keyword()" (which is used to compute an error) because it relies on the stack of visited nodes. We cannot modify a stack of node references while we do the "mut" walk. Happily, an idiomatic solution is easy: we can tell the AST visitor to backtrack to the parent node and create the error there. Since "node_t::accept_base" is no longer a template we don't need the "node_visitation_t" trampoline anymore. The added copying at the FFI boundary makes things slower (memcpy dominates the profile) but it's not unusable, which is good news: $ hyperfine ./fish.{old,new}" -c 'source ../share/completions/git.fish'" Benchmark 1: ./fish.old -c 'source ../share/completions/git.fish' Time (mean ± σ): 195.5 ms ± 2.9 ms [User: 190.1 ms, System: 4.4 ms] Range (min … max): 193.2 ms … 205.1 ms 15 runs Benchmark 2: ./fish.new -c 'source ../share/completions/git.fish' Time (mean ± σ): 677.5 ms ± 62.0 ms [User: 665.4 ms, System: 10.0 ms] Range (min … max): 611.7 ms … 805.5 ms 10 runs Summary './fish.old -c 'source ../share/completions/git.fish'' ran 3.47 ± 0.32 times faster than './fish.new -c 'source ../share/completions/git.fish'' Leftovers: - Enum variants are still snakecase; I didn't get around to changing this yet. - "ast_type_to_string()" still returns a snakecase name. This could be changed since it's not user visible.
2023-04-02 22:42:59 +08:00
generate!("highlighter_t")
generate!("proc_wait_any")
generate!("output_stream_t")
generate!("io_streams_t")
generate!("make_null_io_streams_ffi")
generate!("make_test_io_streams_ffi")
generate!("get_test_output_ffi")
generate_pod!("RustFFIJobList")
generate_pod!("RustFFIProcList")
generate_pod!("RustBuiltin")
2023-02-25 04:14:13 +08:00
generate!("builtin_exists")
generate!("builtin_missing_argument")
generate!("builtin_unknown_option")
generate!("builtin_print_help")
2023-02-19 00:13:58 +08:00
generate!("builtin_print_error_trailer")
generate!("builtin_get_names_ffi")
Port AST to Rust The translation is fairly direct though it adds some duplication, for example there are multiple "match" statements that mimic function overloading. Rust has no overloading, and we cannot have generic methods in the Node trait (due to a Rust limitation, the error is like "cannot be made into an object") so we include the type name in method names. Give clients like "indent_visitor_t" a Rust companion ("IndentVisitor") that takes care of the AST traversal while the AST consumption remains in C++ for now. In future, "IndentVisitor" should absorb the entirety of "indent_visitor_t". This pattern requires that "fish_indent" be exposed includable header to the CXX bridge. Alternatively, we could define FFI wrappers for recursive AST traversal. Rust requires we separate the AST visitors for "mut" and "const" scenarios. Take this opportunity to concretize both visitors: The only client that requires mutable access is the populator. To match the structure of the C++ populator which makes heavy use of function overloading, we need to add a bunch of functions to the trait. Since there is no other mutable visit, this seems acceptable. The "const" visitors never use "will_visit_fields_of()" or "did_visit_fields_of()", so remove them (though this is debatable). Like in the C++ implementation, the AST nodes themselves are largely defined via macros. Union fields like "Statement" and "ArgumentOrRedirection" do currently not use macros but may in future. This commit also introduces a precedent for a type that is defined in one CXX bridge and used in another one - "ParseErrorList". To make this work we need to manually define "ExternType". There is one annoyance with CXX: functions that take explicit lifetime parameters require to be marked as unsafe. This makes little sense because functions that return `&Foo` with implicit lifetime can be misused the same way on the C++ side. One notable change is that we cannot directly port "find_block_open_keyword()" (which is used to compute an error) because it relies on the stack of visited nodes. We cannot modify a stack of node references while we do the "mut" walk. Happily, an idiomatic solution is easy: we can tell the AST visitor to backtrack to the parent node and create the error there. Since "node_t::accept_base" is no longer a template we don't need the "node_visitation_t" trampoline anymore. The added copying at the FFI boundary makes things slower (memcpy dominates the profile) but it's not unusable, which is good news: $ hyperfine ./fish.{old,new}" -c 'source ../share/completions/git.fish'" Benchmark 1: ./fish.old -c 'source ../share/completions/git.fish' Time (mean ± σ): 195.5 ms ± 2.9 ms [User: 190.1 ms, System: 4.4 ms] Range (min … max): 193.2 ms … 205.1 ms 15 runs Benchmark 2: ./fish.new -c 'source ../share/completions/git.fish' Time (mean ± σ): 677.5 ms ± 62.0 ms [User: 665.4 ms, System: 10.0 ms] Range (min … max): 611.7 ms … 805.5 ms 10 runs Summary './fish.old -c 'source ../share/completions/git.fish'' ran 3.47 ± 0.32 times faster than './fish.new -c 'source ../share/completions/git.fish'' Leftovers: - Enum variants are still snakecase; I didn't get around to changing this yet. - "ast_type_to_string()" still returns a snakecase name. This could be changed since it's not user visible.
2023-04-02 22:42:59 +08:00
generate!("pretty_printer_t")
2023-02-11 23:51:43 +08:00
generate!("escape_string")
Port fd_monitor (and its needed components) I needed to rename some types already ported to rust so they don't clash with their still-extant cpp counterparts. Helper ffi functions added to avoid needing to dynamically allocate an FdMonitorItem for every fd (we use dozens per basic prompt). I ported some functions from cpp to rust that are used only in the backend but without removing their existing cpp counterparts so cpp code can continue to use their version of them (`wperror` and `make_detached_pthread`). I ran into issues porting line-by-line logic because rust inverts the behavior of `std::remove_if(..)` by making it (basically) `Vec::retain_if(..)` so I replaced bools with an explict enum to make everything clearer. I'll port the cpp tests for this separately, for now they're using ffi. Porting closures was ugly. It's nothing hard, but it's very ugly as now each capturing lambda has been changed into an explicit struct that contains its parameters (that needs to be dynamically allocated), a standalone callback (member) function to replace the lambda contents, and a separate trampoline function to call it from rust over the shared C abi (not really relevant to x86_64 w/ its single calling convention but probably needed on other platforms). I don't like that `fd_monitor.rs` has its own `c_void`. I couldn't find a way to move that to `ffi.rs` but still get cxx bridge to consider it a shared POD. Every time I moved it to a different module, it would consider it to be an opaque rust type instead. I worry this means we're going to have multiple `c_void1`, `c_void2`, etc. types as we continue to port code to use function pointers. Also, rust treats raw pointers as foreign so you can't do `impl Send for * const Foo` even if `Foo` is from the same module. That necessitated a wrapper type (`void_ptr`) that implements `Send` and `Sync` so we can move stuff between threads. The code in fd_monitor_t has been split into two objects, one that is used by the caller and a separate one associated with the background thread (this is made nice and clean by rust's ownership model). Objects not needed under the lock (i.e. accessed by the background thread exclusively) were moved to the separate `BackgroundFdMonitor` type.
2023-02-18 09:21:44 +08:00
generate!("fd_event_signaller_t")
generate!("block_t")
generate!("block_type_t")
generate!("statuses_t")
generate!("io_chain_t")
generate!("env_var_t")
2023-06-17 05:38:08 +08:00
generate!("exec_subshell_ffi")
generate!("rgb_color_t")
generate_pod!("color24_t")
2023-04-11 01:49:50 +08:00
generate!("colorize_shell")
generate!("reader_status_count")
generate!("get_history_variable_text_ffi")
generate!("is_interactive_session")
generate!("set_interactive_session")
generate!("screen_set_midnight_commander_hack")
generate!("screen_clear_layout_cache_ffi")
generate!("escape_code_length_ffi")
generate!("reader_schedule_prompt_repaint")
generate!("reader_change_history")
generate!("history_session_id")
generate!("reader_change_cursor_selection_mode")
generate!("reader_set_autosuggestion_enabled_ffi")
generate!("complete_invalidate_path")
generate!("complete_add_wrapper")
generate!("update_wait_on_escape_ms_ffi")
generate!("update_wait_on_sequence_key_ms_ffi")
generate!("autoload_t")
generate!("make_autoload_ffi")
generate!("perform_autoload_ffi")
generate!("complete_get_wrap_targets_ffi")
generate!("is_thompson_shell_script")
}
impl parser_t {
pub fn get_wait_handles_mut(&mut self) -> &mut WaitHandleStore {
let ptr = self.get_wait_handles_void() as *mut Box<WaitHandleStoreFFI>;
assert!(!ptr.is_null());
unsafe { (*ptr).from_ffi_mut() }
}
pub fn get_wait_handles(&self) -> &WaitHandleStore {
let ptr = self.get_wait_handles_void() as *const Box<WaitHandleStoreFFI>;
assert!(!ptr.is_null());
unsafe { (*ptr).from_ffi() }
}
pub fn get_block_at_index(&self, i: usize) -> Option<&block_t> {
let b = self.block_at_index(i);
unsafe { b.as_ref() }
}
pub fn get_jobs(&self) -> &[SharedPtr<job_t>] {
let ffi_jobs = self.ffi_jobs();
unsafe { slice::from_raw_parts(ffi_jobs.jobs, ffi_jobs.count) }
}
pub fn libdata_pod(&mut self) -> &mut library_data_pod_t {
let libdata = self.pin().ffi_libdata_pod();
unsafe { &mut *libdata }
}
pub fn remove_var(&mut self, var: &wstr, flags: c_int) -> c_int {
self.pin().remove_var_ffi(&var.to_ffi(), flags)
}
pub fn job_get_from_pid(&self, pid: pid_t) -> Option<&job_t> {
let job = self.ffi_job_get_from_pid(pid.into());
unsafe { job.as_ref() }
}
pub fn get_vars(&mut self) -> EnvStackRef {
self.pin().vars().from_ffi()
}
2023-06-17 05:38:08 +08:00
pub fn get_func_name(&mut self, level: i32) -> Option<WString> {
let name = self.pin().get_function_name_ffi(c_int(level));
name.as_ref()
.map(|s| s.from_ffi())
.filter(|s| !s.is_empty())
}
}
unsafe impl Send for env_universal_t {}
impl env_stack_t {
/// Access the underlying Rust environment stack.
#[allow(clippy::borrowed_box)]
pub fn from_ffi(&self) -> EnvStackRef {
// Safety: get_impl_ffi returns a pointer to a Box<EnvStackRefFFI>.
let envref = self.get_impl_ffi();
assert!(!envref.is_null());
let env: &Box<EnvStackRefFFI> = unsafe { &*(envref.cast()) };
env.0.clone()
}
}
impl environment_t {
/// Helper to get a variable as a string, using the default flags.
pub fn get_as_string(&self, name: &wstr) -> Option<WString> {
self.get_as_string_flags(name, EnvMode::default())
}
/// Helper to get a variable as a string, using the given flags.
pub fn get_as_string_flags(&self, name: &wstr, flags: EnvMode) -> Option<WString> {
self.get_or_null(&name.to_ffi(), flags.bits())
.as_ref()
.map(|s| s.as_string().from_ffi())
}
}
impl env_stack_t {
/// Helper to get a variable as a string, using the default flags.
pub fn get_as_string(&self, name: &wstr) -> Option<WString> {
self.get_as_string_flags(name, EnvMode::default())
}
/// Helper to get a variable as a string, using the given flags.
pub fn get_as_string_flags(&self, name: &wstr, flags: EnvMode) -> Option<WString> {
self.get_or_null(&name.to_ffi(), flags.bits())
.as_ref()
.map(|s| s.as_string().from_ffi())
}
/// Helper to set a value.
2023-06-17 05:38:08 +08:00
pub fn set_var<T: AsRef<wstr>, U: AsRef<wstr>>(
&mut self,
name: T,
value: &[U],
flags: EnvMode,
) -> libc::c_int {
use crate::wchar_ffi::{wstr_to_u32string, W0String};
let strings: Vec<W0String> = value.iter().map(wstr_to_u32string).collect();
let ptrs: Vec<*const u32> = strings.iter().map(|s| s.as_ptr()).collect();
self.pin()
.set_ffi(
2023-06-17 05:38:08 +08:00
&name.as_ref().to_ffi(),
flags.bits(),
ptrs.as_ptr() as *const c_void,
ptrs.len(),
)
.into()
}
}
impl job_t {
#[allow(clippy::mut_from_ref)]
pub fn get_procs(&self) -> &mut [UniquePtr<process_t>] {
let ffi_procs = self.ffi_processes();
unsafe { slice::from_raw_parts_mut(ffi_procs.procs, ffi_procs.count) }
}
pub fn get_job_group(&self) -> &JobGroup {
unsafe { ::std::mem::transmute::<&job_group_t, &JobGroup>(self.ffi_group()) }
}
2023-01-15 06:56:24 +08:00
}
impl process_t {
/// \return the wait handle for the process, if it exists.
pub fn get_wait_handle(&self) -> Option<WaitHandleRef> {
let handle_ptr = self.get_wait_handle_void() as *const Box<WaitHandleRefFFI>;
if handle_ptr.is_null() {
None
} else {
let handle: &WaitHandleRefFFI = unsafe { &*handle_ptr };
Some(handle.from_ffi().clone())
}
}
/// \return the wait handle for the process, creating it if necessary.
pub fn make_wait_handle(&mut self, jid: u64) -> Option<WaitHandleRef> {
let handle_ref = self.pin().make_wait_handle_void(jid) as *const Box<WaitHandleRefFFI>;
if handle_ref.is_null() {
None
} else {
let handle: &WaitHandleRefFFI = unsafe { &*handle_ref };
Some(handle.from_ffi().clone())
}
}
}
2023-01-15 06:56:24 +08:00
/// Allow wcharz_t to be "into" wstr.
2023-08-09 06:16:04 +08:00
impl From<wcharz_t> for &wstr {
2023-01-15 06:56:24 +08:00
fn from(w: wcharz_t) -> Self {
let len = w.length();
#[allow(clippy::unnecessary_cast)]
2023-01-15 06:56:24 +08:00
let v = unsafe { slice::from_raw_parts(w.str_ as *const u32, len) };
2023-08-09 06:16:04 +08:00
wstr::from_slice(v).expect("Invalid UTF-32")
2023-01-15 06:56:24 +08:00
}
}
/// Allow wcharz_t to be "into" WString.
2023-08-09 06:16:04 +08:00
impl From<wcharz_t> for WString {
2023-01-15 06:56:24 +08:00
fn from(w: wcharz_t) -> Self {
2023-08-09 06:16:04 +08:00
let w: &wstr = w.into();
w.to_owned()
2023-01-15 06:56:24 +08:00
}
}
/// A bogus trait for turning &mut Foo into Pin<&mut Foo>.
/// autocxx enforces that non-const methods must be called through Pin,
/// but this means we can't pass around mutable references to types like parser_t.
/// We also don't want to assert that parser_t is Unpin.
/// So we just allow constructing a pin from a mutable reference; none of the C++ code.
/// It's worth considering disabling this in cxx; for now we use this trait.
/// Eventually parser_t and io_streams_t will not require Pin so we just unsafe-it away.
pub trait Repin {
fn pin(&mut self) -> Pin<&mut Self> {
unsafe { Pin::new_unchecked(self) }
}
fn unpin(self: Pin<&mut Self>) -> &mut Self {
unsafe { self.get_unchecked_mut() }
}
}
// Implement Repin for our types.
impl Repin for autoload_t {}
impl Repin for block_t {}
impl Repin for env_stack_t {}
impl Repin for env_universal_t {}
impl Repin for io_streams_t {}
impl Repin for job_t {}
impl Repin for output_stream_t {}
impl Repin for parser_t {}
impl Repin for process_t {}
impl Repin for wcstring_list_ffi_t {}
2023-01-15 06:56:24 +08:00
pub use autocxx::c_int;
pub use ffi::*;
pub use libc::c_char;
Port fd_monitor (and its needed components) I needed to rename some types already ported to rust so they don't clash with their still-extant cpp counterparts. Helper ffi functions added to avoid needing to dynamically allocate an FdMonitorItem for every fd (we use dozens per basic prompt). I ported some functions from cpp to rust that are used only in the backend but without removing their existing cpp counterparts so cpp code can continue to use their version of them (`wperror` and `make_detached_pthread`). I ran into issues porting line-by-line logic because rust inverts the behavior of `std::remove_if(..)` by making it (basically) `Vec::retain_if(..)` so I replaced bools with an explict enum to make everything clearer. I'll port the cpp tests for this separately, for now they're using ffi. Porting closures was ugly. It's nothing hard, but it's very ugly as now each capturing lambda has been changed into an explicit struct that contains its parameters (that needs to be dynamically allocated), a standalone callback (member) function to replace the lambda contents, and a separate trampoline function to call it from rust over the shared C abi (not really relevant to x86_64 w/ its single calling convention but probably needed on other platforms). I don't like that `fd_monitor.rs` has its own `c_void`. I couldn't find a way to move that to `ffi.rs` but still get cxx bridge to consider it a shared POD. Every time I moved it to a different module, it would consider it to be an opaque rust type instead. I worry this means we're going to have multiple `c_void1`, `c_void2`, etc. types as we continue to port code to use function pointers. Also, rust treats raw pointers as foreign so you can't do `impl Send for * const Foo` even if `Foo` is from the same module. That necessitated a wrapper type (`void_ptr`) that implements `Send` and `Sync` so we can move stuff between threads. The code in fd_monitor_t has been split into two objects, one that is used by the caller and a separate one associated with the background thread (this is made nice and clean by rust's ownership model). Objects not needed under the lock (i.e. accessed by the background thread exclusively) were moved to the separate `BackgroundFdMonitor` type.
2023-02-18 09:21:44 +08:00
/// A version of [`* const core::ffi::c_void`] (or [`* const libc::c_void`], if you prefer) that
/// implements `Copy` and `Clone`, because those two don't. Used to represent a `void *` ptr for ffi
/// purposes.
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct void_ptr(pub *const core::ffi::c_void);
impl core::fmt::Debug for void_ptr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:p}", &self.0)
}
}
unsafe impl Send for void_ptr {}
unsafe impl Sync for void_ptr {}
impl core::convert::From<*const core::ffi::c_void> for void_ptr {
fn from(value: *const core::ffi::c_void) -> Self {
Self(value as *const _)
}
}
impl core::convert::From<*const u8> for void_ptr {
fn from(value: *const u8) -> Self {
Self(value as *const _)
}
}
impl core::convert::From<*const autocxx::c_void> for void_ptr {
fn from(value: *const autocxx::c_void) -> Self {
Self(value as *const _)
}
}
impl core::convert::From<void_ptr> for *const u8 {
fn from(value: void_ptr) -> Self {
value.0 as *const _
}
}
impl core::convert::From<void_ptr> for *const core::ffi::c_void {
fn from(value: void_ptr) -> Self {
value.0 as *const _
}
}
impl core::convert::From<void_ptr> for *const autocxx::c_void {
fn from(value: void_ptr) -> Self {
value.0 as *const _
}
}
impl TryFrom<&wstr> for job_control_t {
type Error = ();
fn try_from(value: &wstr) -> Result<Self, Self::Error> {
if value == "full" {
Ok(job_control_t::all)
} else if value == "interactive" {
Ok(job_control_t::interactive)
} else if value == "none" {
Ok(job_control_t::none)
} else {
Err(())
}
}
}