objc2 icon indicating copy to clipboard operation
objc2 copied to clipboard

Better error handling in `msg_send!` and `msg_send_id!`

Open madsmtm opened this issue 1 year ago • 0 comments

Background

Many methods take an NSError** as their last parameter, which is used to communicate errors to the caller, see Error Handling Programming Guide For Cocoa.

Swift has a convention for when they convert such methods, we should have something similar.

Note that only methods that return BOOL or an instance are supported, because, as per the documentation:

Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.

Examples of a few different methods in Foundation that return errors:

Implementation

The idea is that we change msg_send! and msg_send_id! to support specifying error: _ as the last part of the selector (_ is not a valid expresion, so this is easy to distinguish), and if so, performs either a BOOL != NO check, or a NULL check, and returns a Result with the desired value or the error. Example:

fn myMethodThatReturnsError(&self, that_returns: i32) -> Result<(), Id<NSError, Shared>> {
    unsafe { msg_send![self, myMethod: that_returns, error: _] }
}

This way, it is very easy to specify, while also only happening if the user explicitly requests it!

TODO

I still need to figure out how out and inout parameters work ABI-wise:

  • https://stackoverflow.com/questions/5609564/objective-c-in-out-inout-byref-byval-and-so-on-what-are-they
  • https://developer.apple.com/documentation/swift/manual-memory-management
  • https://developer.apple.com/documentation/swift/autoreleasingunsafemutablepointer
  • https://docs.swift.org/swift-book/LanguageGuide/Functions.html#ID173
  • -[NSCalendar getEra:yearForWeekOfYear:weekOfYear:weekday:fromDate:]

Also important to know for #264.

madsmtm avatar Oct 05 '22 18:10 madsmtm