summaryrefslogtreecommitdiffstats
path: root/src/bindgen/mangle.rs
blob: c8769f83ccba53f6953a2216edd20790917efa6a (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use crate::bindgen::config::MangleConfig;
use crate::bindgen::ir::{ConstExpr, GenericArgument, GenericPath, Path, Type};
use crate::bindgen::rename::IdentifierType;

pub fn mangle_path(path: &Path, generic_values: &[GenericArgument], config: &MangleConfig) -> Path {
    Path::new(mangle_name(path.name(), generic_values, config))
}

pub fn mangle_name(
    name: &str,
    generic_values: &[GenericArgument],
    config: &MangleConfig,
) -> String {
    Mangler::new(name, generic_values, /* last = */ true, config).mangle()
}

enum Separator {
    OpeningAngleBracket = 1,
    Comma,
    ClosingAngleBracket,
    BeginMutPtr,
    BeginConstPtr,
    BeginFn,
    BetweenFnArg,
    EndFn,
}

struct Mangler<'a> {
    input: &'a str,
    generic_values: &'a [GenericArgument],
    output: String,
    last: bool,
    config: &'a MangleConfig,
}

impl<'a> Mangler<'a> {
    fn new(
        input: &'a str,
        generic_values: &'a [GenericArgument],
        last: bool,
        config: &'a MangleConfig,
    ) -> Self {
        Self {
            input,
            generic_values,
            output: String::new(),
            last,
            config,
        }
    }

    fn mangle(mut self) -> String {
        self.mangle_internal();
        self.output
    }

    fn push(&mut self, id: Separator) {
        let count = id as usize;
        let separator = if self.config.remove_underscores {
            ""
        } else {
            "_"
        };
        self.output.extend(std::iter::repeat(separator).take(count));
    }

    fn append_mangled_argument(&mut self, arg: &GenericArgument, last: bool) {
        match *arg {
            GenericArgument::Type(ref ty) => self.append_mangled_type(ty, last),
            GenericArgument::Const(ConstExpr::Name(ref name)) => {
                // This must behave the same as a GenericArgument::Type,
                // because const arguments are commonly represented as Types;
                // see the comment on `enum GenericArgument`.
                let fake_ty = Type::Path(GenericPath::new(Path::new(name), vec![]));
                self.append_mangled_type(&fake_ty, last);
            }
            GenericArgument::Const(ConstExpr::Value(ref val)) => self.output.push_str(val),
        }
    }

    fn append_mangled_type(&mut self, ty: &Type, last: bool) {
        match *ty {
            Type::Path(ref generic) => {
                let sub_path =
                    Mangler::new(generic.export_name(), generic.generics(), last, self.config)
                        .mangle();

                self.output.push_str(
                    &self
                        .config
                        .rename_types
                        .apply(&sub_path, IdentifierType::Type),
                );
            }
            Type::Primitive(ref primitive) => {
                self.output.push_str(
                    &self
                        .config
                        .rename_types
                        .apply(primitive.to_repr_rust(), IdentifierType::Type),
                );
            }
            Type::Ptr {
                ref ty, is_const, ..
            } => {
                self.push(if is_const {
                    Separator::BeginConstPtr
                } else {
                    Separator::BeginMutPtr
                });
                self.append_mangled_type(ty, last);
            }
            Type::FuncPtr {
                ref ret, ref args, ..
            } => {
                self.push(Separator::BeginFn);
                self.append_mangled_type(ret, args.is_empty());
                for (i, arg) in args.iter().enumerate() {
                    self.push(Separator::BetweenFnArg);
                    let last = last && i == args.len() - 1;
                    self.append_mangled_type(&arg.1, last);
                }
                if !self.last {
                    self.push(Separator::EndFn);
                }
            }
            Type::Array(..) => {
                unimplemented!(
                    "Unable to mangle generic parameter {:?} for '{}'",
                    ty,
                    self.input
                );
            }
        }
    }

    fn mangle_internal(&mut self) {
        debug_assert!(self.output.is_empty());
        self.output = self.input.to_owned();
        if self.generic_values.is_empty() {
            return;
        }

        self.push(Separator::OpeningAngleBracket);
        for (i, arg) in self.generic_values.iter().enumerate() {
            if i != 0 {
                self.push(Separator::Comma);
            }
            let last = self.last && i == self.generic_values.len() - 1;
            self.append_mangled_argument(arg, last);
        }

        // Skip writing the trailing '>' mangling when possible
        if !self.last {
            self.push(Separator::ClosingAngleBracket)
        }
    }
}

#[test]
fn generics() {
    use crate::bindgen::ir::{GenericPath, PrimitiveType};
    use crate::bindgen::rename::RenameRule::{self, PascalCase};

    fn float() -> GenericArgument {
        GenericArgument::Type(Type::Primitive(PrimitiveType::Float))
    }

    fn c_char() -> GenericArgument {
        GenericArgument::Type(Type::Primitive(PrimitiveType::Char))
    }

    fn path(path: &str) -> GenericArgument {
        generic_path(path, &[])
    }

    fn generic_path(path: &str, arguments: &[GenericArgument]) -> GenericArgument {
        let path = Path::new(path);
        let generic_path = GenericPath::new(path, arguments.to_owned());
        GenericArgument::Type(Type::Path(generic_path))
    }

    // Foo<f32> => Foo_f32
    assert_eq!(
        mangle_path(&Path::new("Foo"), &[float()], &MangleConfig::default()),
        Path::new("Foo_f32")
    );

    // Foo<Bar<f32>> => Foo_Bar_f32
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[generic_path("Bar", &[float()])],
            &MangleConfig::default(),
        ),
        Path::new("Foo_Bar_f32")
    );

    // Foo<Bar> => Foo_Bar
    assert_eq!(
        mangle_path(&Path::new("Foo"), &[path("Bar")], &MangleConfig::default()),
        Path::new("Foo_Bar")
    );

    // Foo<Bar> => FooBar
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[path("Bar")],
            &MangleConfig {
                remove_underscores: true,
                rename_types: RenameRule::None,
            }
        ),
        Path::new("FooBar")
    );

    // Foo<Bar<f32>> => FooBarF32
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[generic_path("Bar", &[float()])],
            &MangleConfig {
                remove_underscores: true,
                rename_types: PascalCase,
            },
        ),
        Path::new("FooBarF32")
    );

    // Foo<Bar<c_char>> => FooBarCChar
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[generic_path("Bar", &[c_char()])],
            &MangleConfig {
                remove_underscores: true,
                rename_types: PascalCase,
            },
        ),
        Path::new("FooBarCChar")
    );

    // Foo<Bar<T>> => Foo_Bar_T
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[generic_path("Bar", &[path("T")])],
            &MangleConfig::default(),
        ),
        Path::new("Foo_Bar_T")
    );

    // Foo<Bar<T>, E> => Foo_Bar_T_____E
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[generic_path("Bar", &[path("T")]), path("E")],
            &MangleConfig::default(),
        ),
        Path::new("Foo_Bar_T_____E")
    );

    // Foo<Bar<T>, Bar<E>> => Foo_Bar_T_____Bar_E
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[
                generic_path("Bar", &[path("T")]),
                generic_path("Bar", &[path("E")]),
            ],
            &MangleConfig::default(),
        ),
        Path::new("Foo_Bar_T_____Bar_E")
    );

    // Foo<Bar<T>, E> => FooBarTE
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[generic_path("Bar", &[path("T")]), path("E")],
            &MangleConfig {
                remove_underscores: true,
                rename_types: PascalCase,
            },
        ),
        Path::new("FooBarTE")
    );

    // Foo<Bar<T>, Bar<E>> => FooBarTBarE
    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[
                generic_path("Bar", &[path("T")]),
                generic_path("Bar", &[path("E")]),
            ],
            &MangleConfig {
                remove_underscores: true,
                rename_types: PascalCase,
            },
        ),
        Path::new("FooBarTBarE")
    );

    assert_eq!(
        mangle_path(
            &Path::new("Top"),
            &[GenericArgument::Const(ConstExpr::Value("40".to_string()))],
            &MangleConfig::default(),
        ),
        Path::new("Top_40")
    );

    assert_eq!(
        mangle_path(
            &Path::new("Top"),
            &[GenericArgument::Const(ConstExpr::Name("N".to_string()))],
            &MangleConfig::default(),
        ),
        Path::new("Top_N")
    );

    assert_eq!(
        mangle_path(
            &Path::new("Top"),
            &[generic_path("N", &[])],
            &MangleConfig::default(),
        ),
        Path::new("Top_N")
    );

    assert_eq!(
        mangle_path(
            &Path::new("Foo"),
            &[
                float(),
                GenericArgument::Const(ConstExpr::Value("40".to_string()))
            ],
            &MangleConfig::default(),
        ),
        Path::new("Foo_f32__40")
    );
}