plusplus 0.2.0

Classes and object-oriented programming for Rust!
Documentation
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
//! # Rust++: Object-Oriented Programming for Rust!!
//!
//! This crate allows you to create polymorphic objects in Rust, with overridable functions, with
//! behavior and syntax that should be familiar to users of object-oriented languages like C++, C#,
//! or Java.
//!
//! As an example:
//!
//! ```
//! # mod doc {
//! use plusplus::{class, ClassInConstruction, Downcast, DowncastTo, InConstruction};
//!
//! // define a class
//! class!{
//!     # crate as plusplus;
//!     // classes can derive traits (though right now only `Clone` is supported)
//!     #[derive(Clone)]
//!     pub class ObjectZero {
//!         string: String;
//!
//!         // a class constructor. Classes returned from Rust++ class constructors must be
//!         // parameterized with the `<InConstruction>` type parameter.
//!         pub fn new() -> ObjectZero<InConstruction> {
//!             // classes are initialized in the constructor with the `init_class!` syntax.
//!             //
//!             // this takes all the class's fields as an argument, plus a `superclass` field for
//!             // initializing the superclass (when present)
//!             init_class! {
//!                 string: "hello".into(),
//!                 another_field: 26,
//!             }
//!         }
//!
//!         // fields can have normal Rust visibility modifiers and be defined
//!         // anywhere in the class
//!         pub(crate) another_field: i32;
//!
//!         pub fn set_string(&mut self, str: String) {
//!             self.string = str;
//!         }
//!     }
//! }
//!
//! // object inheritance works across module and crate boundaries
//! mod object_one {
//!     use plusplus::{class, InConstruction};
//!     use reqwest::Response;
//!     class!{
//!         # crate as plusplus;
//!         // ObjectOne is a subclass of ObjectZero. it inherits all of ObjectZero's methods and
//!         // fields, and can extend ObjectZero's methods with new behavior
//!         //
//!         // A subclass must derive all traits the parent class derives
//!         #[derive(Clone)]
//!         pub class ObjectOne: super::ObjectZero {
//!             string_one: String;
//!             reqwest_url: String;
//!
//!             pub fn new() -> ObjectOne<InConstruction> {
//!                 init_class! {
//!                     // initialize the superclass
//!                     superclass: super::ObjectZero::new(),
//!
//!                     string_one: String::new(),
//!                     reqwest_url: "https://crouton.net/".into(),
//!                 }
//!             }
//!
//!             pub fn print_example(&self) {
//!                 println!("hi from ObjectOne");
//!             }
//!
//!             // you can also write async functions!
//!             pub async fn get_url(&self) -> reqwest::Result<Response> {
//!                 reqwest::get(&self.reqwest_url).await
//!             }
//!
//!             // you override a superclass's methods by declaring an Override block with the name
//!             // of the class you're overriding
//!             override super::ObjectZero {
//!                 pub fn set_string(&mut self, str: String) {
//!                     // you prefix method invocations with the `super_` prefix to call the
//!                     // parent's implementation of the method. this allows you to extend methods
//!                     // with new behaviors!
//!                     self.super_set_string(str.clone());
//!                     self.string_one = str;
//!                 }
//!             }
//!         }
//!     }
//!
//!     // if you want to define methods that can't be overridden, just put them in a normal
//!     // impl block
//!     impl ObjectOne {
//!         pub fn string_one(&self) -> &str {
//!             &self.string_one
//!         }
//!     }
//! }
//! use object_one::ObjectOne;
//! use reqwest::Response;
//!
//! class!{
//!     # crate as plusplus;
//!     #[derive(Clone)]
//!     pub class ObjectTwo: ObjectOne {
//!         string_two: String;
//!         pub fn new(two: impl Into<String>) -> ObjectTwo<InConstruction> {
//!             init_class! {
//!                 superclass: object_one::ObjectOne::new(),
//!                 string_two: two.into(),
//!             }
//!         }
//!
//!         // in order to override a class's method, you must create an override block
//!         // for the class that declared that method
//!         override ObjectOne {
//!             pub fn print_example(&self) {
//!                 self.super_print_example();
//!                 println!("hello from ObjectTwo");
//!             }
//!
//!             pub async fn get_url(&self) -> reqwest::Result<Response> {
//!                 let response = self.super_get_url().await?;
//!                 println!("url get!!!");
//!                 Ok(response)
//!             }
//!         }
//!
//!         // you can override methods from any parent class in the class hierarchy
//!         override ObjectZero {
//!             pub fn set_string(&mut self, str: String) {
//!                 self.super_set_string(str.clone());
//!                 self.string_two = str;
//!             }
//!         }
//!     }
//! }
//!
//! # pub
//! fn main() {
//!     // initialize an object. the `finish` method wraps the class in a `ClassBox`
//!     // and allows it to behave polymorphically.
//!     let object_two = ObjectTwo::new("hello!").finish();
//!
//!     // prints:
//!     // ```
//!     // hi from ObjectOne
//!     // hello from ObjectTwo
//!     // ```
//!     object_two.print_example();
//!     println!();
//!
//!     let object_as_one = object_two.upcast(); // is ClassBox<ObjectOne>
//!
//!     // calling a class method from anywhere in the class hierarchy will always result in the
//!     // deepest implementation of that method getting executed. so, this also prints:
//!     // ```
//!     // hi from ObjectOne
//!     // hello from ObjectTwo
//!     // ```
//!     object_as_one.print_example();
//!     println!();
//!
//!     // you can call a method with the `my_` prefix in order to bypass the method overload and
//!     // call that class's own implementation of the method. so this prints:
//!     // ```
//!     // hi from ObjectOne
//!     // ```
//!     object_as_one.my_print_example();
//!     println!();
//!
//!     let mut object_as_base = object_as_one.upcast(); // is ClassBox<ObjectZero>
//!
//!     // this call results in all three `set_string` methods getting invoked
//!     let new_str = "sets all strings!!";
//!     object_as_base.set_string(new_str.to_string());
//!
//!     // you can't directly access a subclass's fields from a superclass. so, the following line
//!     // would not compile:
//!     // println!("{}" object_as_base.string_two);
//!
//!     let object_as_two = object_as_base
//!         .downcast_to::<ObjectOne>().unwrap()
//!         .downcast_to::<ObjectTwo>().unwrap();
//!
//!     // but, you can access a superclass's fields, within the limits set by visibility rules
//!     assert_eq!(object_as_two.string, new_str);
//!     assert_eq!(object_as_two.string_one(), new_str);
//!     assert_eq!(object_as_two.string_two, new_str);
//!
//!     let tokio_rt = tokio::runtime::Builder::new_current_thread().enable_io().build().unwrap();
//!     tokio_rt.block_on(async {
//!         let object_as_one = object_as_two.upcast();
//!         // method overloads work on async methods, too. this prints:
//!         // ```
//!         // url get!!!
//!         // ```
//!         let response = object_as_one.get_url().await.unwrap();
//!
//!         // prints:
//!         // ```
//!         // <html>
//!         // <title> Crouton
//!         // </title>
//!         // <body bgcolor="white" text="black">
//!         // <img src="crouton.png" alt="Crouton">
//!         // </body>
//!         // </html>
//!         // ```
//!         // delightful....
//!         println!("{}", response.text().await.unwrap());
//!     });
//! }
//! # }
//! # doc::main();
//! ```
//!
//! How? Why?? Is that safe??!? These are questions that I often get asked in my day-to-day life.
//! Fortunately, in this case I have good answers to all three.
//!
//! ## How?
//!
//! First, know that `Constructed` and `InConstruction` are defined as follows:
//!
//! ```
//! use std::mem::MaybeUninit;
//! #[repr(transparent)]
//! pub struct Constructed([MaybeUninit<u8>]);
//! #[repr(transparent)]
//! pub struct InConstruction([MaybeUninit<u8>; 0]);
//! ```
//!
//! Note that `InConstruction` is a zero-sized type, and `Constructed` is an *unsized* type. This
//! will be important later.
//!
//! Now, let's look at how `ObjectOne` gets expanded:
//!
//! ```
//! # mod doc {
//! # use plusplus::{InConstruction, class};
//! # use reqwest::Response;
//! # class!{
//! #     crate as plusplus;
//! #     #[derive(Clone)]
//! #     pub class ObjectZero {
//! #         string: String;
//! #         pub fn new() -> ObjectZero<InConstruction> {
//! #             init_class! {
//! #                 string: "hello".into(),
//! #             }
//! #         }
//! #
//! #         pub fn set_string(&mut self, str: String) {
//! #             self.string = str;
//! #         }
//! #     }
//! # }
//! // we create an inner module for the class internals to make sure nobody
//! // *untoward* fucks around with the vtable
//! pub use plusplus__class_objectone::ObjectOne;
//! mod plusplus__class_objectone {
//!     use super::*;
//!     use plusplus::{
//!         Class, ClassBox, InConstruction, Constructed,
//!         ClassMemory, ClassInConstruction, ClassClone
//!     };
//!     use std::pin::Pin;
//!
//!     // create a virtual function table (or, vtable) to store the overridable function pointers
//!     #[doc(hidden)]
//!     #[derive(Clone, Copy)]
//!     pub struct ObjectOneVtbl {
//!         pub fn_print_example: fn(this: &ObjectOne),
//!         // the futures returned by async virtual functions are automatically boxed
//!         pub fn_get_url: for<'rpp_future>
//!             fn(this: &'rpp_future ObjectOne)
//!                 -> Pin<Box<dyn 'rpp_future + Future<Output=reqwest::Result<Response>>>>,
//!     }
//!     impl ObjectOneVtbl {
//!         // the vtable is initialized with our own implementations of the methods
//!         const BASE: Self = {
//!             fn my_get_url<'rpp_future>(this: &'rpp_future ObjectOne)
//!                 -> Pin<Box<dyn 'rpp_future + Future<Output=reqwest::Result<Response>>>>
//!             {
//!                 Box::pin(ObjectOne::my_get_url(this))
//!             }
//!
//!             Self {
//!                 fn_print_example: ObjectOne::my_print_example,
//!                 fn_get_url: my_get_url,
//!             }
//!         };
//!     }
//!     // define the actual class struct.
//!     //
//!     // the class struct is #[repr(C)] because we need precise control over the type's memory
//!     // layout and *my god* is there going to be a lot of type punning. type puns are this
//!     // crate's meat + potatoes. they're essential.
//!     //
//!     // we'll get to the generic parameter in a moment.
//!     #[repr(C)]
//!     #[derive(Clone)]
//!     pub struct ObjectOne<C: ?Sized + ClassMemory = Constructed>
//!     where
//!         ObjectZero: Class,
//!     {
//!         // we implement inheritance by nesting the class's superclass in the first field of the
//!         // class struct. that way, a reference to an `ObjectOne` is also very nearly a valid
//!         // reference to an `ObjectZero` - you (mostly) just need to do a simple pointer cast.
//!         superclass: ObjectZero<InConstruction>,
//!         // unless you skipped, you know this one
//!         vtbl: ObjectOneVtbl,
//!         // the type ID of the immediate subclass of this type. this is necessary if you want
//!         // downcasting to work
//!         //
//!         // we store an Option<&TypeId> instead of an Option<TypeId> as a size optimization; an
//!         // Option<&TypeId> is 8 bytes, while an Option<TypeId> is 24 bytes
//!         subclass_id: Option<&'static std::any::TypeId>,
//!         // the user-defined type fields.
//!         //
//!         // note that in order to match the apparent private visibility this field was defined
//!         // with we need to add a `pub(super)` to this field, so it's visible outside the
//!         // `plusplus__class_objectone` module
//!         pub(super) string_one: String,
//!         pub reqwest_url: String,
//!         // plusplus class memory. ahh, plusplus class memory.
//!         //
//!         // i said earlier that converting a class reference to its superclass's reference is
//!         // *mostly* a simple pointer cast. however, if class references were just normal thin
//!         // references, calling an overriden method that accesses one of that superclass's
//!         // subclasses would read past the end of that type, and thus (I think???) invoke
//!         // undefined behavior.
//!         //
//!         // so we have this memory field to fix that. the memory field contains a
//!         // `[MaybeUninit<u8>]` buffer, and the size of this buffer is always set to the size of
//!         // the rest of all of the subclasses combined (the buffer size is stored in the metadata
//!         // field of the fat pointer to this object). as a result, doing object casts doesn't
//!         // change the object's observed size, and references to any class in an object's class
//!         // hierarchy will always be references to the whole object in memory.
//!         memory: C,
//!     }
//!
//!     // helper struct that contains the fields the user needs to initialize. if we didn't have
//!     // this struct, then the user's constructor methods would have to live inside the
//!     // `plusplus__class_objectone` module, and they could futz with the class struct internals
//!     // in a potentially unsafe way.
//!     pub struct PlusPlus__InitClass {
//!         pub superclass: ObjectZero<InConstruction>,
//!         pub string_one: String,
//!         pub reqwest_url: String,
//!     }
//!     impl ObjectOne {
//!         // the methods users use to call into the vtable
//!         pub fn print_example(&self) {
//!             (self.vtbl.fn_print_example)(self)
//!         }
//!         // the boxed futures in virtual async fns get converted back to normal async calls
//!         pub async fn get_url(&self) -> reqwest::Result<Response> {
//!             (self.vtbl.fn_get_url)(self).await
//!         }
//!         pub fn super_set_string(&mut self, str: String) {
//!             self.plusplus__super_mut().my_set_string(str)
//!         }
//!         fn plusplus__super_ref(&self) -> &ObjectZero {
//!             self
//!         }
//!         fn plusplus__super_mut(&mut self) -> &mut ObjectZero {
//!             self
//!         }
//!         // this method is used by subclasses to modify their superclass's vtables and insert
//!         // method overrides. this is unsafe because if you put an incorrectly-implemented
//!         // function into the vtable, Bad Things Will Happen
//!         #[doc(hidden)]
//!         pub unsafe fn plusplus__vtbl_mut(&mut self) -> &mut ObjectOneVtbl { &mut self.vtbl }
//!     }
//!     unsafe impl Class for ObjectOne {
//!         // implement the Class trait for this class. this starts with boilerplate...
//!         const TYPE_ID: &'static std::any::TypeId = &std::any::TypeId::of::<ObjectOne>();
//!         type RootClass = <ObjectZero as Class>::RootClass;
//!         type InConstruction = ObjectOne<InConstruction>;
//!         fn subclass_id(&self) -> Option<&'static std::any::TypeId> { self.subclass_id }
//!         fn root_class(&self) -> &Self::RootClass { self }
//!         fn root_class_mut(&mut self) -> &mut Self::RootClass { self }
//!         unsafe fn as_in_construction(&self) -> &ObjectOne<InConstruction> {
//!             unsafe { &*(self as *const Self as *const ObjectOne<InConstruction>) }
//!         }
//!         unsafe fn as_in_construction_mut(&mut self) -> &mut ObjectOne<InConstruction> {
//!             unsafe { &mut *(self as *mut Self as *mut ObjectOne<InConstruction>) }
//!         }
//!
//!         // ....but this is really interesting!!
//!         //
//!         // plusplus needs to provide explicit drop handling. if it didn't, then if you dropped a
//!         // a superclass that's been subclassed, then none of the subclass destructor code would
//!         // be run, because the superclass sees its subclasses as opaque blobs of memory.
//!         //
//!         // let's look at `ObjectZero`'s vtable:
//!         //
//!         // ```
//!         // pub struct ObjectZeroVtbl {
//!         //     class_clone: fn(&ObjectZero) -> plusplus::ClassBox<ObjectZero>,
//!         //     pub manually_drop: unsafe fn(*mut ObjectZero),
//!         //     pub fn_set_string: fn(this: &mut ObjectZero, str: String),
//!         // }
//!         // ```
//!         //
//!         // notice that it has an extra `manually_drop` function pointer. whenever a subclass is
//!         // initialized, it overrides the root `manually_drop` function with its own. then, at
//!         // the end of initialization, `manually_drop` will contain a drop function for the leaf
//!         // class, which can see every superclass in class hierarchy, and then it will drop
//!         // all the data successfully.
//!         //
//!         // we wrap classes with `ClassBox` instead of `Box` for this reason. `ClassBox` knows
//!         // about the special class drop logic; `Box` does not.
//!         unsafe fn manually_drop(slot: &mut std::mem::ManuallyDrop<Self>) {
//!             let as_root_class = slot.root_class_mut();
//!             let manual_drop_fn = unsafe { as_root_class.plusplus__vtbl_mut().manually_drop };
//!             unsafe { manual_drop_fn(as_root_class); }
//!         }
//!         // helper methods that implement
//!         unsafe fn from_root_class_ref(root: &Self::RootClass) -> &Self {
//!             unsafe {
//!                     // ah. um. asdfuwef heheheh don'- don't worry about.. this......
//!                 // ...............................................................
//!                 // .....*sigh*. okay, there's no getting around the fact that this
//!                 // looks really really ugly. i'm sorry. i swear its less bad than it
//!                 // seems.
//!                 //
//!                 // this code first computes the size difference between the source
//!                 // dynamically-sized class and the target class with no padding...
//!                 let t: &<ObjectZero as Class>::RootClass = root;
//!                 let self_size = std::mem::size_of_val(t);
//!                 let target_size = std::mem::size_of::<ObjectOne<InConstruction>>();
//!                 // (if this assertion fails then this code has been called on the
//!                 // wrong types)
//!                 assert!(self_size >= target_size);
//!
//!                 // uses slice_from_raw_parts_mut to construct a fat pointer whose
//!                 // metadata contains the size of the `memory` buffer for the target
//!                 // type....
//!                 let array_size = self_size - target_size;
//!                 // ....then converts that into a fat pointer to the target type.
//!                 let target_ptr = std::ptr::slice_from_raw_parts(
//!                     t as *const <ObjectZero as Class>::RootClass as *const u8,
//!                     array_size
//!                 );
//!                 let target_ref = &*(target_ptr as *const ObjectOne);
//!                 // we do an assertion for good measure to make sure nothing's
//!                 // gone wrong.
//!                 assert_eq!(self_size, std::mem::size_of_val(target_ref));
//!                 target_ref
//!                 // okay, maybe using `slice_from_raw_parts_mut` is ugly as sin.
//!                 // ideally we'd use `std::ptr::from_raw_parts_mut` to construct a
//!                 // pointer with the right metadata correctly, but as of when I'm
//!                 // writing this (June 2nd 2026) its been five years since the issue
//!                 // for that function was opened and frankly i don't want to wait an
//!                 // indeterminate amount of time for someone to remember to stabilize
//!                 // that! i got burned once before by trying to write a library built
//!                 // around specialization (don't ask) and i'm not going to get burned
//!                 // again.
//!             }
//!         }
//!         // essentially the same code as above, but for mutable references
//!         unsafe fn from_root_class_mut(root: &mut Self::RootClass) -> &mut Self {
//!             unsafe {
//!                 let t: &mut <ObjectZero as Class>::RootClass = root;
//!                 let self_size = std::mem::size_of_val(t);
//!                 let target_size = std::mem::size_of::<ObjectOne<InConstruction>>();
//!                 assert!(self_size >= target_size);
//!                 let array_size = self_size - target_size;
//!                 let target_ptr = std::ptr::slice_from_raw_parts_mut(
//!                     t as *mut <ObjectZero as Class>::RootClass as *mut u8,
//!                     array_size
//!                 );
//!                 let target_ref = &mut *(target_ptr as *mut ObjectOne);
//!                 assert_eq!(self_size, std::mem::size_of_val(target_ref));
//!                 target_ref
//!             }
//!         }
//!     }
//!     impl ClassInConstruction for ObjectOne<InConstruction> {
//!         type Class = ObjectOne;
//!         /// Finish constructing this by moving it to the heap placing it in a `ClassBox`.
//!         ///
//!         /// Downcasting, upcasting, and deref coercions will work properly after calling this!
//!         fn finish(self) -> ClassBox<ObjectOne> {
//!             let boxed = Box::new(self);
//!             let leaked = Box::leak(boxed);
//!             let constructed = unsafe { leaked.to_constructed() };
//!             unsafe { ClassBox::from_raw(constructed) }
//!         }
//!     }
//!
//!     // the class construction helper methods
//!     impl ObjectOne<InConstruction> {
//!         // update the parent class's vtable to call the subclass's overridden methods
//!         fn plusplus__set_vtbls(&mut self) {
//!             use Class as _;
//!             // set the parent class's subclass type ID to this class's type ID
//!             unsafe { self.superclass.plusplus__set_subclass(<ObjectOne as Class>::TYPE_ID) };
//!             {
//!                 // the subclass implementation of manually_drop
//!                 unsafe fn manually_drop(this: *mut <ObjectOne as Class>::RootClass) {
//!                     let this = unsafe { ObjectOne::from_root_class_mut(&mut *this) };
//!                     unsafe { std::ptr::drop_in_place(this) };
//!                 }
//!                 let root_vtbl = unsafe {
//!                     <ObjectOne as Class>::root_class_mut(self.to_constructed())
//!                         .plusplus__vtbl_mut()
//!                 };
//!                 root_vtbl.manually_drop = manually_drop;
//!             }
//!             {
//!                 let this: &mut ObjectZero = &mut *(unsafe { self.to_constructed() });
//!                 fn fn_set_string(this: &mut ObjectZero, str: String) {
//!                     let this: &mut ObjectOne = unsafe { ObjectOne::from_root_class_mut(this.root_class_mut()) };
//!                     this.my_set_string(str)
//!                 }
//!                 unsafe { this.plusplus__vtbl_mut().fn_set_string = fn_set_string };
//!             }
//!         }
//!         // this function just initializes the class structure from its `InitClass` fields.
//!         pub(super) fn plusplus__new_from_init(init: PlusPlus__InitClass) -> Self {
//!             use Class;
//!             let mut this = Self {
//!                 vtbl: ObjectOneVtbl::BASE,
//!                 memory: InConstruction::default(),
//!                 subclass_id: None,
//!                 superclass: init.superclass,
//!                 string_one: init.string_one,
//!                 reqwest_url: init.reqwest_url
//!             };
//!             this.plusplus__set_vtbls();
//!
//!             // set the derived trait vtables for the parent class
//!             let root_in_construction = unsafe {
//!                 this.to_constructed().root_class_mut().as_in_construction_mut()
//!             };
//!             root_in_construction.plusplus__set_trait_vtbls::<ObjectOne>();
//!             // the implementation for this function in `ObjectZero` looks like this:
//!             //
//!             // pub fn plusplus__set_trait_vtbls<Class>(&mut self)
//!             // where
//!             //     Class: ?Sized + plusplus::Class<RootClass=ObjectZero>,
//!             //     Class::InConstruction: Clone,
//!             // {
//!             //     let class_clone = |this: &ObjectZero| -> plusplus::ClassBox<ObjectZero> {
//!             //         use plusplus::{Class as _, ClassBox};
//!             //         let child_class = unsafe {
//!             //             Class::from_root_class_ref(this).as_in_construction()
//!             //         };
//!             //         let cloned = child_class.clone().finish();
//!             //         unsafe { ClassBox::from_raw(ClassBox::leak(cloned).root_class_mut()) }
//!             //     };
//!             //     self.vtbl.class_clone = class_clone;
//!             // }
//!             //
//!             // notice the `Class::InConstruction: Clone` bound. implementing traits as a generic
//!             // method on the superclass allows us to use this method's generic bounds to check at
//!             // compiletime whether all the superclass's traits are implemented on the child class.
//!
//!             this
//!         }
//!
//!         // exposed so that subclasses can set the subclass_id field in their superclass. unsafe
//!         // because downcasts will go wrong if this is set to the wrong type id
//!         pub unsafe fn plusplus__set_subclass(&mut self, subclass_id: &'static std::any::TypeId) {
//!             self.subclass_id = Some(subclass_id);
//!         }
//!         /// Unsafe because caller must guarantee that vtbl doesn't contain any subclass methods
//!         pub unsafe fn to_constructed(&mut self) -> &mut ObjectOne {
//!             unsafe {
//!                 &mut *(
//!                     std::ptr::slice_from_raw_parts_mut::<u8>(
//!                         self as *mut _ as *mut u8,
//!                         0
//!                     ) as *mut ObjectOne
//!                 )
//!             }
//!         }
//!     }
//!
//!     // `ClassBox` uses this trait for its own `Clone` implementation
//!     impl ClassClone for ObjectOne {
//!         fn class_clone(&self) -> ClassBox<Self> {
//!             use {ClassBox, Class, ClassClone};
//!             let root_ref: &mut _ = ClassBox::leak(self.root_class().class_clone());
//!             let self_ref = unsafe { Self::from_root_class_mut(root_ref) };
//!             unsafe { ClassBox::from_raw(self_ref) }
//!         }
//!     }
//! }
//!
//! // the user-defined functions
//! impl ObjectOne {
//!     pub fn new() -> ObjectOne<InConstruction> {
//!         // init_class! gets expanded into this
//!         let init_class = plusplus__class_objectone::PlusPlus__InitClass {
//!             superclass: ObjectZero::new(),
//!             string_one: String::new(),
//!             reqwest_url: "https://crouton.net/".into(),
//!         };
//!         ObjectOne::<InConstruction>::plusplus__new_from_init(init_class)
//!     }
//!     // the user-defined methods. these versions don't get overridden by subclasses,
//!     // so they have the `my_` prefix added.
//!     pub fn my_print_example(&self) {
//!         println!("hi from ObjectOne");
//!     }
//!     pub async fn my_get_url(&self) -> reqwest::Result<Response> {
//!         reqwest::get(&self.reqwest_url).await
//!     }
//!     pub fn my_set_string(&mut self, str: String) {
//!         self.super_set_string(str.clone());
//!         self.string_one = str;
//!     }
//! }
//! // deref coercions to the parent class. the compiler will auto-insert multiple deref coercions
//! // to travel multiple layers up the class hierarchy.
//! impl std::ops::Deref for ObjectOne {
//!     type Target = ObjectZero;
//!     fn deref(&self) -> &Self::Target {
//!         unsafe {
//!             // see above for why this code is Like This
//!             let t: &ObjectOne = self;
//!             let self_size = std::mem::size_of_val(t);
//!             let target_size = std::mem::size_of::<ObjectZero<InConstruction>>();
//!             assert!(self_size >= target_size);
//!             let array_size = self_size - target_size;
//!             let target_ptr = std::ptr::slice_from_raw_parts(
//!                 t as *const ObjectOne as *const u8,
//!                 array_size,
//!             );
//!             let target_ref = &*(target_ptr as *const ObjectZero);
//!             assert_eq!(self_size, std::mem::size_of_val(target_ref));
//!             target_ref
//!         }
//!     }
//! }
//! impl std::ops::DerefMut for ObjectOne {
//!     fn deref_mut(&mut self) -> &mut Self::Target {
//!         unsafe {
//!             // ditto
//!             let t: &mut ObjectOne = self;
//!             let self_size = std::mem::size_of_val(t);
//!             let target_size = std::mem::size_of::<ObjectZero<InConstruction>>();
//!             assert!(self_size >= target_size);
//!             let array_size = self_size - target_size;
//!             let target_ptr = std::ptr::slice_from_raw_parts_mut(
//!                 t as *mut ObjectOne as *mut u8,
//!                 array_size,
//!             );
//!             let target_ref = &mut *(target_ptr as *mut ObjectZero);
//!             assert_eq!(self_size, std::mem::size_of_val(target_ref));
//!             target_ref
//!         }
//!     }
//! }
//! # }
//! ```
//!
//! And that's how this works! Thank you for sticking with me.
//!
//! ## Why?
//!
//! Some would say that it is best that Rust is not an object-oriented programming language. I fully
//! agree! Objects have a relatively high amount of overhead, and are conceptually very limited. For
//! *most* code, traits are a strictly better way of expressing genericism than objects.
//!
//! **You usually should not have to use this.** I'll plead with you right now to *really, really
//! think* about whether you need to reach for object-oriented programming to solve your problem.
//!
//! But, *sometimes*, a problem is *very well suited* to an object-oriented implementation and *very
//! poorly suited* to any other implementation. And it's useful to have objects as an option whenever
//! those problems come up. Of course, you could rewrite your code in a different language, but
//! there are a lot of good reasons to use Rust even despite that! What other language has so robust
//! an ecosystem, and also runs on desktops, web browsers, servers, smartphones, and embedded
//! devices?
//!
//! <small>
//! (i also think its really subversive to take such an explicitly not-object-oriented language and
//! force it to be object-oriented. the fact that this is possible <i>at all</i> is wildly funny to
//! me. i was laughing like a madwoman when i was writing this. i had a lot of fun. and isn't that
//! its own reward?)
//! </small>
//!
//! ## Is that safe??!?
//!
//! I think so! The ways I can think of that this theoretically could go wrong are:
//!
//! 1. If the type punning is invalid
//! 2. If the pointer provenance is handled incorrectly
//! 3. If there's a way for a user to access unsafe class internals without using explicitly
//!    `unsafe` code
//! 4. If there's a way for to swap superclasses, and thus swap vtables, of a fully-constructed
//!    class
//!
//! For #1, we're using `#[repr(C)]` carefully, and the subclass/superclass type layouts line up.
//! We're teaching Rust about our provenance tricks with pointer metadata, so unless I'm critically
//! misusing the pointer functions, #2 should be fine. No user-defined code is placed in the
//! protected class module, so #3 isn't a factor. And for #4, as far as I can tell, there is no way
//! to swap superclass vtables once they're constructed with safe code.
//!
//! That said, I may have overlooked something! I am not an expert on unsafe Rust. So if you find
//! something, do [open an issue](https://codeberg.org/osspial/plusplus/issues).
//!
//! Also, Miri hasn't complained in any of the tests I've run on the latest code. Absence of
//! evidence isn't evidence of absence, but like, it's at least a datapoint.
//!
//! -----
//!
//! This was proudly made without any assistance from AI tools.

pub use plusplus_macros::class;
use std::any::TypeId;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::ops::{Deref, DerefMut};
use std::ptr;

/// The extra memory of a class that has been constructed.
///
/// This is unsized, and contains every subclass of a given class.
#[repr(transparent)]
pub struct Constructed([MaybeUninit<u8>]);
/// The extra memory for a class in construction.
///
/// This is a zero-sized type, since a class in construction has no subclasses.
#[repr(transparent)]
#[derive(Default, Clone, Copy)]
pub struct InConstruction([MaybeUninit<u8>; 0]);

/// The extra memory for a class in which subclasses are stored.
pub unsafe trait ClassMemory {}
unsafe impl ClassMemory for Constructed {}
unsafe impl ClassMemory for InConstruction {}

/// A wrapper around polymorphic `Class` types.
///
/// This wrapper aids in upcasting and downcasting, and is also used to make `Drop` work properly.
/// Internally, its a slightly-modified `Box`
#[repr(transparent)]
#[derive(Debug)]
pub struct ClassBox<C: ?Sized + Class> {
    hidden_class: Box<ManuallyDrop<C>>,
}

impl<C: ?Sized + Class> ClassBox<C> {
    /// Leak the class, returning a reference to that class
    pub fn leak<'a>(self) -> &'a mut C {
        let this = ManuallyDrop::new(self);
        let class = unsafe { ptr::read(&this.hidden_class) };
        let manual_drop = Box::leak(class);
        &mut *manual_drop
    }

    /// Reconstruct the class from a raw pointer to that class.
    ///
    /// This is only safe is the raw pointer came from a `Box` or `Box`-derived allocation.
    pub unsafe fn from_raw(raw: *mut C) -> ClassBox<C> {
        let raw = raw as *mut ManuallyDrop<C>;
        ClassBox {
            hidden_class: unsafe { Box::from_raw(raw) },
        }
    }

    /// Upcast the class into its superclass.
    pub fn upcast(self) -> ClassBox<C::Target>
    where
        C: DerefMut,
        C::Target: Class,
    {
        let value_leaked = ClassBox::leak(self);
        let value_cast: &mut _ = value_leaked.deref_mut();
        unsafe { ClassBox::from_raw(value_cast) }
    }
}

impl<C: ?Sized + Class> Deref for ClassBox<C> {
    type Target = C;

    fn deref(&self) -> &Self::Target {
        &self.hidden_class
    }
}

impl<C: ?Sized + Class> DerefMut for ClassBox<C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.hidden_class
    }
}

impl<C: ?Sized + Class> Drop for ClassBox<C> {
    fn drop(&mut self) {
        unsafe {
            C::manually_drop(&mut self.hidden_class);
        }
    }
}

/// Any class type.
///
/// ## Safety
///
/// This class must follow all the many, many layout and behavior invariants specified in the
/// `class!` macro.
pub unsafe trait Class {
    const TYPE_ID: &'static TypeId;
    type RootClass: ?Sized + Class;
    type InConstruction: ClassInConstruction<Class = Self>;

    fn subclass_id(&self) -> Option<&'static TypeId>;
    fn root_class(&self) -> &Self::RootClass;
    fn root_class_mut(&mut self) -> &mut Self::RootClass;
    unsafe fn manually_drop(slot: &mut ManuallyDrop<Self>);
    unsafe fn as_in_construction(&self) -> &Self::InConstruction;
    unsafe fn as_in_construction_mut(&mut self) -> &mut Self::InConstruction;
    unsafe fn from_root_class_ref(root: &Self::RootClass) -> &Self;
    unsafe fn from_root_class_mut(root: &mut Self::RootClass) -> &mut Self;
}

pub trait ClassInConstruction {
    type Class: ?Sized + Class<InConstruction = Self>;
    /// Finish constructing this by moving it to the heap placing it in a `ClassBox`.
    ///
    /// Downcasting, upcasting, and deref coercions will work properly after calling this!
    fn finish(self) -> ClassBox<Self::Class>;
}

pub trait ClassClone: Class {
    fn class_clone(&self) -> ClassBox<Self>;
}

impl<C: ?Sized + Class + ClassClone> Clone for ClassBox<C> {
    fn clone(&self) -> Self {
        self.class_clone()
    }
}

/// Any wrapper around a class that can be downcast into a child class.
pub trait Downcast<T: ?Sized>: Sized {
    type Wrapped;
    /// Downcast into a child class. Returns `Err(self)` if the cast is invalid.
    fn downcast(self) -> Result<Self::Wrapped, Self>;
}

/// Convenience trait to make downcasting into a child class easier to write.
pub trait DowncastTo {
    /// Downcast to child class `T`. Returns `None` if the cast is invalid.
    fn downcast_to<T: ?Sized>(self) -> Option<Self::Wrapped>
    where
        Self: Downcast<T>,
    {
        self.downcast().ok()
    }

    /// Downcast to child class `T`. Returns `Err(self)` if the cast is invalid.
    fn downcast_or_err<T: ?Sized>(self) -> Result<Self::Wrapped, Self>
    where
        Self: Downcast<T>,
    {
        self.downcast()
    }
}

impl<T> DowncastTo for T {}

impl<T: ?Sized + Class, U: ?Sized + Class> Downcast<U> for ClassBox<T>
where
    for<'a> &'a mut T: Downcast<U, Wrapped = &'a mut U>,
{
    type Wrapped = ClassBox<U>;
    fn downcast(self) -> Result<ClassBox<U>, Self> {
        let leaked = ClassBox::leak(self);
        let downcast: Result<&'_ mut U, _> = leaked.downcast();
        downcast
            .map(|b| unsafe { ClassBox::from_raw(b) })
            .map_err(|b| unsafe { ClassBox::from_raw(b) })
    }
}

#[cfg(test)]
mod tests {
    use crate::{ClassInConstruction, Downcast};
    use crate::InConstruction;
    use crate::{ClassBox, ClassMemory, DowncastTo};
    use plusplus_macros::class;
    use std::cell::RefCell;
    use std::rc::Rc;

    #[test]
    fn overrides() {
        let mut object: ClassBox<ObjectZero> = ObjectTwo::new("two").finish().upcast().upcast();

        let new_string = "new string";
        object.set_string(new_string.into(), 0);
        let object_two = object
            .downcast_to::<ObjectOne>()
            .unwrap()
            .downcast_to::<ObjectTwo>()
            .unwrap();
        assert_eq!(object_two.string_two, new_string);
        assert_eq!(object_two.string_one, new_string);
        assert_eq!(object_two.string(), new_string);
    }

    // submod to make sure that visibility works as expected
    pub use submod::ObjectZero;
    mod submod {
        use super::InConstruction;
        use plusplus_macros::class;

        class! {
            pub class ObjectZero {
                string: String;
                pub borrowable: u32;

                pub fn new() -> ObjectZero<InConstruction> {
                    init_class! {
                        string: "hello".into(),
                        borrowable: 2,
                    }
                }

                pub fn string(&self) -> &str {
                    &self.string
                }
                pub fn borrowable_mut(&mut self) -> &mut u32 {
                    &mut self.borrowable
                }

                pub fn set_string(&mut self, str: String, _second_arg: u32) {
                    self.string = str;
                    println!("\nbase impl");
                }
            }
        }
    }

    class! {
        // using crate::tests:: path in order to make sure that the `super::` path modifications
        // don't mess this case up
        pub class ObjectOne: crate::tests::ObjectZero {
            pub string_one: String;

            pub fn new() -> ObjectOne<InConstruction> {
                init_class! {
                    superclass: ObjectZero::new(),
                    string_one: String::new(),
                }
            }

            async fn async_test<'a>(&'a self, s: &'a str) -> &'a str {
                s
            }

            async fn async_test_2(&self, s: &str) -> String {
                s.into()
            }

            unsafe fn unsafe_test(&self) {}

            override ObjectZero {
                pub fn set_string(&mut self, str: String, second_arg: u32) {
                    self.super_set_string(str.clone(), second_arg);
                    self.string_one = str;
                    self.borrowable = 40;
                    println!("override");
                }
            }
        }
    }

    class! {
        pub(crate) class ObjectTwo: ObjectOne {
            string_two: String;
            fn new(two: impl Into<String>) -> ObjectTwo<InConstruction> {
                init_class! {
                    superclass: ObjectOne::new(),
                    string_two: two.into(),
                }
            }

            fn lifetime_bs<'a>(&self, s: &'a str) -> &'a str {
                s
            }

            override ObjectZero {
                pub fn set_string(&mut self, str: String, second_arg: u32) {
                    self.super_set_string(str.clone(), second_arg);
                    self.string_two = str;
                    println!("override two");
                }
            }

            override ObjectOne {
                async fn async_test<'a>(&'a self, s: &'a str) -> &'a str {
                    self.super_async_test(s).await
                }

                async fn async_test_2(&self, s: &str) -> String {
                    self.super_async_test_2(s).await
                }

                unsafe fn unsafe_test(&self) {
                    unsafe{ self.super_unsafe_test() }
                }
            }
        }
    }

    #[test]
    fn test_drops() {
        let string_one;
        let string_root;
        {
            let one = DropTestOne::new().finish();
            string_one = one.string_one();
            string_root = one.string_root();
            let _root = one.upcast();
        }
        assert_eq!("root_dropped", &*string_root.borrow());
        assert_eq!("one_dropped", &*string_one.borrow());
    }

    class! {
        class DropTestRoot {
            string_root: Rc<RefCell<String>>;

            fn new() -> DropTestRoot<InConstruction> {
                init_class!{
                    string_root: Rc::new(RefCell::new("root".to_string())),
                }
            }

            fn string_root(&self) -> Rc<RefCell<String>> {
                self.string_root.clone()
            }
        }
    }

    class! {
        class DropTestOne: DropTestRoot {
            string_one: Rc<RefCell<String>>;

            fn new() -> DropTestOne<InConstruction> {
                init_class!{
                    superclass: DropTestRoot::new(),
                    string_one: Rc::new(RefCell::new("one".to_string())),
                }
            }

            fn string_one(&self) -> Rc<RefCell<String>> {
                self.string_one.clone()
            }
        }
    }

    impl<M: ?Sized + ClassMemory> Drop for DropTestRoot<M> {
        fn drop(&mut self) {
            self.string_root.borrow_mut().push_str("_dropped");
        }
    }

    impl<M: ?Sized + ClassMemory> Drop for DropTestOne<M> {
        fn drop(&mut self) {
            self.string_one.borrow_mut().push_str("_dropped");
        }
    }

    #[test]
    fn test_clone() {
        let clone_one: ClassBox<TestClone1> = TestClone1::new().finish();
        let clone_zero: ClassBox<TestClone> = clone_one.upcast();
        let cloned: ClassBox<TestClone> = clone_zero.clone();
        let clone_one = clone_zero.downcast_to::<TestClone1>().unwrap();

        let cloned_one: ClassBox<TestClone1> = cloned.downcast_to::<TestClone1>().unwrap();

        assert_eq!(cloned_one.vec, clone_one.vec);
        assert_ne!(cloned_one.vec.as_ptr(), clone_one.vec.as_ptr());
        assert_eq!(cloned_one.string, clone_one.string);
        assert_ne!(cloned_one.string.as_ptr(), clone_one.string.as_ptr());
    }

    class! {
        #[derive(Clone)]
        class TestClone {
            string: String;

            fn new() -> TestClone<InConstruction> {
                init_class!{
                    string: String::from("hi"),
                }
            }
        }
    }
    class! {
        #[derive(Clone)]
        class TestClone1: TestClone {
            vec: Vec<i32>;

            fn new() -> TestClone1<InConstruction> {
                init_class!{
                    superclass: TestClone::new(),
                    vec: vec![1, 2, 3, 4, 5],
                }
            }
        }
    }
}