abi_stable/proc_macro_reexports/
sabi_trait_attribute.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/**

This attribute generates an ffi-safe trait object on the trait it's applied to.

All items outside the list of generated items comes from [`abi_stable::sabi_trait`].


# Supertraits.

By default these are the supertraits that `#[sabi_trait]` traits can have: 

- lifetimes: It can be a lifetime declared by the trait, or `'static`.

- `Debug`

- `Display`

- `std::error::Error`: Written as `Error`: The `Error` methods aren't delegated to,
it uses the default implementation,

- `Clone`

- `Send`

- `Sync`

- `Unpin`

To be able to have more supertraits you must use the `#[sabi(use_dyntrait)]` helper attribute,
which changes the underlying implementation from [`RObject`] to [`DynTrait`],
allowing these supertraits: 

- `Iterator`: requires the Item type to be specified.

- `DoubleEndedIterator`: requires the Item type to be specified.

- `std::fmt::Write`: Written as `FmtWrite`

- `std::io::Write`: Written as `IoWrite`

- `std::io::Seek`: Written as `IoSeek`

- `std::io::Read`: Written as `IoRead`

- `std::io::BufRead`: Written as `IoBufRead`

- `Eq`

- `PartialEq`

- `Ord`

- `PartialOrd`

- `Hash`



### Supertrait Extensibility

The properties described below are checked when `abi_stable` loads a dynamic library.

Traits can add non-marker supertraits in minor versions without breaking ABI compatibility,
with the (non-ABI related) caveats described in the extensibility section.

Traits cannot add marker supertraits in minor versions ABI compatibly,
because that would cause problems with thread/memory safety if allowed.
If it were allowed,`!Send` trait objects could be passed from a binary to 
a dynamic library(where the trait object type is `Send`),
and that would be Undefined Behavior in many situations.

# Extensibility

`#[sabi_trait]` trait objects are (ABI-wise) safe to extend in minor versions,
so long as methods are always added at the end, preferably as default methods.

A library will not load (through safe means) if methods are added anywhere but the end.

Accidentally calling newer methods on trait objects from older versions of a
library will cause a panic at runtime, unless it has a default implementation
(within the trait definition that `#[sabi_trait]` can see).

Panics can only happen if one loads multiple versions of a library,
where the trait is extended in each version(without using default methods),
and passes trait objects among those libraries.

# Generated items.

This is a nonexhaustive list of the items generated by the attribute,
where `Trait` is the name of the annotated trait.

### `Trait_trait`

This is the module inside of which all the items are generated.

These are the items reexported from the module: 

- [`Trait`](#trait): The trait itself.

- [`Trait_TO`](#trait_to): The trait object for the trait.

- [`Trait_CTO`](#trait_cto): 
A type alias for the trait object which is constructible in constants.


### `Trait_TO` 

The ffi-safe trait object.

[Its inherent methods are documented here.
](./docs/sabi_trait_inherent/index.html#methods)

`Trait_TO` has inherent method equivalents of the trait methods,
only requiring the wrapped pointer to implement the trait in the individual methods
(instead of putting those bounds in the impl block itself).

<br>

This only implements `Trait` if all the methods are callable,
when the wrapped pointer type implements traits for these methods: 

- `&self` method: requires `AsPtr<PtrTarget = ()>`.
- `&mut self` method: requires `AsMutPtr<PtrTarget = ()>`.
- `self` method: requires `OwnedPointer<PtrTarget = ()>`.

<br>

Trait_TO has these generic parameters(in order): 

- `'trait_lifetime_n`: The lifetime parameters of the trait, if any.

- `'lt`: 
This is the lifetime of the type that the trait object was constructed with.
If the trait requires `'static`(in the list of supertraits),
then it doesn't have this lifetime parameter.

- `Pointer`: 
    An pointer whose referent has been erased,
    most commonly [`RBox<()>`]/[`RArc<()>`]/[`RRef<'_, ()>`]/[`RMut<'_, ()>`].

- `trait_type_param_n`: The type parameters of the trait.

- `trait_const_param_n`: The const parameters of the trait.

- `trait_assoc_type_n`: The associated types of the trait.


A trait defined like this: `trait Foo<'a, T, U>{ type Hello; type World; }`,
has this trait object: `Foo_TO<'a, 'lt, Pointer, T, U, Hello, World>`.

<br>

One can access the underlying implementation of the trait object through the `obj` field,
allowing one to call these methods(a nonexhaustive list): 

- `downcast_into`

- `downcast_as`

- `downcast_as_mut`

To reconstruct `Trait_TO` from its underlying implementation,
you can use the `Trait_TO::from_sabi` associated function.

###  Trait_CTO

A type alias for the type of the trait objct that is constructible in constants,
with the `from_const` constructor function.

Constructed with `Trait_CTO::from_const(&value)`.

Trait_CTO has these generic parameters(in order): 

- `'trait_lifetime_n`: The lifetime parameters of the trait, if any.

- `'lt`: this is the lifetime of the type that the trait object was construct with.
If the trait requires `'static`(in the list of supertraits),
then it doesn't have this lifetime parameter.

- `'_ref`: this is the lifetime of the reference that this was constructed with.

- `trait_type_param_n`: The type parameters of the trait.

- `trait_const_param_n`: The const parameters of the trait.

- `trait_assoc_type_n`: The associated types of the trait.


Example: `Trait_CTO<'lt, 'r, u8, u64, 10, AssocFoo>`

###  Trait 

The trait is defined similarly to how it is before being transformed by the 
`#[sabi_trait]` attribute.

These are the differences: 

- If there is a by-value method, a `Self: Sized` constraint will be added automatically.

- Lifetime supertraits are stripped, because they disallow the trait object to be 
constructed with a reference of a smaller lifetime.

# VTable attributes

To pass attributes to the generated vtable you can use the `#[sabi(  )]` attributes 
that are valid for `#[derive(StableAbi)]`.

[Here is the documentation for the derive macro.
](./derive.StableAbi.html)

# Trait attributes.

These are attributes for the generated trait, applied on the trait(not on methods).

###  `#[sabi(no_trait_impl)]`

Disables the implementation of the trait for the trait object,
you can still call the inherent versions of those methods on the trait object.

This is useful to reduce compile-time overhead,
and to allow users to declare a blanket(generic) implementation of the trait.

###  `#[sabi(no_default_fallback)]`

Stops using default implementation of methods (from the trait declaration) 
as the fallback implementation of the method when it's not in the vtable,
because the trait object comes from a previous version of the library.

By using this attribute, defaulted methods will behave the same as 
non-defaulted methods when they don't exist in the vtable.

### `#[sabi(debug_print_trait)]`

Prints the output generated by the attribute macro,

Note that this does not expand the output of the 
`#[derive(StableAbi)]` attribute on the vtable.

### `#[sabi(use_dyntrait)]`

Changes how the trait object is implemented to use `DynTrait` instead of `RObject`,
this allows using more traits, with the (potential) cost of having more overhead.

# Associated types

The only valid way to refer to associated types in the trait declaration is with 
`Self::AssocType` syntax.

Associated types in the trait object are transformed into type parameters 
that come after those of the trait.

# Object safety

Trait objects generated using this attribute have similar restrictions to built-in trait objects: 

- `Self` can only be used to access associated types 
    (using the `Self::AssocType` syntax).

- `self` is a valid method receiver,
    this requires that the pointer that the generated trait object wraps 
    implements `abi_stable::pointer_trait::OwnedPointer`.

# Questions and Answers

**Question: ** Why does Calling from_ptr/from_value give me a expected a `'static` value error?

Answer: There are 3 possible reasons

- 1: Because the trait has a `'static` supertrait bound.

- 2: Because the trait has one of the comparison traits
(`Eq`/`PartialEq`/`Ord`/`PartialOrd`)
as supertraits.
This requires the type to be `'static` because comparing trait objects requires 
constructing a `std::any::TypeId`, which itself requires `'static` to be constructed.

- 3: Because you passed `TD_CanDowncast` to the constructor function,
which requires constructing a `std::any::TypeId`
(to unerase the trait object back into the value),
which itself requires `'static` to be constructed.

# Examples

###  Dictionary trait 

```rust
use abi_stable::{
    sabi_trait,
    sabi_trait::prelude::*,
    std_types::{RArc, RBox, RNone, ROption, RStr, RString},
    StableAbi,
};

use std::{collections::HashMap, fmt::Debug};

#[sabi_trait]
pub trait Dictionary: Debug + Clone {
    type Value;

    fn get(&self, key: RStr<'_>) -> Option<&Self::Value>;

    /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method
    /// that was defined in the first compatible version of the library
    /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 , etc),
    /// requiring new methods to always be added below preexisting ones.
    ///
    /// The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library
    /// bumps its "major" version,
    /// at which point it would be moved to the last method at the time.
    ///
    #[sabi(last_prefix_field)]
    fn insert(&mut self, key: RString, value: Self::Value) -> ROption<Self::Value>;

    /// It's semver compatible to add defaulted methods below previously-defined ones in
    /// minor version updates.
    fn contains(&self, key: RStr<'_>) -> bool {
        self.get(key).is_some()
    }
}

# fn main() {

{
    impl<V> Dictionary for HashMap<RString, V>
    where
        V: Debug + Clone,
    {
        type Value = V;
        fn get(&self, key: RStr<'_>) -> Option<&V> {
            self.get(key.as_str())
        }
        fn insert(&mut self, key: RString, value: V) -> ROption<V> {
            self.insert(key, value).into()
        }
    }

    let mut map = HashMap::<RString, u32>::new();
    map.insert("hello".into(), 100);
    map.insert("world".into(), 10);

    {
        // This type annotation is for the reader
        //
        // You can unerase trait objects constructed with `TD_CanDowncast`
        // (as opposed to `TD_Opaque`, which can't be unerased).
        let mut object: Dictionary_TO<'_, RBox<()>, u32> =
            Dictionary_TO::from_value(map.clone(), TD_CanDowncast);

        assert_eq!(Dictionary::get(&object, "hello".into()), Some(&100));
        assert_eq!(object.get("hello".into()), Some(&100)); // Inherent method call

        assert_eq!(Dictionary::get(&object, "world".into()), Some(&10));
        assert_eq!(object.get("world".into()), Some(&10)); // Inherent method call

        object.insert("what".into(), 99); // Inherent method call

        // You can only unerase a trait object if it was constructed with `TD_CanDowncast`
        // and it's being unerased into a type that implements `std::any::Any`.
        let map: RBox<HashMap<RString, u32>> = object.obj.downcast_into().unwrap();

        assert_eq!(map.get("hello".into()), Some(&100));
        assert_eq!(map.get("world".into()), Some(&10));
        assert_eq!(map.get("what".into()), Some(&99));
    }
    {
        let arc = RArc::new(map.clone());
        // This type annotation is for the reader
        //
        // You can unerase trait objects constructed with `TD_CanDowncast`
        // (as opposed to `TD_Opaque`, which can't be unerased).
        let object: Dictionary_TO<'_, RArc<()>, u32> =
            Dictionary_TO::from_ptr(arc, TD_CanDowncast);

        assert_eq!(object.get("world".into()), Some(&10));

        // Can't call these methods on `Dictionary_TO<RArc<()>,..>`
        // because `RArc<_>` doesn't implement AsMutPtr.
        //
        // assert_eq!(Dictionary::get(&object,"hello"), Some(&100));
        //
        // object.insert("what".into(), 99);
        // Dictionary::insert(&mut object,"what".into(), 99);

        let map: RArc<HashMap<RString, u32>> = object.obj.downcast_into().unwrap();
        assert_eq!(map.get("hello".into()), Some(&100));
        assert_eq!(map.get("world".into()), Some(&10));
    }
}

{
    impl Dictionary for () {
        type Value = RString;
        fn get(&self, _: RStr<'_>) -> Option<&RString> {
            None
        }
        fn insert(&mut self, _: RString, _: RString) -> ROption<RString> {
            RNone
        }
    }

    // This type annotation is for the reader
    let object: Dictionary_TO<'_, RBox<()>, RString> =
        Dictionary_TO::from_value((), TD_Opaque);

    assert_eq!(object.get("hello".into()), None);
    assert_eq!(object.get("world".into()), None);

    // Cannot unerase trait objects created with `TD_Opaque`.
    assert_eq!(object.obj.downcast_into::<()>().ok(), None);
}

# }


```


### Constructing a trait object in a constant

This shows how one can construct a `#[sabi_trait]` generated trait object in a constant/static.

```rust

use abi_stable::{sabi_trait, sabi_trait::TD_Opaque};

#[sabi_trait]
pub trait StaticSet: Sync + Send + Debug + Clone {
    type Element;

    /// Whether the set contains the key.
    fn contains(&self, key: &Self::Element) -> bool;
}

impl<'a, T> StaticSet for &'a [T]
where
    T: std::fmt::Debug + Sync + Send + std::cmp::PartialEq,
{
    type Element = T;

    fn contains(&self, key: &Self::Element) -> bool {
        (**self).contains(key)
    }
}

const CARDS: &'static [char] =
    &['A', '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K'];

static IS_CARD: StaticSet_CTO<'static, 'static, char> =
    StaticSet_CTO::from_const(&CARDS, TD_Opaque);

# fn main(){

assert!(IS_CARD.contains(&'A'));
assert!(IS_CARD.contains(&'4'));
assert!(IS_CARD.contains(&'7'));
assert!(IS_CARD.contains(&'9'));
assert!(IS_CARD.contains(&'J'));

assert!(!IS_CARD.contains(&'0'));
assert!(!IS_CARD.contains(&'1'));
assert!(!IS_CARD.contains(&'B'));

# }

```

### Cloning an `RArc`-using trait object.

Because of a quirk of how `#[sabi_trait]` trait objects work,
trait objects that use [`RArc`] can only be `.clone()`d if they 
have a `Clone` supertrait.
To work around this, you can use the 
[`RObject::shallow_clone`] /[`DynTrait::shallow_clone`] methods.

```rust
use abi_stable::{
    sabi_trait,
    sabi_trait::TD_Opaque,
    std_types::RArc,
};

# fn main() {
let object = Foo_TO::from_ptr(RArc::new(SomeDay{day: 10}), TD_Opaque);

// calling `RObject::shallow_clone` to clone the `RArc`-based trait object,
// now both have a `RArc` handle to the same data.
let clone = Foo_TO::from_sabi(object.obj.shallow_clone());

assert_eq!(format!("{:?}", object), format!("{:?}", clone));
# }


#[sabi_trait]
pub trait Foo: Sync + Send + Debug {}

#[derive(Debug)]
struct SomeDay {
    day: u32,
}

impl Foo for SomeDay {}
```



[`abi_stable::sabi_trait`]: ./sabi_trait/index.html
[`RObject`]: crate::sabi_trait::RObject
[`RObject::shallow_clone`]: crate::sabi_trait::RObject::shallow_clone
[`DynTrait::shallow_clone`]: crate::DynTrait::shallow_clone
[`DynTrait`]: crate::DynTrait
[`RBox<()>`]: ./std_types/struct.RBox.html
[`RArc<()>`]: ./std_types/struct.RArc.html
[`RArc`]: ./std_types/struct.RArc.html
[`RRef<'_, ()>`]: ./sabi_types/struct.RRef.html
[`RMut<'_, ()>`]: ./sabi_types/struct.RMut.html

*/
#[doc(inline)]
pub use abi_stable_derive::sabi_trait;