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---
title: Generated Code Reference
sidebar_position: 5
id: fdl_generated_code
license: |
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---
This document explains the code generated by the FDL compiler for each target language.
## Example Schema
The examples in this document use this FDL schema:
```proto
package demo;
enum Status [id=100] {
PENDING = 0;
ACTIVE = 1;
COMPLETED = 2;
}
message User [id=101] {
string id = 1;
string name = 2;
optional string email = 3;
int32 age = 4;
}
message Order [id=102] {
string id = 1;
ref User customer = 2;
repeated string items = 3;
map<string, int32> quantities = 4;
Status status = 5;
}
```
## Enum Prefix Stripping
When enum values use a protobuf-style prefix (enum name in UPPER_SNAKE_CASE), the compiler automatically strips the prefix for languages with scoped enums. This produces cleaner, more idiomatic code.
**Input FDL:**
```proto
enum DeviceTier {
DEVICE_TIER_UNKNOWN = 0;
DEVICE_TIER_TIER1 = 1;
DEVICE_TIER_TIER2 = 2;
}
```
**Generated output by language:**
| Language | Generated Values | Notes |
| -------- | ----------------------------------------- | ------------------------- |
| Java | `UNKNOWN, TIER1, TIER2` | Scoped enum |
| Rust | `Unknown, Tier1, Tier2` | PascalCase variants |
| C++ | `UNKNOWN, TIER1, TIER2` | Scoped `enum class` |
| Python | `UNKNOWN, TIER1, TIER2` | Scoped `IntEnum` |
| Go | `DeviceTierUnknown, DeviceTierTier1, ...` | Unscoped, prefix re-added |
**Note:** Go uses unscoped constants, so the enum name prefix is added back to avoid naming collisions.
## Nested Types
When using nested message and enum definitions, the generated code varies by language.
**Input FDL:**
```proto
message SearchResponse {
message Result {
string url = 1;
string title = 2;
}
repeated Result results = 1;
}
```
### Java - Inner Classes
```java
public class SearchResponse {
public static class Result {
private String url;
private String title;
// getters, setters...
}
private List<Result> results;
// getters, setters...
}
```
### Python - Nested Classes
```python
@dataclass
class SearchResponse:
@dataclass
class Result:
url: str = ""
title: str = ""
results: List[Result] = field(default_factory=list)
```
### Go - Underscore
```go
type SearchResponse_Result struct {
Url string
Title string
}
type SearchResponse struct {
Results []SearchResponse_Result
}
```
**Note:** Set `option (fory).go_nested_type_style = "camelcase";` to generate `SearchResponseResult` instead.
### Rust - Nested Module
```rust
pub mod search_response {
use super::*;
#[derive(ForyObject)]
pub struct Result {
pub url: String,
pub title: String,
}
}
#[derive(ForyObject)]
pub struct SearchResponse {
pub results: Vec<search_response::Result>,
}
```
### C++ - Nested Classes
```cpp
class SearchResponse final {
public:
class Result final {
public:
std::string url;
std::string title;
};
std::vector<Result> results;
};
FORY_STRUCT(SearchResponse::Result, url, title);
FORY_STRUCT(SearchResponse, results);
```
**Summary:**
| Language | Approach | Syntax Example |
| -------- | ------------------------- | ------------------------- |
| Java | Static inner classes | `SearchResponse.Result` |
| Python | Nested dataclasses | `SearchResponse.Result` |
| Go | Underscore (configurable) | `SearchResponse_Result` |
| Rust | Nested module | `search_response::Result` |
| C++ | Nested classes | `SearchResponse::Result` |
## Java
### Enum Generation
```java
package demo;
public enum Status {
PENDING,
ACTIVE,
COMPLETED;
}
```
### Message Generation
```java
package demo;
import java.util.List;
import java.util.Map;
import org.apache.fory.annotation.ForyField;
public class User {
private String id;
private String name;
@ForyField(nullable = true)
private String email;
private int age;
public User() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
```java
package demo;
import java.util.List;
import java.util.Map;
import org.apache.fory.annotation.ForyField;
public class Order {
private String id;
@ForyField(ref = true)
private User customer;
private List<String> items;
private Map<String, Integer> quantities;
private Status status;
public Order() {
}
// Getters and setters...
}
```
### Registration Helper
```java
package demo;
import org.apache.fory.Fory;
public class DemoForyRegistration {
public static void register(Fory fory) {
fory.register(Status.class, 100);
fory.register(User.class, 101);
fory.register(Order.class, 102);
}
}
```
### Usage
```java
import demo.*;
import org.apache.fory.Fory;
import org.apache.fory.config.Language;
public class Example {
public static void main(String[] args) {
Fory fory = Fory.builder()
.withLanguage(Language.XLANG)
.withRefTracking(true)
.build();
DemoForyRegistration.register(fory);
User user = new User();
user.setId("u123");
user.setName("Alice");
user.setAge(30);
Order order = new Order();
order.setId("o456");
order.setCustomer(user);
order.setStatus(Status.ACTIVE);
byte[] bytes = fory.serialize(order);
Order restored = (Order) fory.deserialize(bytes);
}
}
```
## Python
### Module Generation
```python
# Licensed to the Apache Software Foundation (ASF)...
from dataclasses import dataclass
from enum import IntEnum
from typing import Dict, List, Optional
import pyfory
class Status(IntEnum):
PENDING = 0
ACTIVE = 1
COMPLETED = 2
@dataclass
class User:
id: str = ""
name: str = ""
email: Optional[str] = None
age: pyfory.int32 = 0
@dataclass
class Order:
id: str = ""
customer: Optional[User] = None
items: List[str] = None
quantities: Dict[str, pyfory.int32] = None
status: Status = None
def register_demo_types(fory: pyfory.Fory):
fory.register_type(Status, type_id=100)
fory.register_type(User, type_id=101)
fory.register_type(Order, type_id=102)
```
### Usage
```python
import pyfory
from demo import User, Order, Status, register_demo_types
fory = pyfory.Fory(ref_tracking=True)
register_demo_types(fory)
user = User(id="u123", name="Alice", age=30)
order = Order(
id="o456",
customer=user,
items=["item1", "item2"],
quantities={"item1": 2, "item2": 1},
status=Status.ACTIVE
)
data = fory.serialize(order)
restored = fory.deserialize(data)
```
## Go
### File Generation
```go
// Licensed to the Apache Software Foundation (ASF)...
package demo
import (
fory "github.com/apache/fory/go/fory"
)
type Status int32
const (
StatusPending Status = 0
StatusActive Status = 1
StatusCompleted Status = 2
)
type User struct {
Id string
Name string
Email *string `fory:"nullable"`
Age int32
}
type Order struct {
Id string
Customer *User `fory:"ref"`
Items []string
Quantities map[string]int32
Status Status
}
func RegisterTypes(f *fory.Fory) error {
if err := f.RegisterEnum(Status(0), 100); err != nil {
return err
}
if err := f.Register(User{}, 101); err != nil {
return err
}
if err := f.Register(Order{}, 102); err != nil {
return err
}
return nil
}
```
### Usage
```go
package main
import (
"demo"
fory "github.com/apache/fory/go/fory"
)
func main() {
f := fory.NewFory(true) // Enable ref tracking
if err := demo.RegisterTypes(f); err != nil {
panic(err)
}
email := "alice@example.com"
user := &demo.User{
Id: "u123",
Name: "Alice",
Email: &email,
Age: 30,
}
order := &demo.Order{
Id: "o456",
Customer: user,
Items: []string{"item1", "item2"},
Quantities: map[string]int32{
"item1": 2,
"item2": 1,
},
Status: demo.StatusActive,
}
bytes, err := f.Marshal(order)
if err != nil {
panic(err)
}
var restored demo.Order
if err := f.Unmarshal(bytes, &restored); err != nil {
panic(err)
}
}
```
## Rust
### Module Generation
```rust
// Licensed to the Apache Software Foundation (ASF)...
use fory::{Fory, ForyObject};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(ForyObject, Debug, Clone, PartialEq, Default)]
#[repr(i32)]
pub enum Status {
#[default]
Pending = 0,
Active = 1,
Completed = 2,
}
#[derive(ForyObject, Debug, Clone, PartialEq, Default)]
pub struct User {
pub id: String,
pub name: String,
#[fory(nullable = true)]
pub email: Option<String>,
pub age: i32,
}
#[derive(ForyObject, Debug, Clone, PartialEq, Default)]
pub struct Order {
pub id: String,
pub customer: Arc<User>,
pub items: Vec<String>,
pub quantities: HashMap<String, i32>,
pub status: Status,
}
pub fn register_types(fory: &mut Fory) -> Result<(), fory::Error> {
fory.register::<Status>(100)?;
fory.register::<User>(101)?;
fory.register::<Order>(102)?;
Ok(())
}
```
**Note:** Rust uses `Arc` by default for `ref` fields. Set
`[(fory).thread_safe_pointer = false]` to generate `Rc` instead.
### Usage
```rust
use demo::{User, Order, Status, register_types};
use fory::Fory;
use std::sync::Arc;
use std::collections::HashMap;
fn main() -> Result<(), fory::Error> {
let mut fory = Fory::default();
register_types(&mut fory)?;
let user = Arc::new(User {
id: "u123".to_string(),
name: "Alice".to_string(),
email: Some("alice@example.com".to_string()),
age: 30,
});
let mut quantities = HashMap::new();
quantities.insert("item1".to_string(), 2);
quantities.insert("item2".to_string(), 1);
let order = Order {
id: "o456".to_string(),
customer: user,
items: vec!["item1".to_string(), "item2".to_string()],
quantities,
status: Status::Active,
};
let bytes = fory.serialize(&order)?;
let restored: Order = fory.deserialize(&bytes)?;
Ok(())
}
```
## C++
### Header Generation
```cpp
/*
* Licensed to the Apache Software Foundation (ASF)...
*/
#ifndef DEMO_H_
#define DEMO_H_
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include "fory/serialization/fory.h"
namespace demo {
struct User;
struct Order;
enum class Status : int32_t {
PENDING = 0,
ACTIVE = 1,
COMPLETED = 2,
};
FORY_ENUM(Status, PENDING, ACTIVE, COMPLETED);
struct User {
std::string id;
std::string name;
std::optional<std::string> email;
int32_t age;
bool operator==(const User& other) const {
return id == other.id && name == other.name &&
email == other.email && age == other.age;
}
};
FORY_STRUCT(User, id, name, email, age);
struct Order {
std::string id;
std::shared_ptr<User> customer;
std::vector<std::string> items;
std::map<std::string, int32_t> quantities;
Status status;
bool operator==(const Order& other) const {
return id == other.id && customer == other.customer &&
items == other.items && quantities == other.quantities &&
status == other.status;
}
};
FORY_STRUCT(Order, id, customer, items, quantities, status);
inline void RegisterTypes(fory::serialization::Fory& fory) {
fory.register_enum<Status>(100);
fory.register_struct<User>(101);
fory.register_struct<Order>(102);
}
} // namespace demo
#endif // DEMO_H_
```
### Usage
```cpp
#include "demo.h"
#include <iostream>
int main() {
fory::serialization::Fory fory = fory::serialization::Fory::builder()
.xlang(true)
.ref_tracking(true)
.build();
demo::RegisterTypes(fory);
auto user = std::make_shared<demo::User>();
user->id = "u123";
user->name = "Alice";
user->email = "alice@example.com";
user->age = 30;
demo::Order order;
order.id = "o456";
order.customer = user;
order.items = {"item1", "item2"};
order.quantities = {{"item1", 2}, {"item2", 1}};
order.status = demo::Status::ACTIVE;
auto bytes = fory.serialize(order);
auto restored = fory.deserialize<demo::Order>(bytes);
return 0;
}
```
## Generated Annotations Summary
### Java Annotations
| Annotation | Purpose |
| ----------------------------- | -------------------------- |
| `@ForyField(nullable = true)` | Marks field as nullable |
| `@ForyField(ref = true)` | Enables reference tracking |
### Python Type Hints
| Hint | Purpose |
| -------------- | ------------------- |
| `Optional[T]` | Nullable field |
| `List[T]` | Repeated field |
| `Dict[K, V]` | Map field |
| `pyfory.int32` | Fixed-width integer |
### Go Struct Tags
| Tag | Purpose |
| ----------------- | -------------------------- |
| `fory:"nullable"` | Marks field as nullable |
| `fory:"ref"` | Enables reference tracking |
### Rust Attributes
| Attribute | Purpose |
| -------------------------- | -------------------------- |
| `#[derive(ForyObject)]` | Enables Fory serialization |
| `#[fory(nullable = true)]` | Marks field as nullable |
| `#[tag("...")]` | Name-based registration |
| `#[repr(i32)]` | Enum representation |
### C++ Macros
| Macro | Purpose |
| ---------------------------- | ----------------------- |
| `FORY_STRUCT(T[, fields..])` | Registers struct fields |
| `FORY_ENUM(T, values..)` | Registers enum values |
## Name-Based Registration
When types don't have explicit type IDs, they use namespace-based registration:
### FDL
```proto
package myapp.models;
message Config { // No @id
string key = 1;
string value = 2;
}
```
### Generated Registration
**Java:**
```java
fory.register(Config.class, "myapp.models", "Config");
```
**Python:**
```python
fory.register_type(Config, namespace="myapp.models", typename="Config")
```
**Go:**
```go
f.RegisterTagType("myapp.models.Config", Config{})
```
**Rust:**
```rust
#[derive(ForyObject)]
#[tag("myapp.models.Config")]
pub struct Config { ... }
```
**C++:**
```cpp
fory.register_struct<Config>("myapp.models", "Config");
```
## Customization
### Extending Generated Code
Generated code can be extended through language-specific mechanisms:
**Java:** Use inheritance or composition:
```java
public class ExtendedUser extends User {
public String getDisplayName() {
return getName() + " <" + getEmail() + ">";
}
}
```
**Python:** Add methods after import:
```python
from demo import User
def get_display_name(self):
return f"{self.name} <{self.email}>"
User.get_display_name = get_display_name
```
**Go:** Use separate file in same package:
```go
package demo
func (u *User) DisplayName() string {
return u.Name + " <" + *u.Email + ">"
}
```
**Rust:** Use trait extensions:
```rust
trait UserExt {
fn display_name(&self) -> String;
}
impl UserExt for User {
fn display_name(&self) -> String {
format!("{} <{}>", self.name, self.email.as_deref().unwrap_or(""))
}
}
```
**C++:** Use inheritance or free functions:
```cpp
std::string display_name(const demo::User& user) {
return user.name + " <" + user.email.value_or("") + ">";
}
```