abi_stable/proc_macro_reexports/
stable_abi_derive.rs

1/**
2
3The StableAbi derive macro allows one to implement the [`StableAbi trait`] to :
4
5- Assert that the type has a stable representation across Rust version/compiles.
6
7- Produce the layout of the type at runtime to check it against the loaded library.
8
9# Caveats 
10
11Due to how this macro is implemented, using `Self` in bounds doesn't work,
12you must use the full type name and generic arguments.
13
14# Container Attributes
15
16These helper attributes are applied on the type declaration.
17
18###  `#[sabi(phantom_field(name: type))]` 
19
20Adds a virtual field to the type layout constant,
21which is checked against the phantom field that was declared in the same order 
22for compatibility.
23
24###  `#[sabi(phantom_type_param = type)]` 
25
26Adds a virtual type parameter to the type layout constant,
27which is checked for compatibility.
28
29###  `#[sabi(phantom_const_param = constant expression)]` 
30
31Adds a virtual const parameter to the type layout constant,
32which is checked for equality with the virtual const parameter declared in the same order.
33
34The parameter must implement `StableAbi + Eq + Debug`.
35
36<span id = "not_stableabi_attr"></span>
37###  `#[sabi(not_stableabi(TypeParameter))]`  
38
39Replaces the implicit `TypeParameter: `[`StableAbi`](trait@StableAbi) constraint
40with a `TypeParameter: `[`GetStaticEquivalent_`] constraint.
41
42###  `#[sabi(unsafe_unconstrained(TypeParameter))]`  
43
44Removes the implicit `TypeParameter: `[`StableAbi`](trait@StableAbi) constraint.
45
46The type parameter will be ignored when determining whether the type 
47has already been checked, when loading a dynamic library,
48
49Don't use this if transmuting this type to have different type parameters,
50only changing the `#[sabi(unsafe_unconstrained())]` one,
51would cause Undefined Behavior.
52
53This is only necessary if you are passing `TypeParameter` to [`UnsafeIgnoredType`]
54
55###  `#[sabi(bound(Type: ATrait))]` 
56
57Adds a bound to the [`StableAbi`](trait@StableAbi) impl.
58
59###  `#[sabi(bounds(Type: ATrait, Type2: OtherTrait))]` 
60
61Adds many bounds to the [`StableAbi`](trait@StableAbi) impl.
62
63<span id = "prefix_bound_attr"></span>
64###  `#[sabi(prefix_bound(Type: ATrait))]` 
65
66This is only valid for Prefix types, declared with [`#[sabi(kind(Prefix(..)))]`](#sabi_kind_prefix_attr).
67
68Adds a bound to the [`PrefixTypeTrait`] impl (for the deriving type).
69
70###  `#[sabi(prefix_bounds(Type: ATrait, Type2: OtherTrait))]` 
71
72This is only valid for Prefix types, declared with [`#[sabi(kind(Prefix(..)))]`](#sabi_kind_prefix_attr).
73
74Adds many bounds to the [`PrefixTypeTrait`] impl (for the deriving type).
75
76### `#[sabi(unsafe_allow_type_macros)]`
77
78This allows type macros to be used alongside the StableAbi derive macro.
79
80The reason this is unsafe to enable them is because StableAbi cannot currently 
81analize the lifetimes within macros,
82which means that if any lifetime argument inside the macro invocation changes
83it won't be checked by the runtime type checker.
84
85A type macro is any macro that evaluates to a type.
86
87###  `#[sabi(tag = some_expr)]` 
88
89Adds a [`Tag`](crate::type_layout::Tag) associated with the type,
90a dynamically typed data structure used to encode extra properties about a type.
91
92This can only be done once,
93to add multiple properties you must to use any of a map, an array, or a set.
94
95You can only rely on tags for safety if 
96the specific tags were present since the first compatible version of the library,
97otherwise this only guarantees compatibility between parent and child libraries,
98not sibling libraries.
99
100Parent means the library/binary that loaded a library,
101or the parents of that one.
102
103Sibling means libraries loaded at runtime by the same library/binary 
104(or a parent of that one).
105
106For more information about tags, [look here](./type_layout/tagging/index.html)
107
108<span id = "sabi_extra_checks_attr"></span>
109###  `#[sabi(extra_checks = <some_constant_expression>)]` 
110
111Adds an `ExtraChecks` trait object associated with the type,
112which allows encoding and checking extra properties about a type.
113
114`<some_constant_expression>` must be a constant that implements ExtraChecks .
115
116For examples of using this attribute
117[look here](./abi_stability/extra_checks/index.html#examples)
118
119###  `#[sabi(debug_print)]` 
120
121Prints the generated code, stopping compilation.
122
123<span id = "sabi_kind_prefix_attr"></span>
124###  `#[sabi(kind(Prefix( .. )))]` 
125Declares the struct as being a prefix-type.
126
127Arguments (what goes inside `#[sabi(kind(Prefix(   <here>   )))]`):
128
129- `prefix_ref = <Identifier>)` (optional: defaults to `<DerivingType>_Ref`):
130Declares an ffi-safe pointer to a vtable/module,
131that can be extended in semver compatible versions.<br>
132Uses `<Identifier>` as the name of the prefix struct.<br>
133For more details on prefix-types [look here](./docs/prefix_types/index.html)
134
135- `prefix_fields = <Identifier>)` (optional: defaults to `<DerivingType>_Prefix`):<br>
136Declares a struct with all the fields in the deriving type up to (and including)
137the field with the [`#[sabi(last_prefix_field)]`](#sabilast_prefix_field) attribute,
138named `<Identifier>`.
139
140- `prefix_ref_docs = <expression>` (optional, allows multiple):<br>
141Replaces the default documentation for `<DerivingType>_Ref` with the passed-in expresion.<br>
142If this is passed multiple times, then multiple `#[doc = ...]` attributes are emitted.
143
144<span id = "kind_with_non_exhaustive_attr"></span>
145###  `#[sabi(kind(WithNonExhaustive( .. ))]` 
146
147Declares this enum as being nonexhaustive,
148generating items and impls necessary to wrap this enum in the [`NonExhaustive`] type
149to pass it through ffi.
150For more details on nonexhaustive enums [look here](./docs/sabi_nonexhaustive/index.html)
151
152###  `#[sabi(module_reflection(...))]`  
153
154Determines how this type is accessed when treated as a module for reflection.
155
156`#[sabi(module_reflection( Module ))]`<br>
157The default reflection mode, treats its the public fields as module items.
158
159`#[sabi(module_reflection( Opaque ))]`<br>
160Treats this as an empty module.
161
162`#[sabi(module_reflection( Deref ))]`<br>
163Delegates the treatment of this type as a module to the type it dereferences to.
164
165###  `#[sabi(impl_InterfaceType(...))]`  
166
167Implements the [`InterfaceType`] trait for a type,
168defining the usable/required traits when creating a 
169[`DynTrait`]`<_, ThisType>`/[`NonExhaustive`]`<_, _, ThisType>`.
170
171Syntax: `#[sabi(impl_InterfaceType(Trait0, Trait1, ..., TraitN))]`
172
173If a trait is not specified,
174it will not be required when constructing [`DynTrait`]/[`NonExhaustive`],
175and won't be usable afterwards.
176
177<span id = "InterfaceType_traits"> These are the traits you can specify: </span>
178
179- `Send`: Changing this to require/unrequire in minor versions is an abi breaking change.
180
181- `Sync`: Changing this to require/unrequire in minor versions is an abi breaking change.
182
183- `Unpin`: Changing this to require/unrequire in minor versions is an abi breaking change.
184
185- `Clone`
186
187- `Default`
188
189- `Display`
190
191- `Debug`
192
193- `Eq`
194
195- `PartialEq`
196
197- `Ord`
198
199- `PartialOrd`
200
201- `Hash`
202
203- `Deserialize`: corresponds to `serde::Deserialize`
204
205- `Serialize`: corresponds to `serde::Serialize`
206
207- `Iterator`:
208    this type will also have to implement [`abi_stable::erased_types::IteratorItem`].
209
210- `DoubleEndedIterator`:
211    this type will also have to implement [`abi_stable::erased_types::IteratorItem`].
212
213- `FmtWrite`: corresponds to `std::fmt::Write` .
214
215- `IoWrite`: corresponds to `std::io::Write` .
216
217- `IoSeek`: corresponds to `std::io::Seek` .
218
219- `IoRead`: corresponds to `std::io::Read` .
220
221- `IoBufRead`: corresponds to `std::io::BufRead` .
222
223- `Error`: corresponds to `std::error::Error` .
224
225<br>
226Examples:
227
228- `#[sabi(impl_InterfaceType(Send, Sync))]`
229
230- `#[sabi(impl_InterfaceType(Send, Sync, Iterator, DoubleEndedIterator))]`
231
232- `#[sabi(impl_InterfaceType(Clone, Debug, FmtWrite))]`
233
234- `#[sabi(impl_InterfaceType(Clone, Debug, IoWrite, IoRead))]`
235
236###  `#[sabi(unsafe_opaque_fields]`
237
238Does not require any field to implement [`StableAbi`](trait@StableAbi),
239and instead uses the [`StableAbi`](trait@StableAbi) impl of [`UnsafeOpaqueField`]`<FieldType>`.
240
241This is unsafe because the layout of their type won't be verified when loading the library,
242which causes Undefined Behavior if the type has a different layout.
243
244
245###  `#[sabi(unsafe_sabi_opaque_fields)]`
246
247Requires every field to implement [`StableAbi`](trait@StableAbi)(unless overridden),
248but doesn't check their layout.
249
250This is unsafe because the layout of their type won't be verified when loading the library,
251which causes Undefined Behavior if the type has a different layout.
252
253# Field attributes
254
255These helper attributes are applied to fields.
256
257
258###  `#[sabi(rename = ident)]` 
259
260Renames the field in the generated layout information.
261Use this when renaming private fields.
262
263###  `#[sabi(unsafe_change_type = SomeType)]` 
264
265Changes the type of this field in the generated type layout constant to SomeType.
266
267This has the `unsafe` prefix because SomeType is relied on being correct by
268[`StableAbi`](trait@StableAbi).
269
270###  `#[sabi(unsafe_opaque_field)]` 
271
272Does not require the field to implement [`StableAbi`],
273and instead uses the StableAbi impl of [`UnsafeOpaqueField`]`<FieldType>`.
274
275This is unsafe because the layout of the type won't be verified when loading the library,
276which causes Undefined Behavior if the type has a different layout.
277
278###  `#[sabi(unsafe_sabi_opaque_field)]`
279
280Requires the field to implement [`StableAbi`] (unless overridden),
281but doesn't check its layout.
282
283This is unsafe because the layout of the type won't be verified when loading the library,
284which causes Undefined Behavior if the type has a different layout.
285
286###  `#[sabi(bound = SomeBound)]` 
287
288Adds a `TheFieldType: SomeBound` constraint to the [`StableAbi`](trait@StableAbi) impl.
289
290Eg: 
291```ignore
292#[sabi(bound = Debug)]
293name: RStr<'static>,
294```
295adds the `RStr<'static>: Debug` bound to the [`StableAbi`](trait@StableAbi) impl
296
297###  `#[sabi(with_field_indices)]` 
298
299This is only valid for Prefix types, declared with [`#[sabi(kind(Prefix(..)))]`](#sabi_kind_prefix_attr).
300
301Generates associated constants named `field_index_for_<field_name>` with 
302the index of each field in the prefix type.
303Those indices can then be passed to the `abi_stable::prefix_types::panic_on_missing_*` 
304functions to panic on a missing field.
305
306###  `#[sabi(accessor_bound = ATrait)]` 
307
308This is only valid for Prefix types, declared with [`#[sabi(kind(Prefix(..)))]`](#sabi_kind_prefix_attr).
309
310Adds the bound to the field type in the accessor method.
311
312###  `#[sabi(last_prefix_field)]` 
313
314This is only valid for Prefix types, declared with [`#[sabi(kind(Prefix(..)))]`](#sabi_kind_prefix_attr).
315
316Declares that the field it is applied to is the last field in the prefix,
317where every field up to it is guaranteed to exist.
318
319###  `#[sabi(accessible_if = expression)]` 
320
321This is only valid for Prefix types, declared with [`#[sabi(kind(Prefix(..)))]`](#sabi_kind_prefix_attr).
322
323This attribute turns any field conditional based on the const boolean expression 
324(which must be valid a bool constant).
325
326Whether this attribute is aplied to any given prefix field must not change in minor versions.
327
328If `expression` is false, the field won't be accessible,
329and the type of the field can be anything so long as its size and alignment is compatible.
330
331If `expression` is true, the type of the field must be compatible when checking layout.
332
333If this attribute is apllied to prefix fields,
334it will only be compatible with other types if they agree on 
335which accessors are conditional for prefix fields.
336
337Prefix fields with this attribute are made private in the generated
338`<DerivingType>_Prefix` struct, without this attribute they keep the visibility.
339
340To do `#[sabi(accessible_if = <TypeParameter as Trait>::CONSTANT)]` you can use the 
341[`#[sabi(prefix_bound(TypeParameter: Trait))]`](#prefix_bound_attr) helper attribute.
342
343###  `#[sabi(refl(pub_getter = function_name))]` 
344
345Determines the public getter for a field used by reflection.
346
347The function can return either a reference or a value.
348
349# Field and/or Container attributes
350
351###  `#[sabi(missing_field( .. ))]` 
352
353This is only valid for Prefix types,
354declared with [`#[sabi(kind(Prefix(..)))]`](#sabi_kind_prefix_attr).
355
356Determines what happens in the accessor method for a field, when the field is missing.
357The default is that it returns an `Option<FieldType>`,
358returning None if the field is absent, Some(field_value) if it's present.
359
360If the attribute is on the struct, it's applied to all fields(this is overridable)
361after the [`#[sabi(last_prefix_field)]`](#sabilast_prefix_field) attribute.
362
363If the attribute is on a field, it's applied to that field only,
364overriding the setting on the struct.
365
366`#[sabi(missing_field(panic))]`<br>
367Panics if the field doesn't exist, with an informative error message.
368
369`#[sabi(missing_field(option))]`<br>
370Returns None if the field doesn't exist, Some(fieldvalue) if it does.
371This is the default.
372
373`#[sabi(missing_field(with = somefunction))]`<br>
374Returns `somefunction()` if the field doesn't exist.
375
376`#[sabi(missing_field(value = some_expression))]`<br>
377Returns `some_expression` if the field doesn't exist.
378
379`#[sabi(missing_field(default))]`<br>
380Returns `Default::default()` if the field doesn't exist.
381
382# Variant and/or Container attributes
383
384###  `#[sabi(with_constructor)]` 
385
386This is only valid for nonexhaustive enums, 
387declared with [`#[sabi(kind(WithNonExhaustive(..)))]`](#kind_with_non_exhaustive_attr).
388
389Creates constructors for enum variant(s), named the same as the variant(s) with an `_NE` suffix.
390
391This attribute can be overriden on variants(when it was also applied to the Container itself).
392
393For a variant like this:
394`VariantNamed{foo: RString, bar: RBox<Struct>}`
395it would generate an associated function like this(the exact generated code might differ a bit):
396```ignore
397fn VariantNamed_NE(foo: RString, bar: RBox<Struct>) -> Enum_NE {
398    let x = Enum::VariantNamed { foo, bar };
399    NonExhaustive::new(x)
400}
401```
402
403###  `#[sabi(with_boxed_constructor)]` 
404
405This is only valid for nonexhaustive enums, 
406declared with [`#[sabi(kind(WithNonExhaustive(..)))]`](#kind_with_non_exhaustive_attr).
407
408Creates constructors for enum variant(s) which only contain a pointer,
409named the same as the variant(s) with an `_NE` suffix.
410
411This attribute can be overriden on variants(when it was also applied to the Container itself).
412
413All constructor functions are declared inside a single impl block with 
414`Self` bounded by the traits that are necessary to construct [`NonExhaustive`] from it.
415
416For a variant like this:
417
418`VariantNamed(RBox<T>)`
419
420it would generate an associated function like this(the exact generated code might differ a bit):
421```ignore
422fn VariantNamed_NE(value: T) -> Enum_NE<T> {
423    let x = RBox::new(value);
424    let x = Enum::VariantNamed(x);
425    NonExhaustive::new(x)
426}
427```
428
429<br>
430
431For a variant like this:
432
433`VariantNamed{ptr_: MyPointer<T>}`
434
435it would generate an associated function like this(the exact generated code might differ a bit):
436```ignore
437fn VariantNamed_NE(value: T) -> Enum_NE<T> {
438    let x = MyPointer::new(value);
439    let x = Enum::VariantNamed { ptr_: x };
440    NonExhaustive::new(x)
441}
442```
443
444For a variant like this:
445
446`VariantNamed(BoxedStruct)`
447
448it would generate an associated function like this(the exact generated code might differ a bit):
449```ignore
450fn VariantNamed_NE(
451    value: <BoxedStruct as ::std::ops::Deref>::Target,
452) -> Enum_NE<T> {
453    let x = BoxedStruct::new(value);
454    let x = Enum::VariantNamed(x);
455    NonExhaustive::new(x)
456}
457```
458
459
460
461# Supported repr attributes
462
463Because repr attributes can cause the type to change layout,
464the StableAbi derive macro has to know about every repr attribute applied to the type,
465since it might invalidate layout stability.
466
467###  `repr(C)` 
468
469This is the representation that most StableAbi types will have.
470
471###  `repr(transparent)` 
472
473`repr(transparent)` types are supported,
474though their layout is not considered equivalent to their only non-zero-sized field,
475since this library considers all types as being meaningful even if zero-sized.
476
477###  `repr(i8|u8|i16|u16|i32|u32|i64|u64|isize|usize)` 
478
479These repr attributes are only supported for enums.
480
481###  `repr(align(...))` 
482
483
484`repr(align(...))` is supported,
485so long as it is used in combination with the other supported repr attributes.
486
487
488# Examples 
489
490###  Basic example 
491
492```
493
494use abi_stable::StableAbi;
495
496#[repr(C)]
497#[derive(StableAbi)]
498struct Point2D {
499    x: u32,
500    y: u32,
501}
502
503```
504
505###  On a `#[repr(transparent)]` newtype 
506
507```
508
509use abi_stable::StableAbi;
510
511#[repr(transparent)]
512#[derive(StableAbi)]
513pub struct Wrapper<T> {
514    pub inner: T,
515}
516
517
518```
519
520###  On a `#[repr(u8)]` enum.
521
522This enum cannot add variants in minor versions,
523for that you have to use [nonexhaustive enums](./docs/sabi_nonexhaustive/index.html).
524
525```
526use abi_stable::{std_types::RString, StableAbi};
527
528#[repr(u8)]
529#[derive(StableAbi)]
530pub enum Command {
531    LaunchRockets,
532    EatLaundry,
533    WakeTheDragon { using: RString },
534}
535
536```
537
538###  Prefix-types 
539
540For examples of Prefix-types [look here](./docs/prefix_types/index.html#examples).
541
542###  Nonexhaustive-enums 
543
544For examples of nonexhaustive enums 
545[look here for the first example
546](./docs/sabi_nonexhaustive/index.html#defining-a-deserializable-nonexhaustive-enum).
547
548### Examples of `#[sabi(not_stableabi())]`
549
550For examples of using both [`#[derive(GetStaticEquivalent)]`][derive@GetStaticEquivalent] and
551[`#[sabi(not_stableabi())]`](#not_stableabi_attr)
552[look here](derive@GetStaticEquivalent#examples).
553
554
555
556
557
558[`NonExhaustive`]: ./nonexhaustive_enum/struct.NonExhaustive.html
559[`GetStaticEquivalent_`]: crate::abi_stability::get_static_equivalent::GetStaticEquivalent_
560[`StableAbi trait`]: trait@StableAbi
561[`UnsafeOpaqueField`]: crate::abi_stability::stable_abi_trait::UnsafeOpaqueField
562[`UnsafeIgnoredType`]: crate::marker_type::UnsafeIgnoredType
563[`PrefixTypeTrait`]: crate::prefix_type::PrefixTypeTrait
564[`ExtraChecks`]: crate::abi_stability::extra_checks::ExtraChecks
565[`InterfaceType`]: crate::InterfaceType
566
567*/
568#[doc(inline)]
569pub use abi_stable_derive::StableAbi;