Skip to content

Commit

Permalink
Merge pull request #452 from madsmtm/doc
Browse files Browse the repository at this point in the history
Improve examples and remove words that downplay the difficulty of a given task
  • Loading branch information
madsmtm authored Jun 16, 2023
2 parents 1c3f05c + d5a6ccf commit ee2afe2
Show file tree
Hide file tree
Showing 73 changed files with 419 additions and 342 deletions.
35 changes: 19 additions & 16 deletions crates/block-sys/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,27 @@ see that for related crates.

## Runtime Support

This library is basically just a raw interface to the aptly specified [Blocks
ABI](https://clang.llvm.org/docs/Block-ABI-Apple.html). However, different
runtime implementations exist and act in slightly different ways (and have
several different helper functions), the most important aspect being that the
libraries are named differently, so the linking must take that into account.

The user can choose the desired runtime by using the relevant cargo feature
flags, see the following sections (might have to disable the default `apple`
This library is a raw interface to the aptly specified [Blocks ABI][abi].
However, different runtime implementations exist and act in slightly different
ways (and have several different helper functions), the most important aspect
being that the libraries are named differently, so the linking must take that
into account.

You can choose the desired runtime by using the relevant cargo feature flags,
see the following sections (you might have to disable the default `apple`
feature first). Note that if the `objc-sys` crate is present in the module
tree, this should have the same feature flag enabled as that.


[abi]: https://clang.llvm.org/docs/Block-ABI-Apple.html


### Apple's [`libclosure`](https://github.com/apple-oss-distributions/libclosure)

- Feature flag: `apple`.

This is naturally the most sophisticated runtime, and it has quite a lot more
features than the specification mandates. This is used by default.
This is the most sophisticated runtime, and it has quite a lot more features
than the specification mandates. It is used by default.

The minimum required operating system versions are as follows:
- macOS: `10.6`
Expand All @@ -45,11 +48,11 @@ Though in practice Rust itself requires higher versions than this.

- Feature flag: `compiler-rt`.

This is effectively just a copy of Apple's older (around macOS 10.6) runtime,
and is now used in [Swift's `libdispatch`] and [Swift's Foundation] as well.
This is a copy of Apple's older (around macOS 10.6) runtime, and is now used
in [Swift's `libdispatch`] and [Swift's Foundation] as well.

This can be easily used on many Linux systems with the `libblocksruntime-dev`
package.
The runtime and associated headers can be installed on many Linux systems with
the `libblocksruntime-dev` package.

Using this runtime probably won't work together with `objc-sys` crate.

Expand Down Expand Up @@ -77,8 +80,8 @@ Sources:

**Unstable: Hasn't been tested on Windows yet!**

Essentially just [a fork](https://github.com/microsoft/libobjc2) based on
GNUStep's `libobjc2` version 1.8.
[A fork](https://github.com/microsoft/libobjc2) based on GNUStep's `libobjc2`
version 1.8.


### [`ObjFW`](https://github.com/ObjFW/ObjFW)
Expand Down
9 changes: 5 additions & 4 deletions crates/block-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,12 @@ fn main() {

match (apple, compiler_rt, gnustep, objfw) {
(true, false, false, false) => {
// Link to libclosure (internally called libsystem_blocks), which is
// exported by libSystem.dylib.
// Link to libclosure (internally called libsystem_blocks), which
// is exported by libSystem.dylib.
//
// Note that System.framework is just a deprecated wrapper over the
// dynamic library.
// Note: Don't get confused by the presence of `System.framework`,
// it is a deprecated wrapper over the dynamic library, so we'd
// rather use the latter.
println!("cargo:rustc-link-lib=dylib=System");
// Alternative: Only link to libsystem_blocks.dylib
// println!("cargo:rustc-link-search=native=/usr/lib/system");
Expand Down
3 changes: 2 additions & 1 deletion crates/block-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,8 @@ pub struct Block_layout {
/// }
/// ```
///
/// But it is safe to access this through just `Block_descriptor_header`.
/// But since all of these start with `Block_descriptor_header`, it is
/// always safe to reinterpret this pointer as that.
// Note: Important to use `*const c_void` until we know which type it is!
pub descriptor: *const c_void,
}
Expand Down
4 changes: 2 additions & 2 deletions crates/block2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

Apple's C language extension of blocks in Rust.

This crate provides functionality for interracting with C blocks, which is
effectively the C-equivalent of Rust's closures.
This crate provides functionality for interracting with C blocks, which is the
C-equivalent of Rust's closures.

They are _technically_ not limited to only being used in Objective-C, though
in practice it's likely the only place you'll ever encounter them.
Expand Down
6 changes: 3 additions & 3 deletions crates/block2/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,9 @@ block_args_impl!(
#[repr(C)]
pub struct Block<A, R> {
_inner: [u8; 0],
// We effectively store `Block_layout` + a bit more, but `Block` has to
// remain an empty type otherwise the compiler thinks we only have
// provenance over `Block_layout`.
// We store `Block_layout` + a bit more, but `Block` has to remain an
// empty type otherwise the compiler thinks we only have provenance over
// `Block_layout`.
_layout: PhantomData<ffi::Block_layout>,
// To get correct variance on args and return types
_p: PhantomData<fn(A) -> R>,
Expand Down
2 changes: 1 addition & 1 deletion crates/block2/src/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const GLOBAL_DESCRIPTOR: ffi::Block_descriptor_header = ffi::Block_descriptor_he

/// An Objective-C block that does not capture its environment.
///
/// This is effectively just a glorified function pointer, and can created and
/// This is effectively a glorified function pointer, and can created and
/// stored in static memory using the [`global_block!`] macro.
///
/// If [`ConcreteBlock`] is the [`Fn`]-block equivalent, this is likewise the
Expand Down
4 changes: 2 additions & 2 deletions crates/block2/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! # Apple's C language extension of blocks
//!
//! C Blocks are effectively the C-equivalent of Rust's closures, in that they
//! have the ability to capture their environments.
//! C Blocks are the C-equivalent of Rust's closures, in that they have the
//! ability to capture their environments.
//!
//! This crate provides capabilities to create and invoke these blocks, in an
//! ergonomic "Rust-centric" fashion.
Expand Down
2 changes: 1 addition & 1 deletion crates/header-translator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ cargo run --bin header-translator

Make sure you have the same XCode version installed as the one documented in [`crates/icrate/README.md`](../icrate/README.md).

If you use a different operating system than macOS, or simply have multiple SDKs installed, you can specify the directory as the first argument:
If you use a different operating system than macOS, or have multiple SDKs installed, you can specify the directory as the first argument:

```console
cargo run --bin header-translator -- /Applications/Xcode_new.app/Contents/Developer
Expand Down
7 changes: 3 additions & 4 deletions crates/header-translator/src/data/CoreAnimation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ data! {
// `nil` superlayer.

// If the layer already has a superlayer, it will be changed
// appropriately by these methods (effectively, removeFromSuperlayer
// is called on the given layer inside these).
// appropriately by these methods (`removeFromSuperlayer` is called on
// the given layer inside these).
unsafe -addSublayer;
unsafe -insertSublayer_atIndex;
unsafe -insertSublayer_below;
Expand Down Expand Up @@ -193,8 +193,7 @@ data! {
unsafe -endFrame;
}

// SAFETY: CATransaction is basically just a way to call methods that
// access thread-local state.
// SAFETY: CATransaction methods access thread-local state.
class CATransaction {
unsafe +begin;
unsafe +commit;
Expand Down
2 changes: 1 addition & 1 deletion crates/header-translator/src/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ impl MemoryManagement {
// And if:
// > its signature obeys the added restrictions of the method family.
//
// Which is just:
// Which is:
// > must return a retainable object pointer
if result_type.is_id() {
// We also check that the correct modifier flags were set for the
Expand Down
2 changes: 1 addition & 1 deletion crates/header-translator/src/rust_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl AttributeParser<'_, '_> {
if position.strip(self.expected_name, needle).is_some() {
let rest = rest.trim();
// If it can be stripped from both `name` and `expected_name`,
// it might just appear twice in `name`.
// it might appear twice in `name`.
//
// This is done to support:
// "const char * _Nonnull _Nonnull[]".
Expand Down
7 changes: 3 additions & 4 deletions crates/header-translator/src/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1467,8 +1467,8 @@ impl fmt::Display for Stmt {
// Copying collections is done as a shallow copy:
// <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Collections/Articles/Copying.html>
//
// E.g. it simply does a retain count bump, and hence
// does not require the inner type to implement
// E.g. it does a retain count bump on the items, and
// hence does not require the inner type to implement
// `NSCopying`.
//
// The types does have to be cloneable, since generic
Expand Down Expand Up @@ -1712,8 +1712,7 @@ impl fmt::Display for Stmt {
writeln!(f, "typed_extensible_enum!(pub type {} = {ty};);", id.name)?;
}
None | Some(UnexposedAttr::BridgedTypedef) => {
// "bridged" typedefs should just use a normal type
// alias.
// "bridged" typedefs should use a normal type alias.
writeln!(f, "pub type {} = {ty};", id.name)?;
}
kind => panic!("invalid alias kind {kind:?} for {ty:?}"),
Expand Down
4 changes: 2 additions & 2 deletions crates/header-translator/translation-config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ ios = "16.0"
### - `ns_returns_retained` / `cf_returns_retained` / `os_returns_retained`
###
### The rest are only very rarely used in Apple's frameworks, so while we
### _could_ handle them too, I think it's easier to just do it manually.
### _could_ handle them too, I think it's easier to do it manually.
###
### See https://clang.llvm.org/docs/AttributeReference.html
###
Expand Down Expand Up @@ -783,7 +783,7 @@ skipped = true
skipped = true

# The original superclass typedef is a bit difficult to extract from the
# superclass name, so let's just overwrite it.
# superclass name, so let's do it manually.
[class.ASCredentialProviderViewController]
definition-skipped = true
[class.ASAccountAuthenticationModificationViewController]
Expand Down
9 changes: 4 additions & 5 deletions crates/icrate/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
* Added `NSTimeInterval`.
* Added `NSString::len_utf16` and `NSAttributedString::len_utf16`.
* Added `NSString::concat` and `NSString::join_path`.
* Added `CGSize`, `CGPoint` and `CGRect` (just aliases to equivalent
`NS`-types, but helps readability).
* Added `CGSize`, `CGPoint` and `CGRect` (aliases to equivalent `NS`-types
that helps readability).

### Changed
* **BREAKING**: `NSSize::new` no longer requires it's arguments to be
Expand Down Expand Up @@ -310,8 +310,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Removed
* `NSObject::hash_code`, `NSObject::is_equal` and `NSObject::description` in
favour of just having the trait implementations `Hash`, `PartiqalEq` and
`Debug`.
favour of having the trait implementations `Hash`, `PartiqalEq` and `Debug`.


## objc2-foundation 0.2.0-alpha.6 - 2022-07-19
Expand Down Expand Up @@ -397,7 +396,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Removed
* **BREAKING**: Removed `Deref` and `DerefMut` from `NSData` and
`NSMutableData`, since these invoke a non-trivial amount of code, and could
easily lead to hard-to-diagnose performance issues.
lead to hard-to-diagnose performance issues.


## objc2-foundation 0.2.0-alpha.3 - 2021-12-22
Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/examples/basic_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn main() {
autoreleasepool(|pool| {
println!("{}", string.as_str(pool));
});
// Or simply use the `Display` implementation
// Or use the `Display` implementation
let _s = string.to_string(); // Using ToString
println!("{string}"); // Or Display directly

Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/examples/nspasteboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use objc2::rc::Id;
use objc2::runtime::{Class, Object, ProtocolObject};
use objc2::ClassType;

/// Simple, straightforward implementation
/// Simplest implementation
pub fn get_text_1(pasteboard: &NSPasteboard) -> Option<Id<NSString>> {
unsafe { pasteboard.stringForType(NSPasteboardTypeString) }
}
Expand Down
3 changes: 1 addition & 2 deletions crates/icrate/src/Foundation/__macro_helpers/cached.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ impl<T: Message> CachedId<T> {
let ptr = self.ptr.load(Ordering::SeqCst);
// SAFETY: The pointer is either NULL, or has been created below.
unsafe { ptr.as_ref() }.unwrap_or_else(|| {
// "Forget" about releasing the object, effectively promoting it
// to a static.
// "Forget" about releasing the object, promoting it to a static.
let s = ManuallyDrop::new(f());
let ptr = Id::as_ptr(&s);
self.ptr.store(ptr as *mut T, Ordering::SeqCst);
Expand Down
6 changes: 3 additions & 3 deletions crates/icrate/src/Foundation/__macro_helpers/ns_string.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![cfg(feature = "Foundation_NSString")]
//! Macro for making a static NSString.
//!
//! This basically does what clang does, see:
//! This closely follows what clang does, see:
//! - Apple: <https://github.com/llvm/llvm-project/blob/release/13.x/clang/lib/CodeGen/CodeGenModule.cpp#L5057-L5249>
//! - GNUStep 2.0 (not yet supported): <https://github.com/llvm/llvm-project/blob/release/13.x/clang/lib/CodeGen/CGObjCGNU.cpp#L973-L1118>
//! - Other (not yet supported): <https://github.com/llvm/llvm-project/blob/release/13.x/clang/lib/CodeGen/CGObjCGNU.cpp#L2471-L2507>
Expand Down Expand Up @@ -39,8 +39,8 @@ extern "C" {
#[repr(C)]
pub struct CFConstString {
isa: &'static Class,
// Important that we don't just use `usize` here, since that would be
// wrong on big-endian systems!
// Important that we don't use `usize` here, since that would be wrong on
// big-endian systems!
cfinfo: u32,
#[cfg(target_pointer_width = "64")]
_rc: u32,
Expand Down
4 changes: 2 additions & 2 deletions crates/icrate/src/Foundation/additions/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl NSData {
// bug; it forgets to assign the input buffer and length to the
// instance before it swizzles to NSDataWithDeallocatorBlock.
// See https://github.com/gnustep/libs-base/pull/213
// So we just use NSDataWithDeallocatorBlock directly.
// So instead we use NSDataWithDeallocatorBlock directly.
//
// NSMutableData does not have this problem.
#[cfg(feature = "gnustep-1-7")]
Expand Down Expand Up @@ -112,7 +112,7 @@ impl NSMutableData {
#[doc(alias = "replaceBytesInRange:withBytes:length:")]
pub fn replace_range(&mut self, range: Range<usize>, bytes: &[u8]) {
// No need to verify the length of the range here,
// `replaceBytesInRange:` just zero-fills if out of bounds.
// `replaceBytesInRange:` zero-fills if out of bounds.
let ptr = bytes.as_ptr() as *mut c_void;
unsafe { self.replaceBytesInRange_withBytes_length(range.into(), ptr, bytes.len()) }
}
Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/src/Foundation/additions/dictionary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ unsafe impl<K: Message, V: Message> iter::FastEnumerationHelper for NSDictionary

#[cfg(feature = "Foundation_NSMutableDictionary")]
unsafe impl<K: Message, V: Message> iter::FastEnumerationHelper for NSMutableDictionary<K, V> {
// Naturally, the same goes for mutable dictionaries.
// The same goes for mutable dictionaries.
type Item = K;

#[inline]
Expand Down
14 changes: 7 additions & 7 deletions crates/icrate/src/Foundation/additions/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ type InnerFloat = f32;
// TODO: Use a newtype here?
pub type CGFloat = InnerFloat;

// NSGeometry types are just aliases to CGGeometry types on iOS, tvOS, watchOS
// and macOS 64bit (and hence their Objective-C encodings are different).
// NSGeometry types are aliases to CGGeometry types on iOS, tvOS, watchOS and
// macOS 64bit (and hence their Objective-C encodings are different).
//
// TODO: Adjust `objc2-encode` so that this is handled there, and so that we
// can effectively just forget about it and use `NS` and `CG` types equally.
// can effectively forget about it and use `NS` and `CG` types equally.
#[cfg(all(
feature = "apple",
not(all(target_os = "macos", target_pointer_width = "32"))
Expand Down Expand Up @@ -346,23 +346,23 @@ impl CGRect {

/// A point in a Cartesian coordinate system.
///
/// This is just a convenience alias for [`CGPoint`]. For ease of use, it is
/// This is a convenience alias for [`CGPoint`]. For ease of use, it is
/// available on all platforms, though in practice it is only useful on macOS.
///
/// See [Apple's documentation](https://developer.apple.com/documentation/foundation/nspoint?language=objc).
pub type NSPoint = CGPoint;

/// A two-dimensional size.
///
/// This is just a convenience alias for [`CGSize`]. For ease of use, it is
/// This is a convenience alias for [`CGSize`]. For ease of use, it is
/// available on all platforms, though in practice it is only useful on macOS.
///
/// See [Apple's documentation](https://developer.apple.com/documentation/foundation/nssize?language=objc).
pub type NSSize = CGSize;

/// A rectangle.
///
/// This is just a convenience alias for [`CGRect`]. For ease of use, it is
/// This is a convenience alias for [`CGRect`]. For ease of use, it is
/// available on all platforms, though in practice it is only useful on macOS.
///
/// See [Apple's documentation](https://developer.apple.com/documentation/foundation/nsrect?language=objc).
Expand Down Expand Up @@ -406,7 +406,7 @@ mod tests {
use crate::Foundation::{NSEqualPoints, NSEqualRects, NSEqualSizes};

// We assume that comparisons handle e.g. `x` and `y` in the same way,
// therefore we just set the coordinates / dimensions to the same.
// therefore we set the coordinates / dimensions to the same.
let cases: &[(CGFloat, CGFloat)] = &[
(0.0, 0.0),
(-0.0, -0.0),
Expand Down
2 changes: 1 addition & 1 deletion crates/icrate/src/Foundation/additions/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ impl FastEnumeratorHelper {
// violated, but if that is the case, the program already
// has UB, so then it is better that we detect it.
//
// - The value is a simple integer, so is always initialized.
// - The value is an integer, so is always initialized.
//
//
// We do an unaligned read here since we have no guarantees
Expand Down
4 changes: 2 additions & 2 deletions crates/icrate/src/Foundation/additions/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ use objc2::encode::Encoding;
use crate::common::*;
use crate::Foundation::{CGFloat, NSNumber};

// SAFETY: `NSNumber` is just a wrapper around an integer/float/bool, and it
// is immutable.
// SAFETY: `NSNumber` is a wrapper around an integer/float/bool, and it is
// immutable.
unsafe impl Sync for NSNumber {}
unsafe impl Send for NSNumber {}

Expand Down
Loading

0 comments on commit ee2afe2

Please sign in to comment.