-
Notifications
You must be signed in to change notification settings - Fork 546
/
Copy pathRustGenerator.js
222 lines (197 loc) · 6.29 KB
/
RustGenerator.js
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
/**
* @fileOverview This file is used by the api class generator in another repo
* but is checked in here so that it's updated in lockstep with rust code that expects it.
*/
import { AssociationType, Type, ValueType } from "../src/common/api/common/EntityConstants.js"
/**
* @param p {object}
* @param p.type {import("../src/common/api/common/EntityTypes.js").TypeModel}
* @param p.modelName {string}
* @return {string}
*/
export function generateRustType({ type, modelName }) {
let typeName = mapTypeName(type.name, modelName)
let buf = `#[derive(uniffi::Record, Clone, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "testing"), derive(PartialEq, Debug))]
pub struct ${typeName} {\n`
for (let [valueName, valueProperties] of Object.entries(type.values)) {
const rustType = rustValueType(valueName, type, valueProperties)
if (valueName === "type") {
buf += `\t#[serde(rename = "type")]\n`
buf += `\tpub r#type: ${rustType},\n`
} else if (valueProperties.type === "Bytes") {
buf += `\t#[serde(with = "serde_bytes")]\n`
buf += `\tpub ${valueName}: ${rustType},\n`
} else {
buf += `\tpub ${valueName}: ${rustType},\n`
}
}
for (let [associationName, associationProperties] of Object.entries(type.associations)) {
const innerRustType = rustAssociationType(associationProperties)
let rustType
switch (associationProperties.cardinality) {
case "ZeroOrOne":
rustType = `Option<${innerRustType}>`
break
case "Any":
rustType = `Vec<${innerRustType}>`
break
case "One":
rustType = innerRustType
break
}
if (associationName === "type") {
buf += `\t#[serde(rename = "type")]\n`
buf += `\tpub r#type: ${rustType},\n`
} else {
buf += `\tpub ${associationName}: ${rustType},\n`
}
}
if (type.encrypted) {
buf += `\tpub _errors: Option<Errors>,\n`
}
// aggregates do not say whether they are encrypted or not. For some reason!
if (type.encrypted || Object.values(type.values).some((v) => v.encrypted)) {
buf += `\tpub _finalIvs: HashMap<String, FinalIv>,\n`
}
buf += "}"
buf += `
impl Entity for ${typeName} {
fn type_ref() -> TypeRef {
TypeRef {
app: "${modelName}",
type_: "${typeName}",
}
}
}`
return buf
}
export function generateRustServiceDefinition(appName, appVersion, services) {
let imports = new Set([
"#![allow(unused_imports, dead_code, unused_variables)]",
"use crate::ApiCallError;",
"use crate::entities::Entity;",
"use crate::services::{PostService, GetService, PutService, DeleteService, Service, Executor, ExtraServiceParams};",
"use crate::bindings::rest_client::HttpMethod;",
"use crate::services::hidden::Nothing;",
])
const code = services
.map((s) => {
let serviceDefinition = `
pub struct ${s.name};
crate::service_impl!(declare, ${s.name}, "${appName}/${s.name.toLowerCase()}", ${appVersion});
`
function getTypeRef(dataType) {
if (dataType) {
return `Some(${dataType}::type_ref())`
} else {
return "None"
}
}
function addImports(appName, input, output) {
if (input) {
imports.add(`use crate::entities::generated::${appName}::${input};`)
}
if (output) {
imports.add(`use crate::entities::generated::${appName}::${output};`)
}
}
function makeImpl(name, input, output) {
addImports(appName, input, output)
return `crate::service_impl!(${name}, ${s.name}, ${input ?? "()"}, ${output ?? "()"});\n`
}
if (s.bodyTypes.POST_IN || s.bodyTypes.POST_OUT) {
serviceDefinition += makeImpl("POST", s.bodyTypes.POST_IN, s.bodyTypes.POST_OUT)
}
if (s.bodyTypes.GET_IN || s.bodyTypes.GET_OUT) {
serviceDefinition += makeImpl("GET", s.bodyTypes.GET_IN, s.bodyTypes.GET_OUT)
}
if (s.bodyTypes.PUT_IN || s.bodyTypes.PUT_OUT) {
serviceDefinition += makeImpl("PUT", s.bodyTypes.PUT_IN, s.bodyTypes.PUT_OUT)
}
if (s.bodyTypes.DELETE_IN || s.bodyTypes.DELETE_OUT) {
serviceDefinition += makeImpl("DELETE", s.bodyTypes.DELETE_IN, s.bodyTypes.DELETE_OUt)
}
return serviceDefinition
})
.join("\n")
return "// @generated\n" + Array.from(imports).join("\n") + code
}
/**
* @param types {string[]}
* @return {string}
*/
export function combineRustTypes(types) {
if (types.length === 0) return "\n"
return `// @generated
#![allow(non_snake_case, unused_imports)]
use super::super::*;
use crate::*;
use serde::{Deserialize, Serialize};
${types.join("\n\n")}
`
}
/**
* @param name {string}
* @param modelName {string}
* @return {string}
*/
function mapTypeName(name, modelName) {
if (name === "File" && modelName === "tutanota") return "TutanotaFile"
if (name === "Exception" && modelName === "sys") return "SysException"
return name
}
/**
* @param valueName {string}
* @param type {import("../src/common/api/common/EntityTypes.js").TypeModel}
* @param value {import("../src/common/api/common/EntityTypes.js").ModelValue}
* @return {string}
*/
function rustValueType(valueName, type, value) {
const ValueToRustTypes = Object.freeze({
String: "String",
Number: "i64",
Bytes: "Vec<u8>",
Date: "DateTime",
Boolean: "bool",
GeneratedId: "GeneratedId",
CustomId: "CustomId",
CompressedString: "String",
})
let innerType
if (valueName === "_id" && (type.type === Type.ListElement || type.type === Type.BlobElement)) {
if (value.type === ValueType.CustomId) {
innerType = "Option<IdTupleCustom>"
} else {
innerType = "Option<IdTupleGenerated>"
}
} else if (valueName === "_id") {
innerType = `Option<${ValueToRustTypes[value.type]}>`
} else {
innerType = ValueToRustTypes[value.type]
}
if (value.cardinality === "ZeroOrOne") {
return `Option<${innerType}>`
} else {
return innerType
}
}
/**
* @param association {import("../src/common/api/common/EntityTypes.js").ModelAssociation}
* @return {string}
*/
function rustAssociationType(association) {
if (association.type === AssociationType.Aggregation) {
if (association.dependency) {
return `super::${association.dependency}::${association.refType}`
} else {
return association.refType
}
} else if (association.type === AssociationType.ListElementAssociationCustom) {
return "IdTupleCustom"
} else if (association.type === AssociationType.ListElementAssociationGenerated || association.type === AssociationType.BlobElementAssociation) {
return "IdTupleGenerated" // blob ids are also always generated
} else {
return "GeneratedId"
}
}