-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathrust.rs
More file actions
1630 lines (1433 loc) · 56.9 KB
/
rust.rs
File metadata and controls
1630 lines (1433 loc) · 56.9 KB
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
use super::code_indenter::{CodeIndenter, Indenter};
use super::util::{collect_case, iter_reducers, print_lines, type_ref_name};
use super::Lang;
use crate::util::{iter_tables, iter_types, iter_unique_cols, print_auto_generated_file_comment};
use convert_case::{Case, Casing};
use spacetimedb_lib::sats::layout::PrimitiveType;
use spacetimedb_lib::sats::AlgebraicTypeRef;
use spacetimedb_schema::def::{ModuleDef, ReducerDef, ScopedTypeName, TableDef, TypeDef};
use spacetimedb_schema::identifier::Identifier;
use spacetimedb_schema::schema::{Schema, TableSchema};
use spacetimedb_schema::type_for_generate::{AlgebraicTypeDef, AlgebraicTypeUse};
use std::collections::BTreeSet;
use std::fmt::{self, Write};
use std::ops::Deref;
/// Pairs of (module_name, TypeName).
type Imports = BTreeSet<AlgebraicTypeRef>;
const INDENT: &str = " ";
pub struct Rust;
impl Lang for Rust {
fn table_filename(
&self,
_module: &spacetimedb_schema::def::ModuleDef,
table: &spacetimedb_schema::def::TableDef,
) -> String {
table_module_name(&table.name) + ".rs"
}
fn type_filename(&self, type_name: &ScopedTypeName) -> String {
type_module_name(type_name) + ".rs"
}
fn reducer_filename(&self, reducer_name: &Identifier) -> String {
reducer_module_name(reducer_name) + ".rs"
}
fn generate_type(&self, module: &ModuleDef, typ: &TypeDef) -> String {
let type_name = collect_case(Case::Pascal, typ.name.name_segments());
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out);
out.newline();
match &module.typespace_for_generate()[typ.ty] {
AlgebraicTypeDef::Product(product) => {
gen_and_print_imports(module, out, &product.elements, &[typ.ty]);
out.newline();
define_struct_for_product(module, out, &type_name, &product.elements, "pub");
}
AlgebraicTypeDef::Sum(sum) => {
gen_and_print_imports(module, out, &sum.variants, &[typ.ty]);
out.newline();
define_enum_for_sum(module, out, &type_name, &sum.variants, false);
}
AlgebraicTypeDef::PlainEnum(plain_enum) => {
let variants = plain_enum
.variants
.iter()
.cloned()
.map(|var| (var, AlgebraicTypeUse::Unit))
.collect::<Vec<_>>();
define_enum_for_sum(module, out, &type_name, &variants, true);
}
}
out.newline();
writeln!(
out,
"
impl __sdk::InModule for {type_name} {{
type Module = super::RemoteModule;
}}
",
);
output.into_inner()
}
fn generate_table(&self, module: &ModuleDef, table: &TableDef) -> String {
let schema = TableSchema::from_module_def(module, table, (), 0.into())
.validated()
.expect("Failed to generate table due to validation errors");
let type_ref = table.product_type_ref;
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out);
let row_type = type_ref_name(module, type_ref);
let row_type_module = type_ref_module_name(module, type_ref);
writeln!(out, "use super::{row_type_module}::{row_type};");
let product_def = module.typespace_for_generate()[type_ref].as_product().unwrap();
// Import the types of all fields.
// We only need to import fields which have indices or unique constraints,
// but it's easier to just import all of 'em, since we have `#![allow(unused)]` anyway.
gen_and_print_imports(
module,
out,
&product_def.elements,
&[], // No need to skip any imports; we're not defining a type, so there's no chance of circular imports.
);
let table_name = table.name.deref();
let table_name_pascalcase = table.name.deref().to_case(Case::Pascal);
let table_handle = table_name_pascalcase.clone() + "TableHandle";
let insert_callback_id = table_name_pascalcase.clone() + "InsertCallbackId";
let delete_callback_id = table_name_pascalcase.clone() + "DeleteCallbackId";
let accessor_trait = table_access_trait_name(&table.name);
let accessor_method = table_method_name(&table.name);
write!(
out,
"
/// Table handle for the table `{table_name}`.
///
/// Obtain a handle from the [`{accessor_trait}::{accessor_method}`] method on [`super::RemoteTables`],
/// like `ctx.db.{accessor_method}()`.
///
/// Users are encouraged not to explicitly reference this type,
/// but to directly chain method calls,
/// like `ctx.db.{accessor_method}().on_insert(...)`.
pub struct {table_handle}<'ctx> {{
imp: __sdk::TableHandle<{row_type}>,
ctx: std::marker::PhantomData<&'ctx super::RemoteTables>,
}}
#[allow(non_camel_case_types)]
/// Extension trait for access to the table `{table_name}`.
///
/// Implemented for [`super::RemoteTables`].
pub trait {accessor_trait} {{
#[allow(non_snake_case)]
/// Obtain a [`{table_handle}`], which mediates access to the table `{table_name}`.
fn {accessor_method}(&self) -> {table_handle}<'_>;
}}
impl {accessor_trait} for super::RemoteTables {{
fn {accessor_method}(&self) -> {table_handle}<'_> {{
{table_handle} {{
imp: self.imp.get_table::<{row_type}>({table_name:?}),
ctx: std::marker::PhantomData,
}}
}}
}}
pub struct {insert_callback_id}(__sdk::CallbackId);
pub struct {delete_callback_id}(__sdk::CallbackId);
impl<'ctx> __sdk::Table for {table_handle}<'ctx> {{
type Row = {row_type};
type EventContext = super::EventContext;
fn count(&self) -> u64 {{ self.imp.count() }}
fn iter(&self) -> impl Iterator<Item = {row_type}> + '_ {{ self.imp.iter() }}
type InsertCallbackId = {insert_callback_id};
fn on_insert(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> {insert_callback_id} {{
{insert_callback_id}(self.imp.on_insert(Box::new(callback)))
}}
fn remove_on_insert(&self, callback: {insert_callback_id}) {{
self.imp.remove_on_insert(callback.0)
}}
type DeleteCallbackId = {delete_callback_id};
fn on_delete(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static,
) -> {delete_callback_id} {{
{delete_callback_id}(self.imp.on_delete(Box::new(callback)))
}}
fn remove_on_delete(&self, callback: {delete_callback_id}) {{
self.imp.remove_on_delete(callback.0)
}}
}}
"
);
out.delimited_block(
"
#[doc(hidden)]
pub(super) fn register_table(client_cache: &mut __sdk::ClientCache<super::RemoteModule>) {
",
|out| {
writeln!(out, "let _table = client_cache.get_or_make_table::<{row_type}>({table_name:?});");
for (unique_field_ident, unique_field_type_use) in iter_unique_cols(module.typespace_for_generate(), &schema, product_def) {
let unique_field_name = unique_field_ident.deref().to_case(Case::Snake);
let unique_field_type = type_name(module, unique_field_type_use);
writeln!(
out,
"_table.add_unique_constraint::<{unique_field_type}>({unique_field_name:?}, |row| &row.{unique_field_name});",
);
}
},
"}",
);
if schema.pk().is_some() {
let update_callback_id = table_name_pascalcase.clone() + "UpdateCallbackId";
write!(
out,
"
pub struct {update_callback_id}(__sdk::CallbackId);
impl<'ctx> __sdk::TableWithPrimaryKey for {table_handle}<'ctx> {{
type UpdateCallbackId = {update_callback_id};
fn on_update(
&self,
callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static,
) -> {update_callback_id} {{
{update_callback_id}(self.imp.on_update(Box::new(callback)))
}}
fn remove_on_update(&self, callback: {update_callback_id}) {{
self.imp.remove_on_update(callback.0)
}}
}}
"
);
}
out.newline();
write!(
out,
"
#[doc(hidden)]
pub(super) fn parse_table_update(
raw_updates: __ws::TableUpdate<__ws::BsatnFormat>,
) -> __sdk::Result<__sdk::TableUpdate<{row_type}>> {{
__sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| {{
__sdk::InternalError::failed_parse(
\"TableUpdate<{row_type}>\",
\"TableUpdate\",
).with_cause(e).into()
}})
}}
"
);
for (unique_field_ident, unique_field_type_use) in
iter_unique_cols(module.typespace_for_generate(), &schema, product_def)
{
let unique_field_name = unique_field_ident.deref().to_case(Case::Snake);
let unique_field_name_pascalcase = unique_field_name.to_case(Case::Pascal);
let unique_constraint = table_name_pascalcase.clone() + &unique_field_name_pascalcase + "Unique";
let unique_field_type = type_name(module, unique_field_type_use);
write!(
out,
"
/// Access to the `{unique_field_name}` unique index on the table `{table_name}`,
/// which allows point queries on the field of the same name
/// via the [`{unique_constraint}::find`] method.
///
/// Users are encouraged not to explicitly reference this type,
/// but to directly chain method calls,
/// like `ctx.db.{accessor_method}().{unique_field_name}().find(...)`.
pub struct {unique_constraint}<'ctx> {{
imp: __sdk::UniqueConstraintHandle<{row_type}, {unique_field_type}>,
phantom: std::marker::PhantomData<&'ctx super::RemoteTables>,
}}
impl<'ctx> {table_handle}<'ctx> {{
/// Get a handle on the `{unique_field_name}` unique index on the table `{table_name}`.
pub fn {unique_field_name}(&self) -> {unique_constraint}<'ctx> {{
{unique_constraint} {{
imp: self.imp.get_unique_constraint::<{unique_field_type}>({unique_field_name:?}),
phantom: std::marker::PhantomData,
}}
}}
}}
impl<'ctx> {unique_constraint}<'ctx> {{
/// Find the subscribed row whose `{unique_field_name}` column value is equal to `col_val`,
/// if such a row is present in the client cache.
pub fn find(&self, col_val: &{unique_field_type}) -> Option<{row_type}> {{
self.imp.find(col_val)
}}
}}
"
);
}
// TODO: expose non-unique indices.
output.into_inner()
}
fn generate_reducer(&self, module: &ModuleDef, reducer: &ReducerDef) -> String {
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out);
out.newline();
gen_and_print_imports(
module,
out,
&reducer.params_for_generate.elements,
// No need to skip any imports; we're not emitting a type that other modules can import.
&[],
);
out.newline();
let reducer_name = reducer.name.deref();
let func_name = reducer_function_name(reducer);
let set_reducer_flags_trait = reducer_flags_trait_name(reducer);
let args_type = reducer_args_type_name(&reducer.name);
let enum_variant_name = reducer_variant_name(&reducer.name);
// Define an "args struct" for the reducer.
// This is not user-facing (note the `pub(super)` visibility);
// it is an internal helper for serialization and deserialization.
// We actually want to ser/de instances of `enum Reducer`, but:
// - `Reducer` will have struct-like variants, which SATS ser/de does not support.
// - The WS format does not contain a BSATN-serialized `Reducer` instance;
// it holds the reducer name or ID separately from the argument bytes.
// We could work up some magic with `DeserializeSeed`
// and/or custom `Serializer` and `Deserializer` types
// to account for this, but it's much easier to just use an intermediate struct per reducer.
define_struct_for_product(
module,
out,
&args_type,
&reducer.params_for_generate.elements,
"pub(super)",
);
out.newline();
let callback_id = reducer_callback_id_name(&reducer.name);
// The reducer arguments as `ident: ty, ident: ty, ident: ty,`,
// like an argument list.
let mut arglist = String::new();
write_arglist_no_delimiters(module, &mut arglist, &reducer.params_for_generate.elements, None).unwrap();
// The reducer argument types as `&ty, &ty, &ty`,
// for use as the params in a `FnMut` closure type.
let mut arg_types_ref_list = String::new();
// The reducer argument names as `ident, ident, ident`,
// for passing to function call and struct literal expressions.
let mut arg_names_list = String::new();
for (arg_ident, arg_ty) in &reducer.params_for_generate.elements[..] {
arg_types_ref_list += "&";
write_type(module, &mut arg_types_ref_list, arg_ty).unwrap();
arg_types_ref_list += ", ";
let arg_name = arg_ident.deref().to_case(Case::Snake);
arg_names_list += &arg_name;
arg_names_list += ", ";
}
write!(out, "impl From<{args_type}> for super::Reducer ");
out.delimited_block(
"{",
|out| {
write!(out, "fn from(args: {args_type}) -> Self ");
out.delimited_block(
"{",
|out| {
write!(out, "Self::{enum_variant_name}");
if !reducer.params_for_generate.elements.is_empty() {
// We generate "struct variants" for reducers with arguments,
// but "unit variants" for reducers of no arguments.
// These use different constructor syntax.
out.delimited_block(
" {",
|out| {
for (arg_ident, _ty) in &reducer.params_for_generate.elements[..] {
let arg_name = arg_ident.deref().to_case(Case::Snake);
writeln!(out, "{arg_name}: args.{arg_name},");
}
},
"}",
);
}
out.newline();
},
"}\n",
);
},
"}\n",
);
// TODO: check for lifecycle reducers and do not generate the invoke method.
writeln!(
out,
"
impl __sdk::InModule for {args_type} {{
type Module = super::RemoteModule;
}}
pub struct {callback_id}(__sdk::CallbackId);
#[allow(non_camel_case_types)]
/// Extension trait for access to the reducer `{reducer_name}`.
///
/// Implemented for [`super::RemoteReducers`].
pub trait {func_name} {{
/// Request that the remote module invoke the reducer `{reducer_name}` to run as soon as possible.
///
/// This method returns immediately, and errors only if we are unable to send the request.
/// The reducer will run asynchronously in the future,
/// and its status can be observed by listening for [`Self::on_{func_name}`] callbacks.
fn {func_name}(&self, {arglist}) -> __sdk::Result<()>;
/// Register a callback to run whenever we are notified of an invocation of the reducer `{reducer_name}`.
///
/// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`]
/// to determine the reducer's status.
///
/// The returned [`{callback_id}`] can be passed to [`Self::remove_on_{func_name}`]
/// to cancel the callback.
fn on_{func_name}(&self, callback: impl FnMut(&super::ReducerEventContext, {arg_types_ref_list}) + Send + 'static) -> {callback_id};
/// Cancel a callback previously registered by [`Self::on_{func_name}`],
/// causing it not to run in the future.
fn remove_on_{func_name}(&self, callback: {callback_id});
}}
impl {func_name} for super::RemoteReducers {{
fn {func_name}(&self, {arglist}) -> __sdk::Result<()> {{
self.imp.call_reducer({reducer_name:?}, {args_type} {{ {arg_names_list} }})
}}
fn on_{func_name}(
&self,
mut callback: impl FnMut(&super::ReducerEventContext, {arg_types_ref_list}) + Send + 'static,
) -> {callback_id} {{
{callback_id}(self.imp.on_reducer(
{reducer_name:?},
Box::new(move |ctx: &super::ReducerEventContext| {{
let super::ReducerEventContext {{
event: __sdk::ReducerEvent {{
reducer: super::Reducer::{enum_variant_name} {{
{arg_names_list}
}},
..
}},
..
}} = ctx else {{ unreachable!() }};
callback(ctx, {arg_names_list})
}}),
))
}}
fn remove_on_{func_name}(&self, callback: {callback_id}) {{
self.imp.remove_on_reducer({reducer_name:?}, callback.0)
}}
}}
#[allow(non_camel_case_types)]
#[doc(hidden)]
/// Extension trait for setting the call-flags for the reducer `{reducer_name}`.
///
/// Implemented for [`super::SetReducerFlags`].
///
/// This type is currently unstable and may be removed without a major version bump.
pub trait {set_reducer_flags_trait} {{
/// Set the call-reducer flags for the reducer `{reducer_name}` to `flags`.
///
/// This type is currently unstable and may be removed without a major version bump.
fn {func_name}(&self, flags: __ws::CallReducerFlags);
}}
impl {set_reducer_flags_trait} for super::SetReducerFlags {{
fn {func_name}(&self, flags: __ws::CallReducerFlags) {{
self.imp.set_call_reducer_flags({reducer_name:?}, flags);
}}
}}
"
);
output.into_inner()
}
fn generate_globals(&self, module: &ModuleDef) -> Vec<(String, String)> {
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out);
out.newline();
// Declare `pub mod` for each of the files generated.
print_module_decls(module, out);
out.newline();
// Re-export all the modules for the generated files.
print_module_reexports(module, out);
out.newline();
// Define `enum Reducer`.
print_reducer_enum_defn(module, out);
out.newline();
// Define `DbUpdate`.
print_db_update_defn(module, out);
out.newline();
// Define `AppliedDiff`.
print_applied_diff_defn(module, out);
out.newline();
// Define `RemoteModule`, `DbConnection`, `EventContext`, `RemoteTables`, `RemoteReducers` and `SubscriptionHandle`.
// Note that these do not change based on the module.
print_const_db_context_types(out);
out.newline();
// Implement `SpacetimeModule` for `RemoteModule`.
// This includes a method for initializing the tables in the client cache.
print_impl_spacetime_module(module, out);
vec![("mod.rs".to_string(), (output.into_inner()))]
}
}
pub fn write_type<W: Write>(module: &ModuleDef, out: &mut W, ty: &AlgebraicTypeUse) -> fmt::Result {
match ty {
AlgebraicTypeUse::Unit => write!(out, "()")?,
AlgebraicTypeUse::Never => write!(out, "std::convert::Infallible")?,
AlgebraicTypeUse::Identity => write!(out, "__sdk::Identity")?,
AlgebraicTypeUse::ConnectionId => write!(out, "__sdk::ConnectionId")?,
AlgebraicTypeUse::Timestamp => write!(out, "__sdk::Timestamp")?,
AlgebraicTypeUse::TimeDuration => write!(out, "__sdk::TimeDuration")?,
AlgebraicTypeUse::ScheduleAt => write!(out, "__sdk::ScheduleAt")?,
AlgebraicTypeUse::Option(inner_ty) => {
write!(out, "Option::<")?;
write_type(module, out, inner_ty)?;
write!(out, ">")?;
}
AlgebraicTypeUse::Primitive(prim) => match prim {
PrimitiveType::Bool => write!(out, "bool")?,
PrimitiveType::I8 => write!(out, "i8")?,
PrimitiveType::U8 => write!(out, "u8")?,
PrimitiveType::I16 => write!(out, "i16")?,
PrimitiveType::U16 => write!(out, "u16")?,
PrimitiveType::I32 => write!(out, "i32")?,
PrimitiveType::U32 => write!(out, "u32")?,
PrimitiveType::I64 => write!(out, "i64")?,
PrimitiveType::U64 => write!(out, "u64")?,
PrimitiveType::I128 => write!(out, "i128")?,
PrimitiveType::U128 => write!(out, "u128")?,
PrimitiveType::I256 => write!(out, "__sats::i256")?,
PrimitiveType::U256 => write!(out, "__sats::u256")?,
PrimitiveType::F32 => write!(out, "f32")?,
PrimitiveType::F64 => write!(out, "f64")?,
},
AlgebraicTypeUse::String => write!(out, "String")?,
AlgebraicTypeUse::Array(elem_ty) => {
write!(out, "Vec::<")?;
write_type(module, out, elem_ty)?;
write!(out, ">")?;
}
AlgebraicTypeUse::Ref(r) => {
write!(out, "{}", type_ref_name(module, *r))?;
}
}
Ok(())
}
pub fn type_name(module: &ModuleDef, ty: &AlgebraicTypeUse) -> String {
let mut s = String::new();
write_type(module, &mut s, ty).unwrap();
s
}
const ALLOW_LINTS: &str = "#![allow(unused, clippy::all)]";
const SPACETIMEDB_IMPORTS: &[&str] = &[
"use spacetimedb_sdk::__codegen::{",
"\tself as __sdk,",
"\t__lib,",
"\t__sats,",
"\t__ws,",
"};",
];
fn print_spacetimedb_imports(output: &mut Indenter) {
print_lines(output, SPACETIMEDB_IMPORTS);
}
fn print_file_header(output: &mut Indenter) {
print_auto_generated_file_comment(output);
writeln!(output, "{ALLOW_LINTS}");
print_spacetimedb_imports(output);
}
// TODO: figure out if/when sum types should derive:
// - Clone
// - Debug
// - Copy
// - PartialEq, Eq
// - Hash
// - Complicated because `HashMap` is not `Hash`.
// - others?
const ENUM_DERIVES: &[&str] = &[
"#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]",
"#[sats(crate = __lib)]",
];
fn print_enum_derives(output: &mut Indenter) {
print_lines(output, ENUM_DERIVES);
}
const PLAIN_ENUM_EXTRA_DERIVES: &[&str] = &["#[derive(Copy, Eq, Hash)]"];
fn print_plain_enum_extra_derives(output: &mut Indenter) {
print_lines(output, PLAIN_ENUM_EXTRA_DERIVES);
}
/// Generate a file which defines an `enum` corresponding to the `sum_type`.
pub fn define_enum_for_sum(
module: &ModuleDef,
out: &mut Indenter,
name: &str,
variants: &[(Identifier, AlgebraicTypeUse)],
is_plain: bool,
) {
print_enum_derives(out);
if is_plain {
print_plain_enum_extra_derives(out);
}
write!(out, "pub enum {name} ");
out.delimited_block(
"{",
|out| {
for (ident, ty) in variants {
write_enum_variant(module, out, ident, ty);
out.newline();
}
},
"}\n",
);
out.newline()
}
fn write_enum_variant(module: &ModuleDef, out: &mut Indenter, ident: &Identifier, ty: &AlgebraicTypeUse) {
let name = ident.deref().to_case(Case::Pascal);
write!(out, "{name}");
// If the contained type is the unit type, i.e. this variant has no members,
// write it without parens or braces, like
// ```
// Foo,
// ```
if !matches!(ty, AlgebraicTypeUse::Unit) {
// If the contained type is not a product, i.e. this variant has a single
// member, write it tuple-style, with parens.
write!(out, "(");
write_type(module, out, ty).unwrap();
write!(out, ")");
}
writeln!(out, ",");
}
fn write_struct_type_fields_in_braces(
module: &ModuleDef,
out: &mut Indenter,
elements: &[(Identifier, AlgebraicTypeUse)],
// Whether to print a `pub` qualifier on the fields. Necessary for `struct` defns,
// disallowed for `enum` defns.
pub_qualifier: bool,
) {
out.delimited_block(
"{",
|out| write_arglist_no_delimiters(module, out, elements, pub_qualifier.then_some("pub")).unwrap(),
"}",
);
}
fn write_arglist_no_delimiters(
module: &ModuleDef,
out: &mut impl Write,
elements: &[(Identifier, AlgebraicTypeUse)],
// Written before each line. Useful for `pub`.
prefix: Option<&str>,
) -> anyhow::Result<()> {
for (ident, ty) in elements {
if let Some(prefix) = prefix {
write!(out, "{prefix} ")?;
}
let name = ident.deref().to_case(Case::Snake);
write!(out, "{name}: ")?;
write_type(module, out, ty)?;
writeln!(out, ",")?;
}
Ok(())
}
// TODO: figure out if/when product types should derive:
// - Clone
// - Debug
// - Copy
// - PartialEq, Eq
// - Hash
// - Complicated because `HashMap` is not `Hash`.
// - others?
const STRUCT_DERIVES: &[&str] = &[
"#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]",
"#[sats(crate = __lib)]",
];
fn print_struct_derives(output: &mut Indenter) {
print_lines(output, STRUCT_DERIVES);
}
fn define_struct_for_product(
module: &ModuleDef,
out: &mut Indenter,
name: &str,
elements: &[(Identifier, AlgebraicTypeUse)],
vis: &str,
) {
print_struct_derives(out);
write!(out, "{vis} struct {name} ");
// TODO: if elements is empty, define a unit struct with no brace-delimited list of fields.
write_struct_type_fields_in_braces(
module, out, elements, true, // `pub`-qualify fields.
);
out.newline();
}
fn type_ref_module_name(module: &ModuleDef, type_ref: AlgebraicTypeRef) -> String {
let (name, _) = module.type_def_from_ref(type_ref).unwrap();
type_module_name(name)
}
fn type_module_name(type_name: &ScopedTypeName) -> String {
collect_case(Case::Snake, type_name.name_segments()) + "_type"
}
fn table_module_name(table_name: &Identifier) -> String {
table_name.deref().to_case(Case::Snake) + "_table"
}
fn table_method_name(table_name: &Identifier) -> String {
table_name.deref().to_case(Case::Snake)
}
fn table_access_trait_name(table_name: &Identifier) -> String {
table_name.deref().to_case(Case::Pascal) + "TableAccess"
}
fn reducer_args_type_name(reducer_name: &Identifier) -> String {
reducer_name.deref().to_case(Case::Pascal) + "Args"
}
fn reducer_variant_name(reducer_name: &Identifier) -> String {
reducer_name.deref().to_case(Case::Pascal)
}
fn reducer_callback_id_name(reducer_name: &Identifier) -> String {
reducer_name.deref().to_case(Case::Pascal) + "CallbackId"
}
fn reducer_module_name(reducer_name: &Identifier) -> String {
reducer_name.deref().to_case(Case::Snake) + "_reducer"
}
fn reducer_function_name(reducer: &ReducerDef) -> String {
reducer.name.deref().to_case(Case::Snake)
}
fn reducer_flags_trait_name(reducer: &ReducerDef) -> String {
format!("set_flags_for_{}", reducer_function_name(reducer))
}
/// Iterate over all of the Rust `mod`s for types, reducers and tables in the `module`.
fn iter_module_names(module: &ModuleDef) -> impl Iterator<Item = String> + '_ {
itertools::chain!(
iter_types(module).map(|ty| type_module_name(&ty.name)),
iter_reducers(module).map(|r| reducer_module_name(&r.name)),
iter_tables(module).map(|tbl| table_module_name(&tbl.name)),
)
}
/// Print `pub mod` declarations for all the files that will be generated for `items`.
fn print_module_decls(module: &ModuleDef, out: &mut Indenter) {
for module_name in iter_module_names(module) {
writeln!(out, "pub mod {module_name};");
}
}
/// Print appropriate reexports for all the files that will be generated for `items`.
fn print_module_reexports(module: &ModuleDef, out: &mut Indenter) {
for ty in iter_types(module) {
let mod_name = type_module_name(&ty.name);
let type_name = collect_case(Case::Pascal, ty.name.name_segments());
writeln!(out, "pub use {mod_name}::{type_name};")
}
for table in iter_tables(module) {
let mod_name = table_module_name(&table.name);
// TODO: More precise reexport: we want:
// - The trait name.
// - The insert, delete and possibly update callback ids.
// We do not want:
// - The table handle.
writeln!(out, "pub use {mod_name}::*;");
}
for reducer in iter_reducers(module) {
let mod_name = reducer_module_name(&reducer.name);
let reducer_trait_name = reducer_function_name(reducer);
let flags_trait_name = reducer_flags_trait_name(reducer);
let callback_id_name = reducer_callback_id_name(&reducer.name);
writeln!(
out,
"pub use {mod_name}::{{{reducer_trait_name}, {flags_trait_name}, {callback_id_name}}};"
);
}
}
fn print_reducer_enum_defn(module: &ModuleDef, out: &mut Indenter) {
// Don't derive ser/de on this enum;
// it's not a proper SATS enum and the derive will fail.
writeln!(out, "#[derive(Clone, PartialEq, Debug)]");
writeln!(
out,
"
/// One of the reducers defined by this module.
///
/// Contained within a [`__sdk::ReducerEvent`] in [`EventContext`]s for reducer events
/// to indicate which reducer caused the event.
",
);
out.delimited_block(
"pub enum Reducer {",
|out| {
for reducer in iter_reducers(module) {
write!(out, "{} ", reducer_variant_name(&reducer.name));
if !reducer.params_for_generate.elements.is_empty() {
// If the reducer has any arguments, generate a "struct variant,"
// like `Foo { bar: Baz, }`.
// If it doesn't, generate a "unit variant" instead,
// like `Foo,`.
write_struct_type_fields_in_braces(module, out, &reducer.params_for_generate.elements, false);
}
writeln!(out, ",");
}
},
"}\n",
);
out.newline();
writeln!(
out,
"
impl __sdk::InModule for Reducer {{
type Module = RemoteModule;
}}
",
);
out.delimited_block(
"impl __sdk::Reducer for Reducer {",
|out| {
out.delimited_block(
"fn reducer_name(&self) -> &'static str {",
|out| {
out.delimited_block(
"match self {",
|out| {
for reducer in iter_reducers(module) {
write!(out, "Reducer::{}", reducer_variant_name(&reducer.name));
if !reducer.params_for_generate.elements.is_empty() {
// Because we're emitting unit variants when the payload is empty,
// we will emit different patterns for empty vs non-empty variants.
// This is not strictly required;
// Rust allows matching a struct-like pattern
// against a unit-like enum variant,
// but we prefer the clarity of not including the braces for unit variants.
write!(out, " {{ .. }}");
}
writeln!(out, " => {:?},", reducer.name.deref());
}
},
"}\n",
);
},
"}\n",
);
},
"}\n",
);
out.delimited_block(
"impl TryFrom<__ws::ReducerCallInfo<__ws::BsatnFormat>> for Reducer {",
|out| {
writeln!(out, "type Error = __sdk::Error;");
// We define an "args struct" for each reducer in `generate_reducer`.
// This is not user-facing, and is not exported past the "root" `mod.rs`;
// it is an internal helper for serialization and deserialization.
// We actually want to ser/de instances of `enum Reducer`, but:
//
// - `Reducer` will have struct-like variants, which SATS ser/de does not support.
// - The WS format does not contain a BSATN-serialized `Reducer` instance;
// it holds the reducer name or ID separately from the argument bytes.
// We could work up some magic with `DeserializeSeed`
// and/or custom `Serializer` and `Deserializer` types
// to account for this, but it's much easier to just use an intermediate struct per reducer.
//
// As such, we deserialize from the `value.args` bytes into that "args struct,"
// then convert it into a `Reducer` variant via `Into::into`,
// which we also implement in `generate_reducer`.
out.delimited_block(
"fn try_from(value: __ws::ReducerCallInfo<__ws::BsatnFormat>) -> __sdk::Result<Self> {",
|out| {
out.delimited_block(
"match &value.reducer_name[..] {",
|out| {
for reducer in iter_reducers(module) {
writeln!(
out,
"{:?} => Ok(__sdk::parse_reducer_args::<{}::{}>({:?}, &value.args)?.into()),",
reducer.name.deref(),
reducer_module_name(&reducer.name),
reducer_args_type_name(&reducer.name),
reducer.name.deref(),
);
}
writeln!(
out,
"unknown => Err(__sdk::InternalError::unknown_name(\"reducer\", unknown, \"ReducerCallInfo\").into()),",
);
},
"}\n",
)
},
"}\n",
);
},
"}\n",
)
}
fn print_db_update_defn(module: &ModuleDef, out: &mut Indenter) {
writeln!(out, "#[derive(Default)]");
writeln!(out, "#[allow(non_snake_case)]");
writeln!(out, "#[doc(hidden)]");
out.delimited_block(
"pub struct DbUpdate {",
|out| {
for table in iter_tables(module) {
writeln!(
out,
"{}: __sdk::TableUpdate<{}>,",
table_method_name(&table.name),
type_ref_name(module, table.product_type_ref),
);
}
},
"}\n",
);
out.newline();
out.delimited_block(
"
impl TryFrom<__ws::DatabaseUpdate<__ws::BsatnFormat>> for DbUpdate {
type Error = __sdk::Error;
fn try_from(raw: __ws::DatabaseUpdate<__ws::BsatnFormat>) -> Result<Self, Self::Error> {
let mut db_update = DbUpdate::default();
for table_update in raw.tables {
match &table_update.table_name[..] {
",
|out| {