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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Canonical, _almost_-C representation of items in an FFI boundary.
//!
//! The types in here are the [`Library`](crate::Library) building blocks with which
//! a C API can be built. In addition, they contain a few extra, non-C elements
//! (e.g., namespaces, patterns), all of which however can reasonably be mapped to or ignored in C.
//!
//! Except for special circumstances (e.g., when implementing [`CTypeInfo`](crate::lang::rust::CTypeInfo)
//! for a type you don't own; or when writing your own backend) you will not need any of the items in this module.
//! In most cases the **types here are automatically generated by an attribute**; and later **consumed
//! by a backend**.

use crate::patterns::TypePattern;
use crate::util::{ctypes_from_type_recursive, IdPrettifier};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};

// /// If a name like `abc::XXX` is given, strips the `abc::` part.
// fn strip_rust_path_prefix(name_with_path: &str) -> String {
//     let parts: Vec<&str> = name_with_path.split("::").collect();
//     parts.last().unwrap_or(&name_with_path).to_string()
// }

/// A primitive value expressible on C-level.
#[derive(Clone, Debug, PartialOrd, PartialEq)]
pub enum PrimitiveValue {
    Bool(bool),
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    F32(f32),
    F64(f64),
}

/// The value of a constant.
#[derive(Clone, Debug, PartialOrd, PartialEq)]
pub enum ConstantValue {
    Primitive(PrimitiveValue),
}

impl ConstantValue {
    pub(crate) fn fucking_hash_it_already<H: Hasher>(&self, h: &mut H) {
        match self {
            ConstantValue::Primitive(x) => match x {
                PrimitiveValue::Bool(x) => x.hash(h),
                PrimitiveValue::U8(x) => x.hash(h),
                PrimitiveValue::U16(x) => x.hash(h),
                PrimitiveValue::U32(x) => x.hash(h),
                PrimitiveValue::U64(x) => x.hash(h),
                PrimitiveValue::I8(x) => x.hash(h),
                PrimitiveValue::I16(x) => x.hash(h),
                PrimitiveValue::I32(x) => x.hash(h),
                PrimitiveValue::I64(x) => x.hash(h),
                PrimitiveValue::F32(x) => x.to_le_bytes().hash(h),
                PrimitiveValue::F64(x) => x.to_le_bytes().hash(h),
            },
        }
    }
}

/// A Rust `const` definition with a name and value, might become a `#define`.
#[derive(Clone, Debug, PartialOrd, PartialEq)]
pub struct Constant {
    name: String,
    value: ConstantValue,
    meta: Meta,
}

impl Constant {
    pub fn new(name: String, value: ConstantValue, meta: Meta) -> Self {
        Self { name, value, meta }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn value(&self) -> &ConstantValue {
        &self.value
    }

    pub fn meta(&self) -> &Meta {
        &self.meta
    }

    /// Returns the type of this constant.
    pub fn the_type(&self) -> CType {
        match &self.value {
            ConstantValue::Primitive(x) => CType::Primitive(match x {
                PrimitiveValue::Bool(_) => PrimitiveType::Bool,
                PrimitiveValue::U8(_) => PrimitiveType::U8,
                PrimitiveValue::U16(_) => PrimitiveType::U16,
                PrimitiveValue::U32(_) => PrimitiveType::U32,
                PrimitiveValue::U64(_) => PrimitiveType::U64,
                PrimitiveValue::I8(_) => PrimitiveType::I8,
                PrimitiveValue::I16(_) => PrimitiveType::I16,
                PrimitiveValue::I32(_) => PrimitiveType::I32,
                PrimitiveValue::I64(_) => PrimitiveType::I64,
                PrimitiveValue::F32(_) => PrimitiveType::F32,
                PrimitiveValue::F64(_) => PrimitiveType::F64,
            }),
        }
    }
}

/// A type that can exist at the FFI boundary.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum CType {
    Primitive(PrimitiveType),
    Array(ArrayType),
    Enum(EnumType),
    Opaque(OpaqueType),
    Composite(CompositeType),
    FnPointer(FnPointerType),
    ReadPointer(Box<CType>),
    ReadWritePointer(Box<CType>),
    /// Special patterns with primitives existing on C-level but special semantics.
    /// useful to higher level languages.
    Pattern(TypePattern),
}

impl Default for CType {
    fn default() -> Self {
        Self::Primitive(PrimitiveType::Void)
    }
}

impl CType {
    pub fn size_of(&self) -> usize {
        123
    }

    pub fn align_of(&self) -> usize {
        456
    }

    pub const fn void() -> Self {
        Self::Primitive(PrimitiveType::Void)
    }

    /// Produces a name unique for that type with respect to this library.
    ///
    /// The name here is supposed to uniquely determine a type relative to a [`Library`](crate::Library),
    /// but it is not guaranteed to be C-compatible and may contain special characters
    /// (e.g., `*const u32`).
    ///
    /// Backends should instead match on the `CType` variant and determine a more appropriate
    /// name on a case-by-case basis; including changing a name entirely.
    pub fn name_within_lib(&self) -> String {
        match self {
            CType::Primitive(x) => x.rust_name().to_string(),
            CType::Enum(x) => x.rust_name().to_string(),
            CType::Opaque(x) => x.rust_name().to_string(),
            CType::Composite(x) => x.rust_name().to_string(),
            CType::FnPointer(x) => x.internal_name(),
            CType::ReadPointer(x) => format!("*const {}", x.name_within_lib()),
            CType::ReadWritePointer(x) => format!("*mut {}", x.name_within_lib()),
            CType::Pattern(x) => match x {
                TypePattern::Bool => "Bool".to_string(),
                _ => x.fallback_type().name_within_lib(),
            },
            CType::Array(x) => x.rust_name(),
        }
    }

    /// Lists all _other_ types this type refers to.
    pub fn embedded_types(&self) -> Vec<CType> {
        let mut hash_set: HashSet<CType> = HashSet::new();

        ctypes_from_type_recursive(self, &mut hash_set);

        hash_set.remove(self);
        hash_set.iter().cloned().collect()
    }

    /// If this was a pointer type, tries to deref it and return the inner type.
    pub fn deref_pointer(&self) -> Option<&CType> {
        match self {
            CType::Primitive(_) => None,
            CType::Enum(_) => None,
            CType::Opaque(_) => None,
            CType::Composite(_) => None,
            CType::FnPointer(_) => None,
            CType::ReadPointer(x) => Some(x.as_ref()),
            CType::ReadWritePointer(x) => Some(x.as_ref()),
            CType::Pattern(_) => None,
            CType::Array(_) => None,
        }
    }

    /// Convenience method attempting to convert the contained type as a composite.
    pub fn as_composite_type(&self) -> Option<&CompositeType> {
        match self {
            CType::Composite(x) => Some(x),
            _ => None,
        }
    }

    /// Convenience method attempting to convert the contained type as an opaque.
    pub fn as_opaque_type(&self) -> Option<&OpaqueType> {
        match self {
            CType::Opaque(x) => Some(x),
            _ => None,
        }
    }

    /// Checks if this is a [`PrimitiveType::Void`].
    pub fn is_void(&self) -> bool {
        matches!(self, CType::Primitive(PrimitiveType::Void))
    }
}

/// A primitive type that natively exists in C and is FFI safe.
#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum PrimitiveType {
    Void,
    Bool,
    U8,
    U16,
    U32,
    U64,
    I8,
    I16,
    I32,
    I64,
    F32,
    F64,
}

impl PrimitiveType {
    pub fn rust_name(&self) -> &str {
        match self {
            PrimitiveType::Void => "()",
            PrimitiveType::Bool => "bool",
            PrimitiveType::U8 => "u8",
            PrimitiveType::U16 => "u16",
            PrimitiveType::U32 => "u32",
            PrimitiveType::U64 => "u64",
            PrimitiveType::I8 => "i8",
            PrimitiveType::I16 => "i16",
            PrimitiveType::I32 => "i32",
            PrimitiveType::I64 => "i64",
            PrimitiveType::F32 => "f32",
            PrimitiveType::F64 => "f64",
        }
    }
}

/// A (C-style) `type[N]` containing a fixed number of elements of the same type.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct ArrayType {
    array_type: Box<CType>,
    len: usize,
}

impl ArrayType {
    pub fn new(array_type: CType, len: usize) -> Self {
        Self {
            array_type: Box::new(array_type),
            len,
        }
    }

    pub fn rust_name(&self) -> String {
        format!("{}[{}]", self.array_type.name_within_lib(), self.len)
    }

    pub fn array_type(&self) -> &CType {
        &self.array_type
    }

    pub fn len(&self) -> usize {
        self.len
    }
}

/// A (C-style) `enum` containing numbered variants.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct EnumType {
    name: String,
    variants: Vec<Variant>,
    meta: Meta,
}

impl EnumType {
    pub fn new(name: String, variants: Vec<Variant>, meta: Meta) -> Self {
        Self { name, variants, meta }
    }

    pub fn rust_name(&self) -> &str {
        &self.name
    }

    pub fn variants(&self) -> &[Variant] {
        &self.variants
    }

    pub fn variant_by_name(&self, name: &str) -> Option<Variant> {
        self.variants.iter().find(|x| x.name == name).cloned()
    }

    pub fn meta(&self) -> &Meta {
        &self.meta
    }
}

/// Variant and value of a [`EnumType`].
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Variant {
    name: String,
    value: usize,
    documentation: Documentation,
}

impl Variant {
    pub fn new(name: String, value: usize, documentation: Documentation) -> Self {
        Self { name, value, documentation }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn value(&self) -> usize {
        self.value
    }

    pub fn documentation(&self) -> &Documentation {
        &self.documentation
    }
}

/// Used for Rust and C `struct` with named fields, must be `#[repr(C)]`.
///
/// Might translate to a struct or class in another language, equivalent on
/// C-level to:
///
/// ```ignore
/// typedef struct MyComposite
/// {
///     int   field_1;
///     float field_2;
///     char  field_3;
///     // ...
/// } MyComposite;
/// ```
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct CompositeType {
    name: String,
    fields: Vec<Field>,
    meta: Meta,
}

impl CompositeType {
    /// Creates a new composite with the given name and fields and no documentation.
    pub fn new(name: String, fields: Vec<Field>) -> Self {
        Self::with_meta(name, fields, Meta::new())
    }

    /// Creates a new composite with the given name and type-level documentation.
    pub fn with_meta(name: String, fields: Vec<Field>, meta: Meta) -> Self {
        Self { name, fields, meta }
    }

    /// Gets the type's name `
    pub fn rust_name(&self) -> &str {
        &self.name
    }

    pub fn fields(&self) -> &[Field] {
        &self.fields
    }

    /// True if this struct has no contained fields (which happens to be illegal in C99).
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }

    pub fn meta(&self) -> &Meta {
        &self.meta
    }
}

/// Doesn't exist in C, but other languages can benefit from accidentally using 'private' fields.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum Visibility {
    Public,
    Private,
}

/// Fields of a [`CompositeType`].
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Field {
    name: String,
    visibility: Visibility,
    the_type: CType,
    documentation: Documentation,
}

impl Field {
    pub fn new(name: String, the_type: CType) -> Self {
        Self::with_documentation(name, the_type, Visibility::Public, Documentation::new())
    }

    pub fn with_documentation(name: String, the_type: CType, visibility: Visibility, documentation: Documentation) -> Self {
        Self {
            name,
            visibility,
            the_type,
            documentation,
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn the_type(&self) -> &CType {
        &self.the_type
    }

    pub fn visibility(&self) -> &Visibility {
        &self.visibility
    }

    pub fn documentation(&self) -> &Documentation {
        &self.documentation
    }
}

/// A named `struct` that becomes a fieldless `typedef struct S S;` in C.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct OpaqueType {
    name: String,
    meta: Meta,
}

impl OpaqueType {
    pub fn new(name: String, meta: Meta) -> Self {
        Self { name, meta }
    }

    pub fn rust_name(&self) -> &str {
        &self.name
    }

    pub fn meta(&self) -> &Meta {
        &self.meta
    }
}

/// Additional information for user-defined types.
#[derive(Clone, Debug, Default, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Meta {
    documentation: Documentation,
    namespace: String,
}

impl Meta {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_namespace_documentation(namespace: String, documentation: Documentation) -> Self {
        Self { documentation, namespace }
    }

    pub fn with_documentation(documentation: Documentation) -> Self {
        Self::with_namespace_documentation(String::new(), documentation)
    }

    pub fn documentation(&self) -> &Documentation {
        &self.documentation
    }

    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// Convenience method used in generators
    pub fn is_namespace(&self, namespace: &str) -> bool {
        self.namespace == namespace
    }
}

/// A named, exported `#[no_mangle] extern "C" fn f()` function.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Function {
    name: String,
    meta: Meta,
    signature: FunctionSignature,
}

impl Function {
    pub fn new(name: String, signature: FunctionSignature, meta: Meta) -> Self {
        Self { name, meta, signature }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn signature(&self) -> &FunctionSignature {
        &self.signature
    }

    pub fn meta(&self) -> &Meta {
        &self.meta
    }

    pub fn prettifier(&self) -> IdPrettifier {
        IdPrettifier::from_rust_lower(self.name())
    }
}

/// Represents multiple `in` and a single `out` parameters.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash, Default)]
pub struct FunctionSignature {
    params: Vec<Parameter>,
    rval: CType,
}

impl FunctionSignature {
    pub fn new(params: Vec<Parameter>, rval: CType) -> Self {
        Self { params, rval }
    }

    pub fn params(&self) -> &[Parameter] {
        &self.params
    }

    pub fn rval(&self) -> &CType {
        &self.rval
    }
}

/// Parameters of a [`FunctionSignature`].
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Parameter {
    name: String,
    the_type: CType,
}

impl Parameter {
    pub fn new(name: String, the_type: CType) -> Self {
        Self { name, the_type }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn the_type(&self) -> &CType {
        &self.the_type
    }
}

/// Represents `extern "C" fn()` types in Rust and `(*f)().` in C.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct FnPointerType {
    signature: Box<FunctionSignature>,
}

impl FnPointerType {
    pub fn new(signature: FunctionSignature) -> Self {
        Self { signature: Box::new(signature) }
    }

    pub fn signature(&self) -> &FunctionSignature {
        &self.signature
    }

    pub fn internal_name(&self) -> String {
        let signature = self.signature();
        let params = signature.params.iter().map(|x| x.the_type().name_within_lib()).collect::<Vec<_>>().join(",");
        let rval = signature.rval.name_within_lib();

        format!("fn({}) -> {}", params, rval)
    }
}

/// Markdown generated from the `///` you put on Rust code.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash, Default)]
pub struct Documentation {
    lines: Vec<String>,
}

impl Documentation {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn from_line(joined_line: &str) -> Self {
        if joined_line.is_empty() {
            Documentation::new()
        } else {
            Documentation {
                lines: joined_line.split('\n').map(|x| x.to_string()).collect(),
            }
        }
    }

    pub fn from_lines(lines: Vec<String>) -> Self {
        Documentation { lines }
    }

    pub fn lines(&self) -> &[String] {
        &self.lines
    }
}