-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathcpp.rs
More file actions
690 lines (605 loc) · 27.7 KB
/
cpp.rs
File metadata and controls
690 lines (605 loc) · 27.7 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
//! Minimal C++ code generation for SpacetimeDB module definitions.
//! Generates only schema definitions - framework provides all functionality.
use crate::CodegenOptions;
use crate::Lang;
use crate::OutputFile;
use spacetimedb_lib::sats::layout::PrimitiveType;
use spacetimedb_schema::def::{ModuleDef, ReducerDef, TableDef, TypeDef};
use spacetimedb_schema::schema::TableSchema;
use spacetimedb_schema::type_for_generate::{
AlgebraicTypeDef, AlgebraicTypeUse, PlainEnumTypeDef, ProductTypeDef, SumTypeDef,
};
// Removed unused import
use std::collections::HashSet;
use std::fmt::{self, Write};
pub struct Cpp<'opts> {
pub namespace: &'opts str,
}
impl<'opts> Cpp<'opts> {
fn cpp_field_name<'a>(&self, field_name: &'a str) -> &'a str {
match field_name {
"alignas" | "alignof" | "and" | "and_eq" | "asm" | "atomic_cancel" | "atomic_commit"
| "atomic_noexcept" | "auto" | "bitand" | "bitor" | "bool" | "break" | "case" | "catch" | "char"
| "char8_t" | "char16_t" | "char32_t" | "class" | "compl" | "concept" | "const" | "consteval"
| "constexpr" | "constinit" | "const_cast" | "continue" | "co_await" | "co_return" | "co_yield"
| "decltype" | "default" | "delete" | "do" | "double" | "dynamic_cast" | "else" | "enum" | "explicit"
| "export" | "extern" | "false" | "float" | "for" | "friend" | "goto" | "if" | "inline" | "int"
| "long" | "mutable" | "namespace" | "new" | "noexcept" | "not" | "not_eq" | "nullptr" | "operator"
| "or" | "or_eq" | "private" | "protected" | "public" | "register" | "reinterpret_cast" | "requires"
| "return" | "short" | "signed" | "sizeof" | "static" | "static_assert" | "static_cast" | "struct"
| "switch" | "template" | "this" | "thread_local" | "throw" | "true" | "try" | "typedef" | "typeid"
| "typename" | "union" | "unsigned" | "using" | "virtual" | "void" | "volatile" | "wchar_t" | "while"
| "xor" | "xor_eq" => "",
_ => field_name,
}
}
fn write_cpp_field_name(&self, output: &mut String, field_name: &str) -> fmt::Result {
let escaped = self.cpp_field_name(field_name);
if escaped.is_empty() {
write!(output, "{}_", field_name)
} else {
write!(output, "{}", escaped)
}
}
fn is_recursive_mount_module_field(&self, type_name: &str, field_name: &str) -> bool {
type_name == "RawModuleMountV10" && field_name == "module"
}
fn write_header_comment(&self, output: &mut String) {
writeln!(
output,
"// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE"
)
.unwrap();
writeln!(
output,
"// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD."
)
.unwrap();
writeln!(output).unwrap();
writeln!(output, "// This was generated using spacetimedb codegen.").unwrap();
writeln!(output).unwrap();
}
fn write_standard_includes(&self, output: &mut String) {
writeln!(output, "#pragma once").unwrap();
writeln!(output).unwrap();
writeln!(output, "#include <cstdint>").unwrap();
writeln!(output, "#include <string>").unwrap();
writeln!(output, "#include <vector>").unwrap();
writeln!(output, "#include <optional>").unwrap();
writeln!(output, "#include <memory>").unwrap();
writeln!(output, "#include \"../autogen_base.h\"").unwrap();
writeln!(output, "#include \"spacetimedb/bsatn/bsatn.h\"").unwrap();
}
fn cpp_primitive_type(&self, p: &PrimitiveType) -> &'static str {
match p {
PrimitiveType::Bool => "bool",
PrimitiveType::I8 => "int8_t",
PrimitiveType::U8 => "uint8_t",
PrimitiveType::I16 => "int16_t",
PrimitiveType::U16 => "uint16_t",
PrimitiveType::I32 => "int32_t",
PrimitiveType::U32 => "uint32_t",
PrimitiveType::I64 => "int64_t",
PrimitiveType::U64 => "uint64_t",
PrimitiveType::I128 => "SpacetimeDB::I128",
PrimitiveType::U128 => "SpacetimeDB::U128",
PrimitiveType::I256 => "SpacetimeDB::I256",
PrimitiveType::U256 => "SpacetimeDB::U256",
PrimitiveType::F32 => "float",
PrimitiveType::F64 => "double",
}
}
fn write_algebraic_type(&self, output: &mut String, module: &ModuleDef, typ: &AlgebraicTypeUse) -> fmt::Result {
match typ {
AlgebraicTypeUse::Primitive(p) => write!(output, "{}", self.cpp_primitive_type(p)),
AlgebraicTypeUse::Array(elem_type) => {
write!(output, "std::vector<")?;
self.write_algebraic_type(output, module, elem_type)?;
write!(output, ">")
}
AlgebraicTypeUse::Option(inner_type) => {
write!(output, "std::optional<")?;
self.write_algebraic_type(output, module, inner_type)?;
write!(output, ">")
}
AlgebraicTypeUse::Result { .. } => {
write!(output, "__sdk::Result")
}
AlgebraicTypeUse::String => write!(output, "std::string"),
AlgebraicTypeUse::Identity => write!(output, "__sdk::Identity"),
AlgebraicTypeUse::ConnectionId => write!(output, "__sdk::ConnectionId"),
AlgebraicTypeUse::Timestamp => write!(output, "__sdk::Timestamp"),
AlgebraicTypeUse::TimeDuration => write!(output, "__sdk::TimeDuration"),
AlgebraicTypeUse::ScheduleAt => write!(output, "__sdk::ScheduleAt"),
AlgebraicTypeUse::Uuid => write!(output, "__sdk::Uuid"),
AlgebraicTypeUse::Unit => write!(output, "std::monostate"),
AlgebraicTypeUse::Never => write!(output, "std::monostate"),
AlgebraicTypeUse::Ref(type_ref) => {
if let Some((type_name, _type_def)) = module.type_def_from_ref(*type_ref) {
let name = type_name.name().to_string();
write!(output, "{}::{}", self.namespace, name)
} else {
write!(output, "UnknownType /* ref {} */", type_ref.idx())
}
}
}
}
fn collect_dependencies(module: &ModuleDef, typ: &AlgebraicTypeUse) -> HashSet<String> {
let mut deps = HashSet::new();
match typ {
AlgebraicTypeUse::Array(elem_type) | AlgebraicTypeUse::Option(elem_type) => {
deps.extend(Self::collect_dependencies(module, elem_type));
}
AlgebraicTypeUse::Ref(type_ref) => {
if let Some((type_name, _)) = module.type_def_from_ref(*type_ref) {
deps.insert(type_name.name().to_string());
}
}
_ => {}
}
deps
}
fn collect_product_dependencies(&self, module: &ModuleDef, product: &ProductTypeDef) -> HashSet<String> {
let mut deps = HashSet::new();
for (_, field_type) in &product.elements {
deps.extend(Self::collect_dependencies(module, field_type));
}
deps
}
fn collect_sum_dependencies(&self, module: &ModuleDef, sum: &SumTypeDef) -> HashSet<String> {
let mut deps = HashSet::new();
for (_, variant_type) in &sum.variants {
deps.extend(Self::collect_dependencies(module, variant_type));
}
deps
}
// Generate minimal product type (struct with fields only)
fn write_product_type(&self, output: &mut String, module: &ModuleDef, type_name: &str, product: &ProductTypeDef) {
// Use INTERNAL macro for Internal namespace
let macro_name = if self.namespace == "SpacetimeDB::Internal" {
"SPACETIMEDB_INTERNAL_PRODUCT_TYPE"
} else {
"SPACETIMEDB_PRODUCT_TYPE"
};
writeln!(output, "{}({}) {{", macro_name, type_name).unwrap();
// Write fields only
for (field_name, field_type) in &product.elements {
write!(output, " ").unwrap();
if self.is_recursive_mount_module_field(type_name, field_name) {
// Temporary special-case to preserve the recursive RawModuleMountV10 ->
// RawModuleDefV10 shape while breaking the include cycle in generated C++.
write!(output, "std::shared_ptr<{}::RawModuleDefV10>", self.namespace).unwrap();
} else {
self.write_algebraic_type(output, module, field_type).unwrap();
}
write!(output, " ").unwrap();
self.write_cpp_field_name(output, field_name).unwrap();
writeln!(output, ";").unwrap();
}
writeln!(output).unwrap();
// Only generate serialization for Internal types (no deserialization needed)
writeln!(
output,
" void bsatn_serialize(::SpacetimeDB::bsatn::Writer& writer) const {{"
)
.unwrap();
for (field_name, _) in &product.elements {
if self.is_recursive_mount_module_field(type_name, field_name) {
write!(output, " ::SpacetimeDB::bsatn::serialize(writer, *").unwrap();
self.write_cpp_field_name(output, field_name).unwrap();
writeln!(output, ");").unwrap();
} else {
write!(output, " ::SpacetimeDB::bsatn::serialize(writer, ").unwrap();
self.write_cpp_field_name(output, field_name).unwrap();
writeln!(output, ");").unwrap();
}
}
writeln!(output, " }}").unwrap();
// Generate equality method
if type_name == "RawModuleMountV10" {
// Pointer equality is sufficient for this internal autogen type. Mounts are not
// emitted by the C++ module path yet; this exists to keep the schema shape aligned.
writeln!(output, " SPACETIMEDB_PRODUCT_TYPE_EQUALITY(namespace_, module)").unwrap();
} else if !product.elements.is_empty() {
write!(output, " SPACETIMEDB_PRODUCT_TYPE_EQUALITY(").unwrap();
for (i, (field_name, _)) in product.elements.iter().enumerate() {
if i > 0 {
write!(output, ", ").unwrap();
}
self.write_cpp_field_name(output, field_name).unwrap();
}
writeln!(output, ")").unwrap();
}
writeln!(output, "}};").unwrap();
}
fn generate_raw_module_mount_v10_special(&self) -> String {
// RawModuleMountV10 is special for two reasons:
// 1. Its `namespace` field is a C++ keyword, renamed to `namespace_`.
// 2. It contains `RawModuleDefV10` which creates a circular include chain:
// RawModuleMountV10 → RawModuleDefV10 → RawModuleDefV10Section → RawModuleMountV10
// We break this with a forward declaration and shared_ptr (which only needs a declaration).
r#"// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
// This was generated using spacetimedb codegen.
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <optional>
#include <memory>
#include "../autogen_base.h"
#include "spacetimedb/bsatn/bsatn.h"
// Forward declaration breaks the circular include chain:
// RawModuleMountV10 -> RawModuleDefV10 -> RawModuleDefV10Section -> RawModuleMountV10
namespace SpacetimeDB::Internal { struct RawModuleDefV10; }
namespace SpacetimeDB::Internal {
SPACETIMEDB_INTERNAL_PRODUCT_TYPE(RawModuleMountV10) {
std::string namespace_; // renamed: 'namespace' is a C++ keyword
std::shared_ptr<SpacetimeDB::Internal::RawModuleDefV10> module; // shared_ptr breaks infinite-size recursion
void bsatn_serialize(::SpacetimeDB::bsatn::Writer& writer) const {
::SpacetimeDB::bsatn::serialize(writer, namespace_);
if (module) ::SpacetimeDB::bsatn::serialize(writer, *module);
}
bool operator==(const RawModuleMountV10& o) const noexcept {
if (namespace_ != o.namespace_) return false;
if (module && o.module) return *module == *o.module;
return !module && !o.module;
}
bool operator!=(const RawModuleMountV10& o) const noexcept { return !(*this == o); }
};
} // namespace SpacetimeDB::Internal
"#
.to_string()
}
// Generate minimal sum type (TaggedEnum only)
fn write_sum_type(&self, output: &mut String, module: &ModuleDef, type_name: &str, sum: &SumTypeDef) {
// Special case: Generate proper tagged enum for RawIndexAlgorithm with data variants
if type_name == "RawIndexAlgorithm" {
// Generate data structures for each algorithm variant
writeln!(output, "// BTree algorithm data").unwrap();
writeln!(
output,
"SPACETIMEDB_INTERNAL_PRODUCT_TYPE(RawIndexAlgorithmBTreeData) {{"
)
.unwrap();
writeln!(output, " std::vector<uint16_t> columns;").unwrap();
writeln!(
output,
" void bsatn_serialize(::SpacetimeDB::bsatn::Writer& writer) const {{"
)
.unwrap();
writeln!(output, " ::SpacetimeDB::bsatn::serialize(writer, columns);").unwrap();
writeln!(output, " }}").unwrap();
writeln!(output, " SPACETIMEDB_PRODUCT_TYPE_EQUALITY(columns)").unwrap();
writeln!(output, "}};").unwrap();
writeln!(output).unwrap();
// Generate Hash data structure (for future use)
writeln!(output, "// Hash algorithm data (not currently used)").unwrap();
writeln!(
output,
"SPACETIMEDB_INTERNAL_PRODUCT_TYPE(RawIndexAlgorithmHashData) {{"
)
.unwrap();
writeln!(output, " std::vector<uint16_t> columns;").unwrap();
writeln!(
output,
" void bsatn_serialize(::SpacetimeDB::bsatn::Writer& writer) const {{"
)
.unwrap();
writeln!(output, " ::SpacetimeDB::bsatn::serialize(writer, columns);").unwrap();
writeln!(output, " }}").unwrap();
writeln!(output, " SPACETIMEDB_PRODUCT_TYPE_EQUALITY(columns)").unwrap();
writeln!(output, "}};").unwrap();
writeln!(output).unwrap();
// Generate Direct data structure (not currently used)
writeln!(output, "// Direct algorithm data (not currently used)").unwrap();
writeln!(
output,
"SPACETIMEDB_INTERNAL_PRODUCT_TYPE(RawIndexAlgorithmDirectData) {{"
)
.unwrap();
writeln!(output, " uint16_t column;").unwrap();
writeln!(
output,
" void bsatn_serialize(::SpacetimeDB::bsatn::Writer& writer) const {{"
)
.unwrap();
writeln!(output, " ::SpacetimeDB::bsatn::serialize(writer, column);").unwrap();
writeln!(output, " }}").unwrap();
writeln!(output, " SPACETIMEDB_PRODUCT_TYPE_EQUALITY(column)").unwrap();
writeln!(output, "}};").unwrap();
writeln!(output).unwrap();
// Generate the tagged enum
writeln!(output, "// RawIndexAlgorithm tagged enum with data variants").unwrap();
writeln!(output, "SPACETIMEDB_INTERNAL_TAGGED_ENUM({}, ", type_name).unwrap();
writeln!(output, " SpacetimeDB::Internal::RawIndexAlgorithmBTreeData,").unwrap();
writeln!(output, " SpacetimeDB::Internal::RawIndexAlgorithmHashData,").unwrap();
writeln!(output, " SpacetimeDB::Internal::RawIndexAlgorithmDirectData").unwrap();
writeln!(output, ")").unwrap();
return;
}
// Use INTERNAL macro for Internal namespace
let macro_name = if self.namespace == "SpacetimeDB::Internal" {
"SPACETIMEDB_INTERNAL_TAGGED_ENUM"
} else {
"SPACETIMEDB_TAGGED_ENUM"
};
// Collect variant types and check for duplicates
let mut variant_types = Vec::new();
let mut type_strings = Vec::new();
for (variant_name, variant_type) in &sum.variants {
let mut type_str = String::new();
self.write_algebraic_type(&mut type_str, module, variant_type).unwrap();
// Check if this type already exists
let duplicate_index = type_strings.iter().position(|s| s == &type_str);
if let Some(_idx) = duplicate_index {
// Found duplicate - create a wrapper struct to make it unique
let wrapper_name = format!("{}_{}_Wrapper", type_name, variant_name);
let wrapper_macro = if self.namespace == "SpacetimeDB::Internal" {
"SPACETIMEDB_INTERNAL_PRODUCT_TYPE"
} else {
"SPACETIMEDB_PRODUCT_TYPE"
};
writeln!(output, "{}({}) {{", wrapper_macro, wrapper_name).unwrap();
writeln!(output, " {} value;", type_str).unwrap();
writeln!(
output,
" void bsatn_serialize(::SpacetimeDB::bsatn::Writer& writer) const {{"
)
.unwrap();
writeln!(output, " ::SpacetimeDB::bsatn::serialize(writer, value);").unwrap();
writeln!(output, " }}").unwrap();
writeln!(output, " SPACETIMEDB_PRODUCT_TYPE_EQUALITY(value)").unwrap();
writeln!(output, "}};").unwrap();
variant_types.push(wrapper_name);
} else {
// No duplicate, use the type directly
type_strings.push(type_str.clone());
variant_types.push(type_str);
}
}
// Generate the tagged enum with (potentially wrapped) variant types
write!(output, "{}({}", macro_name, type_name).unwrap();
if !variant_types.is_empty() {
write!(output, ", ").unwrap();
for (i, variant_type) in variant_types.iter().enumerate() {
if i > 0 {
write!(output, ", ").unwrap();
}
write!(output, "{}", variant_type).unwrap();
}
}
writeln!(output, ")").unwrap();
}
// Generate minimal plain enum
fn write_plain_enum(&self, output: &mut String, type_name: &str, plain_enum: &PlainEnumTypeDef) {
writeln!(output, "enum class {} : uint8_t {{", type_name).unwrap();
for (i, variant) in plain_enum.variants.iter().enumerate() {
writeln!(output, " {} = {},", variant, i).unwrap();
}
writeln!(output, "}};").unwrap();
}
// Special generation for AlgebraicType to handle circular dependencies
fn generate_algebraic_type_special(&self) -> String {
r#"// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE
// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD.
// This was generated using spacetimedb codegen.
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <optional>
#include <memory>
#include <variant>
#include "spacetimedb/bsatn/bsatn.h"
#include "../forward_declarations.h"
namespace SpacetimeDB::Internal {
// AlgebraicType is special - it uses pointers to break circular dependencies
// This is a custom implementation due to circular references between:
// AlgebraicType -> SumType -> SumTypeVariant -> AlgebraicType
// AlgebraicType -> ProductType -> ProductTypeElement -> AlgebraicType
class AlgebraicType {
public:
enum class Tag : uint8_t {
Ref = 0,
Sum = 1,
Product = 2,
Array = 3,
String = 4,
Bool = 5,
I8 = 6,
U8 = 7,
I16 = 8,
U16 = 9,
I32 = 10,
U32 = 11,
I64 = 12,
U64 = 13,
I128 = 14,
U128 = 15,
I256 = 16,
U256 = 17,
F32 = 18,
F64 = 19
};
using DataType = std::variant<
uint32_t, // Ref
std::unique_ptr<SpacetimeDB::Internal::SumType>, // Sum
std::unique_ptr<SpacetimeDB::Internal::ProductType>, // Product
std::unique_ptr<SpacetimeDB::Internal::AlgebraicType>, // Array element type
std::monostate // All primitive types (String, Bool, I8, U8, etc.)
>;
private:
Tag tag_;
DataType data_;
public:
AlgebraicType();
AlgebraicType(Tag primitive_tag);
AlgebraicType(const AlgebraicType& other);
AlgebraicType& operator=(const AlgebraicType& other);
Tag get_tag() const { return tag_; }
template<size_t Index>
const auto& get() const { return std::get<Index>(data_); }
template<size_t Index>
auto& get() { return std::get<Index>(data_); }
template<size_t Index, typename T>
void set(T&& value);
template<size_t Index>
bool is() const { return tag_ == static_cast<Tag>(Index); }
template<typename Visitor>
auto visit(Visitor&& visitor) const -> decltype(auto) {
return std::visit(std::forward<Visitor>(visitor), data_);
}
template<typename Visitor>
auto visit(Visitor&& visitor) -> decltype(auto) {
return std::visit(std::forward<Visitor>(visitor), data_);
}
void bsatn_serialize(::SpacetimeDB::bsatn::Writer& writer) const;
bool operator==(const AlgebraicType& other) const;
bool operator!=(const AlgebraicType& other) const { return !(*this == other); }
};
} // namespace SpacetimeDB::Internal
"#
.to_string()
}
}
impl Lang for Cpp<'_> {
fn generate_table_file_from_schema(
&self,
module: &ModuleDef,
table: &TableDef,
_schema: TableSchema,
) -> OutputFile {
let mut output = String::new();
self.write_header_comment(&mut output);
self.write_standard_includes(&mut output);
// Add includes for dependencies
if let Some(AlgebraicTypeDef::Product(product)) = module.typespace_for_generate().get(table.product_type_ref) {
let deps = self.collect_product_dependencies(module, product);
for dep in deps {
if dep != table.name.to_string() {
writeln!(output, "#include \"{}.g.h\"", dep).unwrap();
}
}
}
writeln!(output).unwrap();
writeln!(output, "namespace {} {{", self.namespace).unwrap();
writeln!(output).unwrap();
// Generate table as a product type
if let Some(AlgebraicTypeDef::Product(product)) = module.typespace_for_generate().get(table.product_type_ref) {
self.write_product_type(&mut output, module, &table.name, product);
}
writeln!(output, "}} // namespace {}", self.namespace).unwrap();
OutputFile {
filename: format!("{}.g.h", table.name),
code: output,
}
}
fn generate_type_files(&self, module: &ModuleDef, type_def: &TypeDef) -> Vec<OutputFile> {
let mut output = String::new();
self.write_header_comment(&mut output);
let name = type_def.accessor_name.name();
// Special handling for AlgebraicType due to circular dependencies
if name.to_string() == "AlgebraicType" {
return vec![OutputFile {
filename: format!("{name}.g.h"),
code: self.generate_algebraic_type_special(),
}];
}
// Special handling for RawModuleMountV10:
// (1) its `namespace` field is a C++ keyword; (2) its `module` field creates a
// circular include chain through RawModuleDefV10 → RawModuleDefV10Section.
// We break both with a forward declaration and shared_ptr.
if name.to_string() == "RawModuleMountV10" {
return vec![OutputFile {
filename: format!("{name}.g.h"),
code: self.generate_raw_module_mount_v10_special(),
}];
}
self.write_standard_includes(&mut output);
// Add includes for dependencies
let deps = match module.typespace_for_generate().get(type_def.ty) {
Some(AlgebraicTypeDef::Product(product)) => self.collect_product_dependencies(module, product),
Some(AlgebraicTypeDef::Sum(sum)) => self.collect_sum_dependencies(module, sum),
Some(AlgebraicTypeDef::PlainEnum(_)) => HashSet::new(),
None => HashSet::new(),
};
let type_name = name.to_string();
for dep in deps {
if dep != type_name && !(type_name == "RawModuleMountV10" && dep == "RawModuleDefV10") {
writeln!(output, "#include \"{}.g.h\"", dep).unwrap();
}
}
writeln!(output).unwrap();
if type_name == "RawModuleMountV10" {
writeln!(output, "namespace {} {{", self.namespace).unwrap();
writeln!(output, "struct RawModuleDefV10;").unwrap();
writeln!(output, "}} // namespace {}", self.namespace).unwrap();
writeln!(output).unwrap();
}
writeln!(output, "namespace {} {{", self.namespace).unwrap();
writeln!(output).unwrap();
match module.typespace_for_generate().get(type_def.ty) {
Some(AlgebraicTypeDef::Product(product)) => {
self.write_product_type(&mut output, module, name, product);
}
Some(AlgebraicTypeDef::Sum(sum)) => {
self.write_sum_type(&mut output, module, name, sum);
}
Some(AlgebraicTypeDef::PlainEnum(plain_enum)) => {
self.write_plain_enum(&mut output, name, plain_enum);
}
None => {
writeln!(output, "// ERROR: Could not resolve type definition for {}", name).unwrap();
}
}
writeln!(output, "}} // namespace {}", self.namespace).unwrap();
vec![OutputFile {
filename: format!("{name}.g.h"),
code: output,
}]
}
fn generate_reducer_file(&self, _module: &ModuleDef, reducer: &ReducerDef) -> OutputFile {
let mut output = String::new();
self.write_header_comment(&mut output);
self.write_standard_includes(&mut output);
writeln!(output).unwrap();
writeln!(output, "namespace {} {{", self.namespace).unwrap();
writeln!(output).unwrap();
writeln!(output, "// Reducer: {}", reducer.name).unwrap();
writeln!(output, "// This file is intentionally minimal - reducer implementation").unwrap();
writeln!(output, "// is handled by the SpacetimeDB framework.").unwrap();
writeln!(output, "}} // namespace {}", self.namespace).unwrap();
OutputFile {
filename: format!("{}.g.h", reducer.name),
code: output,
}
}
fn generate_procedure_file(
&self,
_module: &ModuleDef,
procedure: &spacetimedb_schema::def::ProcedureDef,
) -> OutputFile {
let mut output = String::new();
self.write_header_comment(&mut output);
self.write_standard_includes(&mut output);
writeln!(output).unwrap();
writeln!(output, "namespace {} {{", self.namespace).unwrap();
writeln!(output).unwrap();
writeln!(output, "// Procedure: {}", procedure.name).unwrap();
writeln!(
output,
"// This file is intentionally minimal - procedure implementation"
)
.unwrap();
writeln!(output, "// is handled by the SpacetimeDB framework.").unwrap();
writeln!(output, "}} // namespace {}", self.namespace).unwrap();
OutputFile {
filename: format!("{}.g.h", procedure.name),
code: output,
}
}
fn generate_global_files(&self, _module: &ModuleDef, _options: &CodegenOptions) -> Vec<OutputFile> {
vec![]
}
}