-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathrust.rs
More file actions
2118 lines (1875 loc) · 76 KB
/
rust.rs
File metadata and controls
2118 lines (1875 loc) · 76 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_indexes, iter_procedures, iter_table_names_and_types, iter_tables, iter_types, iter_unique_cols, iter_views,
print_auto_generated_file_comment, print_auto_generated_version_comment, CodegenVisibility,
};
use crate::CodegenOptions;
use crate::OutputFile;
use convert_case::{Case, Casing};
use spacetimedb_lib::sats::layout::PrimitiveType;
use spacetimedb_lib::sats::AlgebraicTypeRef;
use spacetimedb_schema::def::{ModuleDef, ProcedureDef, ReducerDef, ScopedTypeName, TableDef, TypeDef};
use spacetimedb_schema::identifier::Identifier;
use spacetimedb_schema::reducer_name::ReducerName;
use spacetimedb_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 generate_type_files(&self, module: &ModuleDef, typ: &TypeDef) -> Vec<OutputFile> {
let type_name = collect_case(Case::Pascal, typ.accessor_name.name_segments());
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out, false);
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;
}}
",
);
// Do not implement query col types for nested types.
// as querying is only supported on top-level table row types.
let name = type_ref_name(module, typ.ty);
let implemented = match module
.tables()
.find(|t| type_ref_name(module, t.product_type_ref) == name)
{
Some(table) => {
implement_query_col_types_for_table_struct(module, out, table)
.expect("failed to implement query col types");
out.newline();
true
}
_ => false,
};
if !implemented
&& let Some(type_ref) = module
.views()
.map(|v| v.product_type_ref)
.find(|type_ref| type_ref_name(module, *type_ref) == name)
{
implement_query_col_types_for_struct(module, out, type_ref).expect("failed to implement query col types");
out.newline();
}
vec![OutputFile {
filename: type_module_name(&typ.accessor_name) + ".rs",
code: output.into_inner(),
}]
}
fn generate_table_file_from_schema(&self, module: &ModuleDef, table: &TableDef, schema: TableSchema) -> OutputFile {
let type_ref = table.product_type_ref;
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out, false);
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.accessor_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.accessor_name);
let accessor_method = table_method_name(&table.accessor_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);
"
);
if table.is_event {
// Event tables: implement the `EventTable` trait, which exposes only on-insert callbacks,
// not on-delete or on-update.
// on-update callbacks aren't meaningful for event tables,
// as they never have resident rows, so they can never update an existing row.
// on-delete callbacks are meaningful, but exactly equivalent to the on-insert callbacks,
// so not particularly useful.
// Also, don't emit unique index accessors: no resident rows means these would always be empty,
// so no reason to have them.
write!(
out,
"
impl<'ctx> __sdk::TableLike 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() }}
}}
impl<'ctx> __sdk::WithInsert for {table_handle}<'ctx> {{
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)
}}
}}
impl<'ctx> __sdk::EventTable for {table_handle}<'ctx> {{}}
"
);
} else {
// Non-event tables: implement the `Table` trait, which exposes on-insert and on-delete callbacks.
// Also possibly implement `TableWithPrimrayKey`, which exposes on-update callbacks,
// and emit accessors for unique columns.
write!(
out,
"pub struct {delete_callback_id}(__sdk::CallbackId);
impl<'ctx> __sdk::TableLike 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() }}
}}
impl<'ctx> __sdk::WithInsert for {table_handle}<'ctx> {{
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)
}}
}}
impl<'ctx> __sdk::WithDelete for {table_handle}<'ctx> {{
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)
}}
}}
impl<'ctx> __sdk::Table for {table_handle}<'ctx> {{}}
"
);
if table.primary_key.is_some() {
// If the table has a primary key, implement the `TableWithPrimaryKey` trait
// to expose on-update callbacks.
let update_callback_id = table_name_pascalcase.clone() + "UpdateCallbackId";
write!(
out,
"
pub struct {update_callback_id}(__sdk::CallbackId);
impl<'ctx> __sdk::WithUpdate 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)
}}
}}
impl<'ctx> __sdk::TableWithPrimaryKey for {table_handle}<'ctx> {{}}
"
);
}
// Emit unique index accessors for all of the table's unique fields.
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.
}
// Regardless of event-ness, emit `register_table` and `parse_table_update`.
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});",
);
}
},
"}",
);
out.newline();
write!(
out,
"
#[doc(hidden)]
pub(super) fn parse_table_update(
raw_updates: __ws::v2::TableUpdate,
) -> __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()
}})
}}
"
);
implement_query_table_accessor(table, out, &row_type).expect("failed to implement query table accessor");
OutputFile {
filename: table_module_name(&table.accessor_name) + ".rs",
code: output.into_inner(),
}
}
fn generate_reducer_file(&self, module: &ModuleDef, reducer: &ReducerDef) -> OutputFile {
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out, false);
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 args_type = function_args_type_name(&reducer.accessor_name);
let enum_variant_name = reducer_variant_name(&reducer.accessor_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 FormattedArglist {
arglist_no_delimiters,
arg_names,
} = FormattedArglist::for_arguments(module, &reducer.params_for_generate.elements);
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;
}}
#[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 this method provides no way to listen for its completion status.
/// /// Use [`{func_name}:{func_name}_then`] to run a callback after the reducer completes.
fn {func_name}(&self, {arglist_no_delimiters}) -> __sdk::Result<()> {{
self.{func_name}_then({arg_names} |_, _| {{}})
}}
/// Request that the remote module invoke the reducer `{reducer_name}` to run as soon as possible,
/// registering `callback` to run when we are notified that the reducer completed.
///
/// 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 with the `callback`.
fn {func_name}_then(
&self,
{arglist_no_delimiters}
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
+ Send
+ 'static,
) -> __sdk::Result<()>;
}}
impl {func_name} for super::RemoteReducers {{
fn {func_name}_then(
&self,
{arglist_no_delimiters}
callback: impl FnOnce(&super::ReducerEventContext, Result<Result<(), String>, __sdk::InternalError>)
+ Send
+ 'static,
) -> __sdk::Result<()> {{
self.imp.invoke_reducer_with_callback({args_type} {{ {arg_names} }}, callback)
}}
}}
"
);
OutputFile {
filename: reducer_module_name(&reducer.accessor_name) + ".rs",
code: output.into_inner(),
}
}
fn generate_procedure_file(&self, module: &ModuleDef, procedure: &ProcedureDef) -> OutputFile {
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out, false);
out.newline();
let mut imports = Imports::new();
gen_imports(&mut imports, &procedure.params_for_generate.elements);
add_one_import(&mut imports, &procedure.return_type_for_generate);
print_imports(module, out, imports);
out.newline();
let procedure_name = procedure.name.deref();
let func_name = procedure_function_name(procedure);
let func_name_with_callback = procedure_function_with_callback_name(procedure);
let args_type = function_args_type_name(&procedure.accessor_name);
let res_ty_name = type_name(module, &procedure.return_type_for_generate);
// Define an "args struct" as a serialization helper.
// This is not user-facing, it's not used outside this file.
// Unlike with reducers, we don't have to deserialize procedure args to build events,
// as we don't broadcast procedure args.
define_struct_for_product(
module,
out,
&args_type,
&procedure.params_for_generate.elements,
// non-pub visibility.
"",
);
out.newline();
let FormattedArglist {
arglist_no_delimiters,
arg_names,
..
} = FormattedArglist::for_arguments(module, &procedure.params_for_generate.elements);
writeln!(
out,
"
impl __sdk::InModule for {args_type} {{
type Module = super::RemoteModule;
}}
#[allow(non_camel_case_types)]
/// Extension trait for access to the procedure `{procedure_name}`.
///
/// Implemented for [`super::RemoteProcedures`].
pub trait {func_name} {{
fn {func_name}(&self, {arglist_no_delimiters}) {{
self.{func_name_with_callback}({arg_names} |_, _| {{}});
}}
fn {func_name_with_callback}(
&self,
{arglist_no_delimiters}
__callback: impl FnOnce(&super::ProcedureEventContext, Result<{res_ty_name}, __sdk::InternalError>) + Send + 'static,
);
}}
impl {func_name} for super::RemoteProcedures {{
fn {func_name_with_callback}(
&self,
{arglist_no_delimiters}
__callback: impl FnOnce(&super::ProcedureEventContext, Result<{res_ty_name}, __sdk::InternalError>) + Send + 'static,
) {{
self.imp.invoke_procedure_with_callback::<_, {res_ty_name}>(
{procedure_name:?},
{args_type} {{ {arg_names} }},
__callback,
);
}}
}}
"
);
OutputFile {
filename: procedure_module_name(&procedure.accessor_name) + ".rs",
code: output.into_inner(),
}
}
fn generate_global_files(&self, module: &ModuleDef, options: &CodegenOptions) -> Vec<OutputFile> {
let mut output = CodeIndenter::new(String::new(), INDENT);
let out = &mut output;
print_file_header(out, true);
out.newline();
// Declare `pub mod` for each of the files generated.
print_module_decls(module, options.visibility, out);
out.newline();
// Re-export all the modules for the generated files.
print_module_reexports(module, options.visibility, out);
out.newline();
// Define `enum Reducer`.
print_reducer_enum_defn(module, options.visibility, out);
out.newline();
// Define `DbUpdate`.
print_db_update_defn(module, options.visibility, out);
out.newline();
// Define `AppliedDiff`.
print_applied_diff_defn(module, options.visibility, out);
out.newline();
// Define `RemoteModule`, `DbConnection`, `EventContext`, `RemoteTables`,
// `RemoteReducers`, `RemoteProcedures` 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, options.visibility, out);
vec![OutputFile {
filename: "mod.rs".to_string(),
code: output.into_inner(),
}]
}
}
/// Implements `HasCols` for the given `AlgebraicTypeRef` struct type.
fn implement_query_col_types_for_struct(
module: &ModuleDef,
out: &mut impl Write,
type_ref: AlgebraicTypeRef,
) -> fmt::Result {
let struct_name = type_ref_name(module, type_ref);
let cols_struct = struct_name.clone() + "Cols";
let product_def = module.typespace_for_generate()[type_ref]
.as_product()
.expect("expected product type");
writeln!(
out,
"
/// Column accessor struct for the table `{struct_name}`.
///
/// Provides typed access to columns for query building.
pub struct {cols_struct} {{"
)?;
for element in &product_def.elements {
let field_name = &element.0.deref().to_case(Case::Snake);
let field_type = type_name(module, &element.1);
writeln!(
out,
" pub {field_name}: __sdk::__query_builder::Col<{struct_name}, {field_type}>,"
)?;
}
writeln!(out, "}}")?;
writeln!(
out,
"
impl __sdk::__query_builder::HasCols for {struct_name} {{
type Cols = {cols_struct};
fn cols(table_name: &'static str) -> Self::Cols {{
{cols_struct} {{"
)?;
for element in &product_def.elements {
let field_name = &element.0.deref().to_case(Case::Snake);
writeln!(
out,
" {field_name}: __sdk::__query_builder::Col::new(table_name, {field_name:?}),"
)?;
}
writeln!(
out,
r#"
}}
}}
}}"#
)
}
/// Implements `HasCols` and `HasIxCols` for the given table's row struct type.
fn implement_query_col_types_for_table_struct(
module: &ModuleDef,
out: &mut impl Write,
table: &TableDef,
) -> fmt::Result {
let type_ref = table.product_type_ref;
let struct_name = type_ref_name(module, type_ref);
implement_query_col_types_for_struct(module, out, type_ref)?;
let cols_ix = struct_name.clone() + "IxCols";
writeln!(
out,
"
/// Indexed column accessor struct for the table `{struct_name}`.
///
/// Provides typed access to indexed columns for query building.
pub struct {cols_ix} {{"
)?;
for index in iter_indexes(table) {
let cols = index.algorithm.columns();
if cols.len() != 1 {
continue;
}
let column = table
.columns
.iter()
.find(|col| col.col_id == cols.as_singleton().expect("singleton column"))
.unwrap();
let field_name = column.accessor_name.deref().to_case(Case::Snake);
let field_type = type_name(module, &column.ty_for_generate);
writeln!(
out,
" pub {field_name}: __sdk::__query_builder::IxCol<{struct_name}, {field_type}>,",
)?;
}
writeln!(out, "}}")?;
writeln!(
out,
"
impl __sdk::__query_builder::HasIxCols for {struct_name} {{
type IxCols = {cols_ix};
fn ix_cols(table_name: &'static str) -> Self::IxCols {{
{cols_ix} {{"
)?;
for index in iter_indexes(table) {
let cols = index.algorithm.columns();
if cols.len() != 1 {
continue;
}
let column = table
.columns
.iter()
.find(|col| col.col_id == cols.as_singleton().expect("singleton column"))
.expect("singleton column");
let field_name = column.accessor_name.deref().to_case(Case::Snake);
let col_name = column.name.deref();
writeln!(
out,
" {field_name}: __sdk::__query_builder::IxCol::new(table_name, {col_name:?}),",
)?;
}
writeln!(
out,
r#"
}}
}}
}}"#
)?;
// Event tables cannot be used as lookup tables in semijoins.
if !table.is_event {
writeln!(
out,
"\nimpl __sdk::__query_builder::CanBeLookupTable for {struct_name} {{}}"
)?;
}
Ok(())
}
pub fn implement_query_table_accessor(table: &TableDef, out: &mut impl Write, struct_name: &String) -> fmt::Result {
// NEW: Generate query table accessor trait and implementation
let accessor_method = table_method_name(&table.accessor_name);
let table_name = table.name.deref();
let query_accessor_trait = accessor_method.to_string() + "QueryTableAccess";
writeln!(
out,
"
#[allow(non_camel_case_types)]
/// Extension trait for query builder access to the table `{struct_name}`.
///
/// Implemented for [`__sdk::QueryTableAccessor`].
pub trait {query_accessor_trait} {{
#[allow(non_snake_case)]
/// Get a query builder for the table `{struct_name}`.
fn {accessor_method}(&self) -> __sdk::__query_builder::Table<{struct_name}>;
}}
impl {query_accessor_trait} for __sdk::QueryTableAccessor {{
fn {accessor_method}(&self) -> __sdk::__query_builder::Table<{struct_name}> {{
__sdk::__query_builder::Table::new({table_name:?})
}}
}}
"
)
}
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::Uuid => write!(out, "__sdk::Uuid")?,
AlgebraicTypeUse::ScheduleAt => write!(out, "__sdk::ScheduleAt")?,
AlgebraicTypeUse::Option(inner_ty) => {
write!(out, "Option::<")?;
write_type(module, out, inner_ty)?;
write!(out, ">")?;
}
AlgebraicTypeUse::Result { ok_ty, err_ty } => {
write!(out, "Result::<")?;
write_type(module, out, ok_ty)?;
write!(out, ", ")?;
write_type(module, out, err_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
}
/// Arguments to a reducer or procedure pretty-printed in various ways that are convenient to compute together.
struct FormattedArglist {
/// The arguments as `ident: ty, ident: ty, ident: ty,`,
/// like an argument list.
///
/// Always carries a trailing comma, unless it's zero elements.
arglist_no_delimiters: String,
/// The argument names as `ident, ident, ident,`,
/// for passing to function call and struct literal expressions.
///
/// Always carries a trailing comma, unless it's zero elements.
arg_names: String,
}
impl FormattedArglist {
fn for_arguments(module: &ModuleDef, params: &[(Identifier, AlgebraicTypeUse)]) -> Self {
let mut arglist_no_delimiters = String::new();
write_arglist_no_delimiters(module, &mut arglist_no_delimiters, params, None)
.expect("Writing to a String failed... huh?");
let mut arg_names = String::new();
for (arg_ident, _) in params {
let arg_name = arg_ident.deref().to_case(Case::Snake);
arg_names += &arg_name;
arg_names += ", ";
}
Self {
arglist_no_delimiters,
arg_names,
}
}
}
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, include_version: bool) {
print_auto_generated_file_comment(output);
if include_version {
print_auto_generated_version_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) {