Skip to content

Commit

Permalink
Move diagnostic handler to a separate struct
Browse files Browse the repository at this point in the history
Add the `DiagnosticHandler` struct which implements `LLVMDiagnosticHandler`,
so only that struct and not the whole `Linker` is passed to
`LLVMContextSetDiagnosticHandler`.

This is going to make writing a safe wrapper for `Context` easier.
  • Loading branch information
vadorovsky committed Nov 27, 2024
1 parent 91d8412 commit c9a7d33
Showing 1 changed file with 32 additions and 22 deletions.
54 changes: 32 additions & 22 deletions src/linker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ pub struct Linker {
context: LLVMContextRef,
module: LLVMModuleRef,
target_machine: LLVMTargetMachineRef,
has_errors: bool,
diagnostic_handler: DiagnosticHandler,
}

impl Linker {
Expand All @@ -244,7 +244,7 @@ impl Linker {
context: ptr::null_mut(),
module: ptr::null_mut(),
target_machine: ptr::null_mut(),
has_errors: false,
diagnostic_handler: DiagnosticHandler::new(),
}
}

Expand Down Expand Up @@ -274,7 +274,7 @@ impl Linker {
}

pub fn has_errors(&self) -> bool {
self.has_errors
self.diagnostic_handler.has_errors
}

fn link_modules(&mut self) -> Result<(), LinkerError> {
Expand Down Expand Up @@ -541,8 +541,8 @@ impl Linker {
self.context = LLVMContextCreate();
LLVMContextSetDiagnosticHandler(
self.context,
Some(llvm::diagnostic_handler::<Self>),
self as *mut _ as _,
Some(llvm::diagnostic_handler::<DiagnosticHandler>),
&mut self.diagnostic_handler as *mut _ as _,
);
LLVMInstallFatalErrorHandler(Some(llvm::fatal_error));
LLVMEnablePrettyStackTrace();
Expand All @@ -555,7 +555,33 @@ impl Linker {
}
}

impl llvm::LLVMDiagnosticHandler for Linker {
impl Drop for Linker {
fn drop(&mut self) {
unsafe {
if !self.target_machine.is_null() {
LLVMDisposeTargetMachine(self.target_machine);
}
if !self.module.is_null() {
LLVMDisposeModule(self.module);
}
if !self.context.is_null() {
LLVMContextDispose(self.context);
}
}
}
}

pub struct DiagnosticHandler {
pub(crate) has_errors: bool,
}

impl DiagnosticHandler {
pub fn new() -> Self {
Self { has_errors: false }
}
}

impl llvm::LLVMDiagnosticHandler for DiagnosticHandler {
fn handle_diagnostic(&mut self, severity: llvm_sys::LLVMDiagnosticSeverity, message: &str) {
// TODO(https://reviews.llvm.org/D155894): Remove this when LLVM no longer emits these
// errors.
Expand Down Expand Up @@ -586,22 +612,6 @@ impl llvm::LLVMDiagnosticHandler for Linker {
}
}

impl Drop for Linker {
fn drop(&mut self) {
unsafe {
if !self.target_machine.is_null() {
LLVMDisposeTargetMachine(self.target_machine);
}
if !self.module.is_null() {
LLVMDisposeModule(self.module);
}
if !self.context.is_null() {
LLVMContextDispose(self.context);
}
}
}
}

fn detect_input_type(data: &[u8]) -> Option<InputType> {
if data.len() < 8 {
return None;
Expand Down

0 comments on commit c9a7d33

Please sign in to comment.