cxx_gen/syntax/
trivial.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
use crate::syntax::map::UnorderedMap;
use crate::syntax::set::{OrderedSet as Set, UnorderedSet};
use crate::syntax::{Api, Enum, ExternFn, NamedType, Pair, Struct, Type};
use proc_macro2::Ident;
use std::fmt::{self, Display};

#[derive(Copy, Clone)]
pub(crate) enum TrivialReason<'a> {
    StructField(&'a Struct),
    FunctionArgument(&'a ExternFn),
    FunctionReturn(&'a ExternFn),
    BoxTarget,
    VecElement,
    SliceElement { mutable: bool },
    UnpinnedMut(&'a ExternFn),
}

pub(crate) fn required_trivial_reasons<'a>(
    apis: &'a [Api],
    all: &Set<&'a Type>,
    structs: &UnorderedMap<&'a Ident, &'a Struct>,
    enums: &UnorderedMap<&'a Ident, &'a Enum>,
    cxx: &UnorderedSet<&'a Ident>,
) -> UnorderedMap<&'a Ident, Vec<TrivialReason<'a>>> {
    let mut required_trivial = UnorderedMap::new();

    let mut insist_extern_types_are_trivial = |ident: &'a NamedType, reason| {
        if cxx.contains(&ident.rust)
            && !structs.contains_key(&ident.rust)
            && !enums.contains_key(&ident.rust)
        {
            required_trivial
                .entry(&ident.rust)
                .or_insert_with(Vec::new)
                .push(reason);
        }
    };

    for api in apis {
        match api {
            Api::Struct(strct) => {
                for field in &strct.fields {
                    if let Type::Ident(ident) = &field.ty {
                        let reason = TrivialReason::StructField(strct);
                        insist_extern_types_are_trivial(ident, reason);
                    }
                }
            }
            Api::CxxFunction(efn) | Api::RustFunction(efn) => {
                if let Some(receiver) = &efn.receiver {
                    if receiver.mutable && !receiver.pinned {
                        let reason = TrivialReason::UnpinnedMut(efn);
                        insist_extern_types_are_trivial(&receiver.ty, reason);
                    }
                }
                for arg in &efn.args {
                    match &arg.ty {
                        Type::Ident(ident) => {
                            let reason = TrivialReason::FunctionArgument(efn);
                            insist_extern_types_are_trivial(ident, reason);
                        }
                        Type::Ref(ty) => {
                            if ty.mutable && !ty.pinned {
                                if let Type::Ident(ident) = &ty.inner {
                                    let reason = TrivialReason::UnpinnedMut(efn);
                                    insist_extern_types_are_trivial(ident, reason);
                                }
                            }
                        }
                        _ => {}
                    }
                }
                if let Some(ret) = &efn.ret {
                    match ret {
                        Type::Ident(ident) => {
                            let reason = TrivialReason::FunctionReturn(efn);
                            insist_extern_types_are_trivial(ident, reason);
                        }
                        Type::Ref(ty) => {
                            if ty.mutable && !ty.pinned {
                                if let Type::Ident(ident) = &ty.inner {
                                    let reason = TrivialReason::UnpinnedMut(efn);
                                    insist_extern_types_are_trivial(ident, reason);
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    for ty in all {
        match ty {
            Type::RustBox(ty) => {
                if let Type::Ident(ident) = &ty.inner {
                    let reason = TrivialReason::BoxTarget;
                    insist_extern_types_are_trivial(ident, reason);
                }
            }
            Type::RustVec(ty) => {
                if let Type::Ident(ident) = &ty.inner {
                    let reason = TrivialReason::VecElement;
                    insist_extern_types_are_trivial(ident, reason);
                }
            }
            Type::SliceRef(ty) => {
                if let Type::Ident(ident) = &ty.inner {
                    let reason = TrivialReason::SliceElement {
                        mutable: ty.mutable,
                    };
                    insist_extern_types_are_trivial(ident, reason);
                }
            }
            _ => {}
        }
    }

    required_trivial
}

// Context:
// "type {type} should be trivially move constructible and trivially destructible in C++ to be used as {what} in Rust"
// "needs a cxx::ExternType impl in order to be used as {what}"
pub(crate) fn as_what<'a>(name: &'a Pair, reasons: &'a [TrivialReason]) -> impl Display + 'a {
    struct Description<'a> {
        name: &'a Pair,
        reasons: &'a [TrivialReason<'a>],
    }

    impl<'a> Display for Description<'a> {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let mut field_of = Set::new();
            let mut argument_of = Set::new();
            let mut return_of = Set::new();
            let mut box_target = false;
            let mut vec_element = false;
            let mut slice_shared_element = false;
            let mut slice_mut_element = false;
            let mut unpinned_mut = Set::new();

            for reason in self.reasons {
                match reason {
                    TrivialReason::StructField(strct) => {
                        field_of.insert(&strct.name.rust);
                    }
                    TrivialReason::FunctionArgument(efn) => {
                        argument_of.insert(&efn.name.rust);
                    }
                    TrivialReason::FunctionReturn(efn) => {
                        return_of.insert(&efn.name.rust);
                    }
                    TrivialReason::BoxTarget => box_target = true,
                    TrivialReason::VecElement => vec_element = true,
                    TrivialReason::SliceElement { mutable } => {
                        if *mutable {
                            slice_mut_element = true;
                        } else {
                            slice_shared_element = true;
                        }
                    }
                    TrivialReason::UnpinnedMut(efn) => {
                        unpinned_mut.insert(&efn.name.rust);
                    }
                }
            }

            let mut clauses = Vec::new();
            if !field_of.is_empty() {
                clauses.push(Clause::Set {
                    article: "a",
                    desc: "field of",
                    set: &field_of,
                });
            }
            if !argument_of.is_empty() {
                clauses.push(Clause::Set {
                    article: "an",
                    desc: "argument of",
                    set: &argument_of,
                });
            }
            if !return_of.is_empty() {
                clauses.push(Clause::Set {
                    article: "a",
                    desc: "return value of",
                    set: &return_of,
                });
            }
            if box_target {
                clauses.push(Clause::Ty1 {
                    article: "type",
                    desc: "Box",
                    param: self.name,
                });
            }
            if vec_element {
                clauses.push(Clause::Ty1 {
                    article: "a",
                    desc: "vector element in Vec",
                    param: self.name,
                });
            }
            if slice_shared_element || slice_mut_element {
                clauses.push(Clause::Slice {
                    article: "a",
                    desc: "slice element in",
                    shared: slice_shared_element,
                    mutable: slice_mut_element,
                    param: self.name,
                });
            }
            if !unpinned_mut.is_empty() {
                clauses.push(Clause::Set {
                    article: "a",
                    desc: "non-pinned mutable reference in signature of",
                    set: &unpinned_mut,
                });
            }

            for (i, clause) in clauses.iter().enumerate() {
                if i == 0 {
                    write!(f, "{} ", clause.article())?;
                } else if i + 1 < clauses.len() {
                    write!(f, ", ")?;
                } else {
                    write!(f, " or ")?;
                }
                clause.fmt(f)?;
            }

            Ok(())
        }
    }

    enum Clause<'a> {
        Set {
            article: &'a str,
            desc: &'a str,
            set: &'a Set<&'a Ident>,
        },
        Ty1 {
            article: &'a str,
            desc: &'a str,
            param: &'a Pair,
        },
        Slice {
            article: &'a str,
            desc: &'a str,
            shared: bool,
            mutable: bool,
            param: &'a Pair,
        },
    }

    impl<'a> Clause<'a> {
        fn article(&self) -> &'a str {
            match self {
                Clause::Set { article, .. }
                | Clause::Ty1 { article, .. }
                | Clause::Slice { article, .. } => article,
            }
        }

        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match self {
                Clause::Set {
                    article: _,
                    desc,
                    set,
                } => {
                    write!(f, "{} ", desc)?;
                    for (i, ident) in set.iter().take(3).enumerate() {
                        if i > 0 {
                            write!(f, ", ")?;
                        }
                        write!(f, "`{}`", ident)?;
                    }
                    Ok(())
                }
                Clause::Ty1 {
                    article: _,
                    desc,
                    param,
                } => write!(f, "{}<{}>", desc, param.rust),
                Clause::Slice {
                    article: _,
                    desc,
                    shared,
                    mutable,
                    param,
                } => {
                    write!(f, "{} ", desc)?;
                    if *shared {
                        write!(f, "&[{}]", param.rust)?;
                    }
                    if *shared && *mutable {
                        write!(f, " and ")?;
                    }
                    if *mutable {
                        write!(f, "&mut [{}]", param.rust)?;
                    }
                    Ok(())
                }
            }
        }
    }

    Description { name, reasons }
}