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
//! Helpers for backend authors.

use crate::lang::c::{CType, Function};
use crate::patterns::TypePattern;
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;

/// Converts an internal name like `fn() -> X` to a safe name like `fn_rval_x`
///
/// # Example
///
/// ```
/// use interoptopus::util::safe_name;
///
/// assert_eq!(safe_name("fn(u32) -> u8"), "fn_u32_rval_u8");
/// ```
pub fn safe_name(name: &str) -> String {
    let mut rval = name.to_string();

    rval = rval.replace("fn(", "fn_");
    rval = rval.replace("-> ()", "");
    rval = rval.replace("->", "rval");
    rval = rval.replace("(", "");
    rval = rval.replace(")", "");
    rval = rval.replace("*", "p");
    rval = rval.replace(",", "_");
    rval = rval.replace(" ", "_");

    rval = rval.trim_end_matches('_').to_string();

    rval
}

/// Sorts types so the latter entries will find their dependents earlier in this list.
pub fn sort_types_by_dependencies(mut types: Vec<CType>) -> Vec<CType> {
    let mut rval = Vec::new();

    // Ugly but was fast to write.
    // TODO: This is guaranteed to terminate by proof of running it at least once on my machine.
    while !types.is_empty() {
        let mut this_round = Vec::new();

        for t in &types {
            let embedded = t.embedded_types();
            let all_exist = embedded.iter().all(|x| rval.contains(x));

            if embedded.is_empty() || all_exist {
                this_round.push(t.clone());
            }
        }

        types.retain(|x| !this_round.contains(x));
        rval.append(&mut this_round);
    }

    rval
}

/// Given a number of functions like [`lib_x`, `lib_y`] return the longest common prefix `lib_`.
///
///
/// # Example
///
/// ```rust
/// # use interoptopus::lang::c::{Function, FunctionSignature, Meta};
/// # use interoptopus::util::longest_common_prefix;
///
/// let functions = [
///     Function::new("my_lib_f".to_string(), FunctionSignature::default(), Meta::default()),
///     Function::new("my_lib_g".to_string(), FunctionSignature::default(), Meta::default()),
///     Function::new("my_lib_h".to_string(), FunctionSignature::default(), Meta::default()),
/// ];
///
/// assert_eq!(longest_common_prefix(&functions), "my_lib_".to_string());
/// ```
pub fn longest_common_prefix(functions: &[Function]) -> String {
    let funcs_as_chars = functions.iter().map(|x| x.name().chars().collect::<Vec<_>>()).collect::<Vec<_>>();

    let mut longest_common: Vec<char> = Vec::new();

    if let Some(first) = funcs_as_chars.first() {
        for (i, c) in first.iter().enumerate() {
            for function in &funcs_as_chars {
                if !function.get(i).map(|x| x == c).unwrap_or(false) {
                    return String::from_iter(&longest_common);
                }
            }
            longest_common.push(*c);
        }
    }

    String::from_iter(&longest_common)
}

/// Given some functions and types, return all used and nested types, without duplicates.
pub(crate) fn ctypes_from_functions_types(functions: &[Function], extra_types: &[CType]) -> Vec<CType> {
    let mut types = HashSet::new();

    for function in functions {
        ctypes_from_type_recursive(function.signature().rval(), &mut types);

        for param in function.signature().params() {
            ctypes_from_type_recursive(param.the_type(), &mut types);
        }
    }

    for ty in extra_types {
        ctypes_from_type_recursive(ty, &mut types);
    }

    types.iter().cloned().collect()
}

/// Recursive helper for [`ctypes_from_functions_types`].
pub(crate) fn ctypes_from_type_recursive(start: &CType, types: &mut HashSet<CType>) {
    types.insert(start.clone());

    match start {
        CType::Composite(inner) => {
            for field in inner.fields() {
                ctypes_from_type_recursive(&field.the_type(), types);
            }
        }
        CType::Array(inner) => ctypes_from_type_recursive(&inner.array_type(), types),
        CType::FnPointer(inner) => {
            ctypes_from_type_recursive(inner.signature().rval(), types);
            for param in inner.signature().params() {
                ctypes_from_type_recursive(param.the_type(), types);
            }
        }
        CType::ReadPointer(inner) => ctypes_from_type_recursive(inner, types),
        CType::ReadWritePointer(inner) => ctypes_from_type_recursive(inner, types),
        CType::Primitive(_) => {}
        CType::Enum(_) => {}
        CType::Opaque(_) => {}
        // Note, patterns must _NEVER_ add themselves as fallbacks. Instead, each code generator should
        // decide on a case-by-case bases whether it wants to use the type's fallback, or generate an
        // entirely new pattern. The exception to this rule are patterns that can embed arbitrary
        // types; which we need to recursively inspect.
        CType::Pattern(x) => match x {
            TypePattern::AsciiPointer => {}
            TypePattern::FFIErrorEnum(_) => {}
            TypePattern::NamedCallback(x) => {
                let inner = x.fnpointer();
                ctypes_from_type_recursive(inner.signature().rval(), types);
                for param in inner.signature().params() {
                    ctypes_from_type_recursive(param.the_type(), types);
                }
            }
            TypePattern::Slice(x) => {
                for field in x.fields() {
                    ctypes_from_type_recursive(field.the_type(), types);
                }
            }
            TypePattern::SliceMut(x) => {
                for field in x.fields() {
                    ctypes_from_type_recursive(field.the_type(), types);
                }
            }
            TypePattern::Option(x) => {
                for field in x.fields() {
                    ctypes_from_type_recursive(field.the_type(), types);
                }
            }
            TypePattern::Bool => {}
            TypePattern::APIVersion => {}
        },
    }
}

/// Extracts annotated namespace strings.
pub(crate) fn extract_namespaces_from_types(types: &[CType], into: &mut HashSet<String>) {
    for t in types {
        match t {
            CType::Primitive(_) => {}
            CType::Array(_) => {}

            CType::Enum(x) => {
                into.insert(x.meta().namespace().to_string());
            }
            CType::Opaque(x) => {
                into.insert(x.meta().namespace().to_string());
            }
            CType::Composite(x) => {
                into.insert(x.meta().namespace().to_string());
            }
            CType::FnPointer(_) => {}
            CType::ReadPointer(_) => {}
            CType::ReadWritePointer(_) => {}
            CType::Pattern(x) => match x {
                TypePattern::AsciiPointer => {}
                TypePattern::APIVersion => {}
                TypePattern::FFIErrorEnum(x) => {
                    into.insert(x.the_enum().meta().namespace().to_string());
                }
                TypePattern::Slice(x) => {
                    into.insert(x.meta().namespace().to_string());
                }
                TypePattern::SliceMut(x) => {
                    into.insert(x.meta().namespace().to_string());
                }
                TypePattern::Option(x) => {
                    into.insert(x.meta().namespace().to_string());
                }
                TypePattern::Bool => {}
                TypePattern::NamedCallback(_) => {}
            },
        }
    }
}

/// Maps an internal namespace like `common` to a language namespace like `Company.Common`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NamespaceMappings {
    mappings: HashMap<String, String>,
}

impl NamespaceMappings {
    /// Creates a new mapping, assinging namespace id `""` to `default`.
    pub fn new(default: &str) -> Self {
        let mut mappings = HashMap::new();
        mappings.insert("".to_string(), default.to_string());
        mappings.insert("_global".to_string(), default.to_string());

        Self { mappings }
    }

    /// Adds a mapping between namespace `id` to string `value`.
    pub fn add(mut self, id: &str, value: &str) -> Self {
        self.mappings.insert(id.to_string(), value.to_string());
        self
    }

    /// Returns the default namespace mapping
    pub fn default_namespace(&self) -> &str {
        self.get("").expect("This must exist")
    }

    /// Obtains a mapping for the given ID.
    pub fn get(&self, id: &str) -> Option<&str> {
        self.mappings.get(id).map(|x| x.as_str())
    }
}

/// Allows, for example, `my_id` to be converted to `MyId`.
pub struct IdPrettifier {
    tokens: Vec<String>,
}

impl IdPrettifier {
    /// Creates a new prettifier from a `my_name` identifier.
    pub fn from_rust_lower(id: &str) -> Self {
        Self {
            tokens: id.split('_').map(|x| x.to_string()).collect(),
        }
    }

    pub fn to_camel_case(&self) -> String {
        self.tokens
            .iter()
            .map(|x| {
                x.chars()
                    .enumerate()
                    .map(|(i, x)| if i == 0 { x.to_ascii_uppercase() } else { x })
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("")
    }
}

/// Checks whether the given type should be "the same type everywhere".
///
/// In complex setups we sometimes want to use types between two (otherwise unrelated) bindings.
/// For example, we would like to produce a `FFISlice<u8>` in library A, and consume that in
/// library B. On the other hand, a  `FFISlice<MyStruct>` is not something everyone should know of.
///
/// For our bindings to know whether some types should go to a shared namespace this function
/// will inform them whether the underlying type should be shared.
///
///
pub fn is_global_type(t: &CType) -> bool {
    match t {
        CType::Primitive(_) => true,
        CType::Array(x) => is_global_type(x.array_type()),
        CType::Enum(_) => false,
        CType::Opaque(_) => false,
        CType::Composite(_) => false,
        CType::FnPointer(_) => false,
        CType::ReadPointer(x) => is_global_type(x),
        CType::ReadWritePointer(x) => is_global_type(x),
        CType::Pattern(x) => match x {
            TypePattern::AsciiPointer => true,
            TypePattern::APIVersion => false,
            TypePattern::FFIErrorEnum(_) => false,
            TypePattern::Slice(x) => x.fields().iter().all(|x| is_global_type(x.the_type())),
            TypePattern::SliceMut(x) => x.fields().iter().all(|x| is_global_type(x.the_type())),
            TypePattern::Option(x) => x.fields().iter().all(|x| is_global_type(x.the_type())),
            TypePattern::Bool => true,
            TypePattern::NamedCallback(_) => false,
        },
    }
}

/// Debug macro resolving to the current file and line number.
///
/// ```
/// use interoptopus::here;
///
/// println!(here!())
/// ```
#[macro_export]
macro_rules! here {
    () => {
        concat!(file!(), ":", line!())
    };
}

/// Logs an error if compiled with feature `log`.
#[cfg(feature = "log")]
#[inline(always)]
pub fn log_error<S: AsRef<str>, F: Fn() -> S>(f: F) {
    log::error!("{}", f().as_ref());
}

/// Logs an error if compiled with feature `log`.
#[cfg(not(feature = "log"))]
#[inline(always)]
pub fn log_error<S: AsRef<str>, F: Fn() -> S>(_f: F) {}

#[cfg(test)]
mod test {
    use crate::util::IdPrettifier;

    #[test]
    fn is_pretty() {
        assert_eq!(IdPrettifier::from_rust_lower("hello_world").to_camel_case(), "HelloWorld");
        assert_eq!(IdPrettifier::from_rust_lower("single").to_camel_case(), "Single");
    }
}