-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathadditional_cpp_generator.rs
352 lines (321 loc) · 12 KB
/
additional_cpp_generator.rs
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
// Copyright 2020 Google LLC
//
// Licensed 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
//
// https://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.
use crate::types::{make_ident, type_to_cpp, Namespace, TypeName};
use itertools::Itertools;
use std::collections::HashSet;
use syn::{parse_quote, Ident, Type};
#[derive(Clone)]
enum ArgumentConversionType {
None,
FromUniquePtrToValue,
FromValueToUniquePtr,
}
#[derive(Clone)]
pub(crate) struct ArgumentConversion {
unwrapped_type: Type,
conversion: ArgumentConversionType,
}
impl ArgumentConversion {
pub(crate) fn new_unconverted(ty: Type) -> Self {
ArgumentConversion {
unwrapped_type: ty,
conversion: ArgumentConversionType::None,
}
}
pub(crate) fn new_to_unique_ptr(ty: Type) -> Self {
ArgumentConversion {
unwrapped_type: ty,
conversion: ArgumentConversionType::FromValueToUniquePtr,
}
}
pub(crate) fn new_from_unique_ptr(ty: Type) -> Self {
ArgumentConversion {
unwrapped_type: ty,
conversion: ArgumentConversionType::FromUniquePtrToValue,
}
}
pub(crate) fn work_needed(&self) -> bool {
!matches!(self.conversion, ArgumentConversionType::None)
}
fn unconverted_type(&self) -> String {
match self.conversion {
ArgumentConversionType::FromUniquePtrToValue => self.wrapped_type(),
_ => self.unwrapped_type_as_string(),
}
}
fn converted_type(&self) -> String {
match self.conversion {
ArgumentConversionType::FromValueToUniquePtr => self.wrapped_type(),
_ => self.unwrapped_type_as_string(),
}
}
pub(crate) fn unconverted_rust_type(&self) -> Type {
match self.conversion {
ArgumentConversionType::FromValueToUniquePtr => self.make_unique_ptr_type(),
_ => self.unwrapped_type.clone(),
}
}
pub(crate) fn converted_rust_type(&self) -> Type {
match self.conversion {
ArgumentConversionType::FromUniquePtrToValue => self.make_unique_ptr_type(),
_ => self.unwrapped_type.clone(),
}
}
fn unwrapped_type_as_string(&self) -> String {
type_to_cpp(&self.unwrapped_type, TypeName::from_cxx_type_path)
}
fn wrapped_type(&self) -> String {
format!("std::unique_ptr<{}>", self.unwrapped_type_as_string())
}
fn conversion(&self, var_name: &str) -> String {
match self.conversion {
ArgumentConversionType::None => var_name.to_string(),
ArgumentConversionType::FromUniquePtrToValue => format!("std::move(*{})", var_name),
ArgumentConversionType::FromValueToUniquePtr => format!(
"std::make_unique<{}>({})",
self.unconverted_type(),
var_name
),
}
}
fn make_unique_ptr_type(&self) -> Type {
let innerty = match &self.unwrapped_type {
Type::Path(typ) => {
// Until cxx supports a hierarchic set of inner mods
// for namespace purposes, we just take the final segment.
let final_seg = typ.path.segments.last().unwrap();
parse_quote! {
#final_seg
}
}
_ => self.unwrapped_type.clone(),
};
parse_quote! {
UniquePtr < #innerty >
}
}
}
pub(crate) struct ByValueWrapper {
pub(crate) original_function_name: Ident,
pub(crate) original_function_ns: Namespace,
pub(crate) wrapper_function_name: Ident,
pub(crate) return_conversion: Option<ArgumentConversion>,
pub(crate) argument_conversion: Vec<ArgumentConversion>,
pub(crate) is_a_method: bool,
}
/// Instructions for new C++ which we need to generate.
pub(crate) enum AdditionalNeed {
MakeStringConstructor,
MakeUnique(TypeName, Vec<TypeName>),
ByValueWrapper(Box<ByValueWrapper>),
}
#[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Hash)]
struct Header {
name: &'static str,
system: bool,
}
impl Header {
fn system(name: &'static str) -> Self {
Header { name, system: true }
}
fn user(name: &'static str) -> Self {
Header {
name,
system: false,
}
}
fn include_stmt(&self) -> String {
if self.system {
format!("#include <{}>", self.name)
} else {
format!("#include \"{}\"", self.name)
}
}
}
struct AdditionalFunction {
declaration: String,
definition: String,
headers: Vec<Header>,
}
/// Details of additional generated C++.
pub(crate) struct AdditionalCpp {
pub(crate) declarations: String,
pub(crate) definitions: String,
}
/// Generates additional C++ glue functions needed by autocxx.
/// In some ways it would be preferable to be able to pass snippets
/// of C++ through to `cxx` for inclusion in the C++ file which it
/// generates, and perhaps we'll explore that in future. But for now,
/// autocxx generates its own _additional_ C++ files which therefore
/// need to be built and included in linking procedures.
pub(crate) struct AdditionalCppGenerator {
additional_functions: Vec<AdditionalFunction>,
inclusions: String,
}
impl AdditionalCppGenerator {
pub(crate) fn new(inclusions: String) -> Self {
AdditionalCppGenerator {
additional_functions: Vec::new(),
inclusions,
}
}
pub(crate) fn add_needs(&mut self, additions: Vec<AdditionalNeed>) {
for need in additions {
match need {
AdditionalNeed::MakeStringConstructor => self.generate_string_constructor(),
AdditionalNeed::MakeUnique(ty, args) => self.generate_make_unique(&ty, &args),
AdditionalNeed::ByValueWrapper(by_value_wrapper) => {
self.generate_by_value_wrapper(*by_value_wrapper)
}
}
}
}
pub(crate) fn generate(&self) -> Option<AdditionalCpp> {
if self.additional_functions.is_empty() {
None
} else {
let headers: HashSet<Header> = self
.additional_functions
.iter()
.map(|x| x.headers.iter().cloned())
.flatten()
.collect();
let headers = headers.iter().map(|x| x.include_stmt()).join("\n");
let declarations = self.concat_additional_items(|x| &x.declaration);
let declarations = format!("{}\n{}\n{}", headers, self.inclusions, declarations);
let definitions = self.concat_additional_items(|x| &x.definition);
let definitions = format!("#include \"autocxxgen.h\"\n{}", definitions);
Some(AdditionalCpp {
declarations,
definitions,
})
}
}
fn concat_additional_items<F>(&self, field_access: F) -> String
where
F: FnMut(&AdditionalFunction) -> &str,
{
let mut s = self
.additional_functions
.iter()
.map(field_access)
.collect::<Vec<&str>>()
.join("\n");
s.push('\n');
s
}
fn generate_string_constructor(&mut self) {
let declaration = "std::unique_ptr<std::string> make_string(::rust::Str str)";
let definition = format!(
"{} {{ return std::make_unique<std::string>(std::string(str)); }}",
declaration
);
let declaration = format!("{};", declaration);
self.additional_functions.push(AdditionalFunction {
declaration,
definition,
headers: vec![
Header::system("memory"),
Header::system("string"),
Header::user("cxx.h"),
],
})
}
fn generate_make_unique(&mut self, ty: &TypeName, constructor_arg_types: &[TypeName]) {
let name = format!("{}_make_unique", ty.get_final_ident());
let constructor_args = constructor_arg_types
.iter()
.enumerate()
.map(|(counter, ty)| format!("{} arg{}", ty.to_cpp_name(), counter))
.join(", ");
let declaration = format!("std::unique_ptr<{}> {}({})", ty, name, constructor_args);
let arg_list = constructor_arg_types
.iter()
.enumerate()
.map(|(counter, _)| format!("arg{}", counter))
.join(", ");
let definition = format!(
"{} {{ return std::make_unique<{}>({}); }}",
declaration, ty, arg_list
);
let declaration = format!("{};", declaration);
self.additional_functions.push(AdditionalFunction {
declaration,
definition,
headers: vec![Header::system("memory")],
})
}
fn generate_by_value_wrapper(&mut self, details: ByValueWrapper) {
// Even if the original function call is in a namespace,
// we generate this wrapper in the global namespace.
// We could easily do this the other way round, and when
// cxx::bridge comes to support nested namespace mods then
// we wil wish to do that to avoid name conflicts. However,
// at the moment this is simpler because it avoids us having
// to generate namespace blocks in the generated C++.
let original_func_call = details
.original_function_ns
.into_iter()
.map(|s| make_ident(s))
.chain(std::iter::once(details.original_function_name))
.join("::");
let is_a_method = details.is_a_method;
let name = details.wrapper_function_name;
let get_arg_name = |counter: usize| -> String {
if is_a_method && counter == 0 {
// For method calls that we generate, the first
// argument name needs to be such that we recognize
// it as a method in the second invocation of
// bridge_converter after it's flowed again through
// bindgen.
"autocxx_gen_this".to_string()
} else {
format!("arg{}", counter)
}
};
let args = details
.argument_conversion
.iter()
.enumerate()
.map(|(counter, ty)| format!("{} {}", ty.unconverted_type(), get_arg_name(counter)))
.join(", ");
let ret_type = details
.return_conversion
.as_ref()
.map_or("void".to_string(), |x| x.converted_type());
let declaration = format!("{} {}({})", ret_type, name, args);
let mut arg_list = details
.argument_conversion
.iter()
.enumerate()
.map(|(counter, conv)| conv.conversion(&get_arg_name(counter)));
let receiver = if is_a_method { arg_list.next() } else { None };
let arg_list = arg_list.join(", ");
let mut underlying_function_call = format!("{}({})", original_func_call, arg_list);
if let Some(receiver) = receiver {
underlying_function_call = format!("{}.{}", receiver, underlying_function_call);
}
if let Some(ret) = details.return_conversion {
underlying_function_call =
format!("return {}", ret.conversion(&underlying_function_call));
};
let definition = format!("{} {{ {}; }}", declaration, underlying_function_call,);
let declaration = format!("{};", declaration);
self.additional_functions.push(AdditionalFunction {
declaration,
definition,
headers: vec![Header::system("memory")],
})
}
}