Skip to content

Commit af83ee9

Browse files
authored
Merge pull request #321 from MediosZ/handle_rs_errors
Improve error handling in rs_loader.
2 parents c2c097e + 157b7e0 commit af83ee9

File tree

17 files changed

+187
-99
lines changed

17 files changed

+187
-99
lines changed

source/loaders/rs_loader/rust/compiler/src/api/function.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ extern "C" fn function_singleton_invoke(
3333
unsafe {
3434
let args = std::slice::from_raw_parts(args_p, size).to_vec();
3535
let nf = Box::from_raw(func_impl as *mut class::NormalFunction);
36-
let res = nf.invoke(args).unwrap();
36+
let res = nf.invoke(args).expect("Function return error");
3737

3838
std::mem::forget(nf);
3939
res
@@ -118,8 +118,7 @@ pub fn register_function(function_registration: FunctionRegistration) {
118118
loader_impl_type(function_registration.loader_impl, ret.as_ptr()),
119119
);
120120
};
121-
}
122-
else {
121+
} else {
123122
let ret = CString::new("Null").expect("Failed to convert return type to C string");
124123

125124
unsafe {

source/loaders/rs_loader/rust/compiler/src/lib.rs

Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,15 @@ impl Source {
104104

105105
match source {
106106
Source::File { ref path } => {
107-
let dir = PathBuf::from(path.clone().parent().unwrap());
108-
let name = PathBuf::from(path.file_name().unwrap());
107+
let dir = PathBuf::from(
108+
path.clone()
109+
.parent()
110+
.expect(format!("Unable to get the parent of {:?}", path).as_str()),
111+
);
112+
let name = PathBuf::from(
113+
path.file_name()
114+
.expect(format!("Unable to get the filename of {:?}", path).as_str()),
115+
);
109116

110117
SourceImpl {
111118
input: SourceInput(config::Input::File(path.clone())),
@@ -129,8 +136,15 @@ impl Source {
129136
}
130137
}
131138
Source::Package { ref path } => {
132-
let dir = PathBuf::from(path.clone().parent().unwrap());
133-
let name = PathBuf::from(path.file_name().unwrap());
139+
let dir = PathBuf::from(
140+
path.clone()
141+
.parent()
142+
.expect(format!("Unable to get the parent of {:?}", path).as_str()),
143+
);
144+
let name = PathBuf::from(
145+
path.file_name()
146+
.expect(format!("Unable to get the filename of {:?}", path).as_str()),
147+
);
134148

135149
SourceImpl {
136150
input: SourceInput(config::Input::File(path.clone())),
@@ -252,7 +266,7 @@ impl DlopenLibrary {
252266
let dll_opening_error = format!(
253267
"{}\nrs_loader was unable to open the dll with the following path: `{}`",
254268
error,
255-
path_to_dll.to_str().unwrap()
269+
path_to_dll.to_str().expect("Unable to cast pathbuf to str")
256270
);
257271

258272
return Err(dll_opening_error)
@@ -387,7 +401,11 @@ impl CompilerCallbacks {
387401
.borrow_mut()
388402
.access(|resolver| {
389403
let c_store = resolver.cstore().clone();
390-
c_store.crates_untracked().last().cloned().unwrap()
404+
c_store
405+
.crates_untracked()
406+
.last()
407+
.cloned()
408+
.expect("Unable to get last element of crates.")
391409
});
392410
queries
393411
.global_ctxt()
@@ -686,10 +704,10 @@ struct DiagnosticSink(sync::Arc<sync::Mutex<Vec<u8>>>);
686704

687705
impl std::io::Write for DiagnosticSink {
688706
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
689-
self.0.lock().unwrap().write(buf)
707+
self.0.lock().expect("Unable to acquire lock").write(buf)
690708
}
691709
fn flush(&mut self) -> std::io::Result<()> {
692-
self.0.lock().unwrap().flush()
710+
self.0.lock().expect("Unable to acquire lock").flush()
693711
}
694712
}
695713

@@ -857,12 +875,23 @@ pub fn compile(source: SourceImpl) -> Result<CompilerState, CompilerError> {
857875
Ok(()) => Ok(()),
858876
Err(err) => {
859877
// Read buffered diagnostics
860-
let diagnostics =
861-
String::from_utf8(diagnostics_buffer.lock().unwrap().clone()).unwrap();
878+
let diagnostics = String::from_utf8(
879+
diagnostics_buffer
880+
.lock()
881+
.expect("Unable to acquire lock")
882+
.clone(),
883+
)
884+
.expect("Unable to get string from utf8");
862885
eprintln!("{}", diagnostics);
863886

864887
// Read buffered errors
865-
let errors = String::from_utf8(errors_buffer.lock().unwrap().clone()).unwrap();
888+
let errors = String::from_utf8(
889+
errors_buffer
890+
.lock()
891+
.expect("Unable to acquire lock")
892+
.clone(),
893+
)
894+
.expect("Unable to get string from utf8");
866895
eprintln!("{}", errors);
867896

868897
return Err(CompilerError {
@@ -877,7 +906,7 @@ pub fn compile(source: SourceImpl) -> Result<CompilerState, CompilerError> {
877906
return Err(e);
878907
}
879908

880-
let mut patched_callback = generate_wrapper(callbacks).unwrap();
909+
let mut patched_callback = generate_wrapper(callbacks).expect("Unable to generate wrapper");
881910

882911
// generate binary
883912
match rustc_driver::catch_fatal_errors(|| {
@@ -892,12 +921,23 @@ pub fn compile(source: SourceImpl) -> Result<CompilerState, CompilerError> {
892921
}),
893922
Err(err) => {
894923
// Read buffered diagnostics
895-
let diagnostics =
896-
String::from_utf8(diagnostics_buffer.lock().unwrap().clone()).unwrap();
924+
let diagnostics = String::from_utf8(
925+
diagnostics_buffer
926+
.lock()
927+
.expect("Unable to acquire lock")
928+
.clone(),
929+
)
930+
.expect("Unable to get string from utf8");
897931
eprintln!("{}", diagnostics);
898932

899933
// Read buffered errors
900-
let errors = String::from_utf8(errors_buffer.lock().unwrap().clone()).unwrap();
934+
let errors = String::from_utf8(
935+
errors_buffer
936+
.lock()
937+
.expect("Unable to acquire lock")
938+
.clone(),
939+
)
940+
.expect("Unable to get string from utf8");
901941
eprintln!("{}", errors);
902942

903943
Err(CompilerError {

source/loaders/rs_loader/rust/compiler/src/registrator.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ fn function_create(func: &Function, dlopen_library: &DlopenLibrary) -> FunctionC
1111

1212
let register_func_name = format!("metacall_register_fn_{}", name);
1313
let register_func: unsafe fn() -> *mut class::NormalFunction =
14-
unsafe { dlopen_library.instance.symbol(&register_func_name[..]) }.unwrap();
14+
unsafe { dlopen_library.instance.symbol(&register_func_name[..]) }
15+
.expect(format!("Unable to find register function {}", name).as_str());
1516
let function_impl = unsafe { register_func() } as OpaqueType;
1617
FunctionCreate {
1718
name,
@@ -25,7 +26,8 @@ fn class_create(class: &Class, dlopen_library: &DlopenLibrary) -> ClassCreate {
2526
let name = class.name.clone();
2627
let register_func_name = format!("metacall_register_class_{}", name);
2728
let register_func: unsafe fn() -> *mut class::Class =
28-
unsafe { dlopen_library.instance.symbol(&register_func_name[..]) }.unwrap();
29+
unsafe { dlopen_library.instance.symbol(&register_func_name[..]) }
30+
.expect(format!("Unable to find register function {}", name).as_str());
2931
let class_impl = unsafe { register_func() } as OpaqueType;
3032
ClassCreate {
3133
name,

source/loaders/rs_loader/rust/compiler/src/wrapper/class.rs

Lines changed: 60 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ use std::cell::Ref;
33
use std::cell::RefCell;
44
use std::cell::RefMut;
55
use std::collections::HashMap;
6+
use std::convert::TryInto;
67
use std::ffi::CStr;
78
use std::fmt;
89
use std::sync::Arc;
9-
use std::convert::TryInto;
1010
type Result<T, E = i32> = core::result::Result<T, E>;
1111
use std::os::raw::{c_char, c_double, c_float, c_int, c_long, c_short, c_void};
1212
extern "C" {
@@ -62,11 +62,18 @@ impl Class {
6262
}
6363

6464
pub fn init(&self, fields: Vec<MetacallValue>) -> Instance {
65-
self.constructor.as_ref().unwrap().invoke(fields).unwrap()
65+
self.constructor
66+
.as_ref()
67+
.expect("Unable to get ref of constructor.")
68+
.invoke(fields)
69+
.expect("Invoke return error.")
6670
}
6771

6872
pub fn call(&self, attr: &str, args: Vec<MetacallValue>) -> Result<MetacallValue> {
69-
let attr = self.class_methods.get(attr).unwrap();
73+
let attr = self
74+
.class_methods
75+
.get(attr)
76+
.expect(format!("Unable to get {} from {}", attr, self.name).as_str());
7077

7178
attr.clone().invoke(args)
7279
}
@@ -216,11 +223,19 @@ impl Instance {
216223

217224
/// Lookup an attribute on the instance via the registered `Class`
218225
pub fn get_attr(&self, name: &str, class: &Class) -> Result<MetacallValue> {
219-
let attr = class.attributes.get(name).unwrap().clone();
226+
let attr = class
227+
.attributes
228+
.get(name)
229+
.expect(format!("Unable to find attribute {} from {}", name, self.name()).as_str())
230+
.clone();
220231
attr.invoke(self)
221232
}
222233
pub fn set_attr(&mut self, name: &str, value: MetacallValue, class: &Class) {
223-
let attr = class.attr_setters.get(name).unwrap().clone();
234+
let attr = class
235+
.attr_setters
236+
.get(name)
237+
.expect(format!("Unable to find attribute {} from {}", name, self.name()).as_str())
238+
.clone();
224239
attr.invoke(value, self)
225240
}
226241

@@ -238,7 +253,9 @@ impl Instance {
238253
args: Vec<MetacallValue>,
239254
class: &Class,
240255
) -> Result<MetacallValue> {
241-
let method = class.get_method(name).unwrap();
256+
let method = class
257+
.get_method(name)
258+
.expect(format!("Unable to find method {} from {}", name, self.name()).as_str());
242259
method.invoke(self, args)
243260
}
244261
}
@@ -343,7 +360,9 @@ impl AttributeGetter {
343360
{
344361
Self(Arc::new(move |receiver| {
345362
let borrowed_receiver = receiver.borrow();
346-
let receiver = Ok(borrowed_receiver.downcast_ref::<T>().unwrap());
363+
let receiver = Ok(borrowed_receiver
364+
.downcast_ref::<T>()
365+
.expect("Unable to downcast"));
347366
receiver.map(&f).and_then(|v| v.to_meta_result())
348367
}))
349368
}
@@ -364,7 +383,9 @@ impl AttributeSetter {
364383
{
365384
Self(Arc::new(move |value, receiver| {
366385
let mut borrowed_receiver = receiver.borrow_mut();
367-
let receiver = borrowed_receiver.downcast_mut::<T>().unwrap();
386+
let receiver = borrowed_receiver
387+
.downcast_mut::<T>()
388+
.expect("Unable to downcast");
368389
f(FromMeta::from_meta(value).unwrap(), receiver)
369390
}))
370391
}
@@ -388,7 +409,9 @@ impl InstanceMethod {
388409
Self(Arc::new(
389410
move |receiver: &Instance, args: Vec<MetacallValue>| {
390411
let borrowed_receiver = receiver.borrow();
391-
let receiver = Ok(borrowed_receiver.downcast_ref::<T>().unwrap());
412+
let receiver = Ok(borrowed_receiver
413+
.downcast_ref::<T>()
414+
.expect("Unable to downcast"));
392415

393416
let args = Args::from_meta_list(&args);
394417

@@ -605,11 +628,21 @@ impl TryFrom<i32> for PrimitiveMetacallProtocolTypes {
605628

606629
fn try_from(v: i32) -> Result<Self, Self::Error> {
607630
match v {
608-
x if x == PrimitiveMetacallProtocolTypes::Short as i32 => Ok(PrimitiveMetacallProtocolTypes::Short),
609-
x if x == PrimitiveMetacallProtocolTypes::Int as i32 => Ok(PrimitiveMetacallProtocolTypes::Int),
610-
x if x == PrimitiveMetacallProtocolTypes::Long as i32 => Ok(PrimitiveMetacallProtocolTypes::Long),
611-
x if x == PrimitiveMetacallProtocolTypes::Float as i32 => Ok(PrimitiveMetacallProtocolTypes::Float),
612-
x if x == PrimitiveMetacallProtocolTypes::Double as i32 => Ok(PrimitiveMetacallProtocolTypes::Double),
631+
x if x == PrimitiveMetacallProtocolTypes::Short as i32 => {
632+
Ok(PrimitiveMetacallProtocolTypes::Short)
633+
}
634+
x if x == PrimitiveMetacallProtocolTypes::Int as i32 => {
635+
Ok(PrimitiveMetacallProtocolTypes::Int)
636+
}
637+
x if x == PrimitiveMetacallProtocolTypes::Long as i32 => {
638+
Ok(PrimitiveMetacallProtocolTypes::Long)
639+
}
640+
x if x == PrimitiveMetacallProtocolTypes::Float as i32 => {
641+
Ok(PrimitiveMetacallProtocolTypes::Float)
642+
}
643+
x if x == PrimitiveMetacallProtocolTypes::Double as i32 => {
644+
Ok(PrimitiveMetacallProtocolTypes::Double)
645+
}
613646
_ => Err(()),
614647
}
615648
}
@@ -621,11 +654,17 @@ macro_rules! convert_to {
621654
let id = value_type_id($val);
622655

623656
match id.try_into() {
624-
Ok(PrimitiveMetacallProtocolTypes::Short) => Ok(metacall_value_to_short($val) as $t),
657+
Ok(PrimitiveMetacallProtocolTypes::Short) => {
658+
Ok(metacall_value_to_short($val) as $t)
659+
}
625660
Ok(PrimitiveMetacallProtocolTypes::Int) => Ok(metacall_value_to_int($val) as $t),
626661
Ok(PrimitiveMetacallProtocolTypes::Long) => Ok(metacall_value_to_long($val) as $t),
627-
Ok(PrimitiveMetacallProtocolTypes::Float) => Ok(metacall_value_to_float($val) as $t),
628-
Ok(PrimitiveMetacallProtocolTypes::Double) => Ok(metacall_value_to_double($val) as $t),
662+
Ok(PrimitiveMetacallProtocolTypes::Float) => {
663+
Ok(metacall_value_to_float($val) as $t)
664+
}
665+
Ok(PrimitiveMetacallProtocolTypes::Double) => {
666+
Ok(metacall_value_to_double($val) as $t)
667+
}
629668
Err(_) => {
630669
println!("receive id: {}, should be [2-6]", id);
631670
panic!("received mismatch type");
@@ -670,7 +709,10 @@ impl FromMeta for String {
670709
fn from_meta(val: MetacallValue) -> Result<Self> {
671710
Ok(unsafe {
672711
let s = metacall_value_to_string(val);
673-
CStr::from_ptr(s).to_str().unwrap().to_owned()
712+
CStr::from_ptr(s)
713+
.to_str()
714+
.expect("Unable to cast Cstr to str")
715+
.to_owned()
674716
})
675717
}
676718
}

source/loaders/rs_loader/rust/compiler/src/wrapper/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ pub fn generate_wrapper(callbacks: CompilerCallbacks) -> std::io::Result<Compile
174174
.file_name()
175175
.expect("not a file")
176176
.to_str()
177-
.unwrap()
177+
.expect("Unable to cast OsStr to str")
178178
.to_owned();
179179
let _ = source_path.pop();
180180

source/loaders/rs_loader/rust/src/lib.rs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,3 @@
1-
pub use std::ffi::c_void;
2-
pub use std::ffi::CStr;
3-
pub use std::os::raw::c_char;
4-
pub use std::os::raw::c_int;
5-
pub use std::path::PathBuf;
6-
71
mod lifecycle;
82

93
pub use lifecycle::rs_loader_impl_clear;

source/loaders/rs_loader/rust/src/lifecycle/clear.rs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use super::loader::LoadingMethod;
2-
use crate::{c_int, c_void};
2+
use std::os::raw::{c_int, c_void};
33

44
use compiler::api;
55

@@ -10,18 +10,16 @@ pub extern "C" fn rs_loader_impl_clear(loader_impl: *mut c_void, handle: *mut c_
1010
.as_mut()
1111
.expect("Unable to get loader state")
1212
};
13-
unsafe {
14-
let methods = Box::from_raw(handle as *mut Vec<LoadingMethod>);
15-
for loading_method in *methods {
16-
match loading_method.consume_dlib() {
17-
Ok(lib) => {
18-
// extend the lifetime of library
19-
loader_lifecycle_state.destroy_list.push(lib);
20-
}
21-
Err(err) => {
22-
eprintln!("{}", err);
23-
return 1 as c_int;
24-
}
13+
let methods = unsafe { Box::from_raw(handle as *mut Vec<LoadingMethod>) };
14+
for loading_method in *methods {
15+
match loading_method.consume_dlib() {
16+
Ok(lib) => {
17+
// extend the lifetime of library
18+
loader_lifecycle_state.destroy_list.push(lib);
19+
}
20+
Err(err) => {
21+
eprintln!("{}", err);
22+
return 1 as c_int;
2523
}
2624
}
2725
}

0 commit comments

Comments
 (0)