device-driver-common 2.0.0

Internal compiler crate for the device-driver toolkit
Documentation
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
use std::{
    fmt::{Debug, Display},
    num::NonZeroU32,
    sync::Arc,
};

use convert_case::{Boundary, Case, Pattern};

#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum RuntimeType {
    /// Used for things that participate in all types.
    /// These are manifests, blocks, fields, enum variants, ...
    All,
    /// Used for things that define operations or things you can do with a driver.
    /// These are registers, commands, buffers, ...
    Operation,
    /// Used for things that define a type.
    /// These are devices, fieldsets, enums, ...
    Type,
}

impl RuntimeType {
    pub fn shares_namespace_with(&self, other: RuntimeType) -> bool {
        matches!(
            (self, other),
            (RuntimeType::All, _)
                | (_, RuntimeType::All)
                | (RuntimeType::Operation, RuntimeType::Operation)
                | (RuntimeType::Type, RuntimeType::Type)
        )
    }
}

#[repr(transparent)]
#[derive(Debug, Copy, Clone)]
pub struct Type(RuntimeType);
impl Default for Type {
    fn default() -> Self {
        Self(RuntimeType::Type)
    }
}
#[repr(transparent)]
#[derive(Debug, Copy, Clone)]
pub struct Operation(RuntimeType);
impl Default for Operation {
    fn default() -> Self {
        Self(RuntimeType::Operation)
    }
}
#[repr(transparent)]
#[derive(Debug, Copy, Clone)]
pub struct All(RuntimeType);
impl Default for All {
    fn default() -> Self {
        Self(RuntimeType::All)
    }
}

/// # Safety
/// Must only be implemented on type that are transparently [RuntimeType]
pub unsafe trait IdentifierType: Debug {
    fn runtime_value(&self) -> RuntimeType;
}

unsafe impl IdentifierType for Type {
    fn runtime_value(&self) -> RuntimeType {
        RuntimeType::Type
    }
}
unsafe impl IdentifierType for Operation {
    fn runtime_value(&self) -> RuntimeType {
        RuntimeType::Operation
    }
}
unsafe impl IdentifierType for All {
    fn runtime_value(&self) -> RuntimeType {
        RuntimeType::All
    }
}
unsafe impl IdentifierType for RuntimeType {
    fn runtime_value(&self) -> RuntimeType {
        *self
    }
}

impl From<All> for Type {
    fn from(_: All) -> Self {
        Type::default()
    }
}
impl From<All> for Operation {
    fn from(_: All) -> Self {
        Operation::default()
    }
}

/// A structure that holds the name data of objects
#[derive(Debug, Clone)]
#[repr(C)]
pub struct Identifier<T: IdentifierType> {
    boundaries_applied: bool,
    /// The original string that was parsed without concats
    original: Arc<String>,
    words: Arc<[String]>,
    duplicate_id: Option<NonZeroU32>,
    /// Must never change!
    id_type: T,
}

impl<T: IdentifierType> Identifier<T> {
    /// Try parse a string as an identifier.
    /// It will not have boundaries applied yet.
    pub fn try_parse(value: &str) -> Result<Self, Error>
    where
        T: Default,
    {
        Self::try_parse_with_type(value, T::default())
    }

    /// Try parse a string as an identifier.
    /// It will not have boundaries applied yet.
    pub fn try_parse_with_type(value: &str, id_type: T) -> Result<Self, Error> {
        if value.is_empty() {
            return Err(Error::Empty);
        }

        Ok(Self {
            boundaries_applied: false,
            original: Arc::new(value.into()),
            words: [value.into()].into(),
            duplicate_id: None,
            id_type,
        })
    }

    /// Apply the boundaries. This can only be called once and must be called before [`Self::to_case`]
    pub fn apply_boundaries(&mut self, boundaries: &[Boundary]) -> &mut Self {
        assert!(!self.boundaries_applied);

        let mut words = Vec::new();

        for word in self.words.iter() {
            let mut local_words = convert_case::split(word, boundaries);
            local_words.retain(|word| !word.is_empty());
            words.append(&mut local_words);
        }

        let words = Pattern::Lowercase.mutate(&words);

        self.boundaries_applied = true;
        self.words = words.into_iter().collect();
        self
    }

    pub fn check_validity(&self) -> Result<(), Error> {
        assert!(self.boundaries_applied);

        for (word_index, word) in self.words.iter().enumerate() {
            for (char_offset, char) in word.char_indices() {
                let tfn = match (word_index, char_offset) {
                    (0, 0) => |c| unicode_ident::is_xid_start(c),
                    _ => |c| unicode_ident::is_xid_continue(c),
                };

                if !tfn(char) {
                    let offset = self
                        .original()
                        .to_lowercase()
                        .find(word)
                        .map(|word_offset| word_offset + char_offset)
                        .expect("Word should be present in identifier words");
                    return Err(Error::InvalidCharacter {
                        byte_offset: offset,
                        invalid_char: char,
                    });
                }
            }
        }

        if self.words.iter().all(String::is_empty) {
            return Err(Error::EmptyAfterSplits);
        }

        let converted = self.to_case(Case::Pascal);
        if converted.contains(['-', '_', ' ']) {
            return Err(Error::CannotConvert {
                case_name: "Pascal",
                example: converted,
            });
        }

        Ok(())
    }

    /// Convert the identifier to a string in the given case
    pub fn to_case(&self, case: Case) -> String {
        assert!(
            self.boundaries_applied,
            "Boundaries not applied for `{}`",
            self.original()
        );

        let mut words = self.words.to_vec();

        if let Some(dup_id) = self.duplicate_id {
            words.push("dup".to_string());
            words.push(format!("{dup_id:X}"));
        }

        let words = case.mutate(&words.iter().map(String::as_str).collect::<Vec<_>>());
        case.join(&words)
    }

    /// Get the original text. Don't use this unless it's important to get the *exact* original value.
    /// Better to use [`Self::to_case`] in most circumstances.
    pub fn original(&self) -> &str {
        &self.original
    }

    /// Get a display string that separates the words that make up the identifier visually
    pub fn words_display(&self) -> String {
        self.words.join("·")
    }

    /// Same as [Self::words_display], but prepends another word
    pub fn words_display_prepended(&self, word: String) -> String {
        let mut words = self.words.to_vec();
        words.insert(0, word);
        words.join("·")
    }

    pub fn is_empty(&self) -> bool {
        self.words.iter().all(String::is_empty)
    }

    /// Get a type ref if this is a type identifier
    pub fn take_ref(&self) -> IdentifierRef<T>
    where
        T: Clone,
    {
        IdentifierRef {
            original: self.original.clone(),
            id_type: self.id_type.clone(),
        }
    }

    pub fn set_duplicate_id(&mut self, val: NonZeroU32) {
        self.duplicate_id = Some(val);
    }

    pub fn duplicate_id(&self) -> Option<NonZeroU32> {
        self.duplicate_id
    }

    pub fn to_runtime_type(self) -> Identifier<RuntimeType> {
        Identifier {
            boundaries_applied: self.boundaries_applied,
            original: self.original,
            words: self.words,
            duplicate_id: self.duplicate_id,
            id_type: self.id_type.runtime_value(),
        }
    }

    pub fn as_runtime_type_mut(&mut self) -> &mut Identifier<RuntimeType> {
        assert_eq!(size_of::<T>(), size_of::<RuntimeType>());
        // Safety: We're only casting the T to a RuntimeType which is explicitly allowed by all implementors of IdentifierType
        // The Identifier itself is repr C and so won't be weird when the generic type changes
        unsafe { std::mem::transmute::<&mut Self, &mut Identifier<RuntimeType>>(self) }
    }

    pub fn as_runtime_type(&self) -> &Identifier<RuntimeType> {
        assert_eq!(size_of::<T>(), size_of::<RuntimeType>());
        // Safety: We're only casting the T to a RuntimeType which is explicitly allowed by all implementors of IdentifierType
        // The Identifier itself is repr C and so won't be weird when the generic type changes
        unsafe { std::mem::transmute::<&Self, &Identifier<RuntimeType>>(self) }
    }

    /// Get the identifier type
    pub fn id_type(&self) -> &T {
        &self.id_type
    }

    /// Change the type of the identifier to a more specific type
    pub fn cast<U>(self) -> Identifier<U>
    where
        U: IdentifierType + Default,
        U: From<T>,
    {
        // Fine to do since we have the where bound
        self.cast_unchecked()
    }

    /// Change the type of the identifier.
    /// This is generally a bad idea because of the subtleties!
    /// So make sure this is actually what you want.
    pub fn cast_unchecked<U: IdentifierType + Default>(self) -> Identifier<U> {
        Identifier {
            boundaries_applied: self.boundaries_applied,
            original: self.original,
            words: self.words,
            duplicate_id: self.duplicate_id,
            id_type: U::default(),
        }
    }

    /// Change the type of the identifier, but only if the runtime type is already that type.
    /// This function will panic if they're different.
    #[track_caller]
    pub fn cast_assert<U: IdentifierType + Default>(self) -> Identifier<U> {
        assert_eq!(self.id_type.runtime_value(), U::default().runtime_value());

        Identifier {
            boundaries_applied: self.boundaries_applied,
            original: self.original,
            words: self.words,
            duplicate_id: self.duplicate_id,
            id_type: U::default(),
        }
    }
}

impl<T: IdentifierType + Default> Default for Identifier<T> {
    fn default() -> Self {
        Self {
            boundaries_applied: Default::default(),
            original: Default::default(),
            words: Default::default(),
            duplicate_id: Default::default(),
            id_type: T::default(),
        }
    }
}

impl<T: IdentifierType> std::hash::Hash for Identifier<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.original.hash(state);
        self.duplicate_id.hash(state);
        self.id_type.runtime_value().hash(state);
    }
}

impl<T: IdentifierType> PartialEq for Identifier<T> {
    fn eq(&self, other: &Self) -> bool {
        (self.original == other.original || self.words == other.words)
            && self.duplicate_id == other.duplicate_id
            && self
                .id_type
                .runtime_value()
                .shares_namespace_with(other.id_type.runtime_value())
    }
}
impl<T: IdentifierType> Eq for Identifier<T> {}

#[derive(Debug, Clone, Default)]
pub struct IdentifierRef<T: IdentifierType> {
    original: Arc<String>,
    id_type: T,
}

impl<T: IdentifierType> IdentifierRef<T> {
    pub fn new(identifier_original: String) -> Self
    where
        T: Default,
    {
        Self {
            original: Arc::new(identifier_original),
            id_type: T::default(),
        }
    }

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

    pub fn is_ref_to<U: IdentifierType>(&self, identifier: &Identifier<U>) -> bool {
        identifier.id_type.runtime_value() == self.id_type.runtime_value()
            && self.original() == identifier.original()
    }
}

impl<T: IdentifierType> std::hash::Hash for IdentifierRef<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.original.hash(state);
        self.id_type.runtime_value().hash(state);
    }
}

impl<T: IdentifierType> PartialEq for IdentifierRef<T> {
    fn eq(&self, other: &Self) -> bool {
        self.original == other.original
            && self
                .id_type
                .runtime_value()
                .shares_namespace_with(other.id_type.runtime_value())
    }
}
impl<T: IdentifierType> Eq for IdentifierRef<T> {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    Empty,
    EmptyAfterSplits,
    InvalidCharacter {
        byte_offset: usize,
        invalid_char: char,
    },
    CannotConvert {
        case_name: &'static str,
        example: String,
    },
}

impl std::error::Error for Error {}
impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Empty => write!(f, "identifier is empty"),
            Error::EmptyAfterSplits => write!(f, "identifier is empty after word split"),
            Error::InvalidCharacter {
                byte_offset,
                invalid_char,
            } => {
                write!(
                    f,
                    "identifier contains an invalid character at byte offset {byte_offset}: '{invalid_char:?}'"
                )
            }
            Error::CannotConvert { case_name, example } => {
                write!(
                    f,
                    "cannot change the casing of the identifier. Identifier is `{example}` when converted to {case_name} case, but that's not correct casing"
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn simple_cases() {
        assert_eq!(Identifier::<All>::try_parse(""), Err(Error::Empty));
        assert_eq!(
            Identifier::<All>::try_parse("1")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .check_validity(),
            Err(Error::InvalidCharacter {
                byte_offset: 0,
                invalid_char: '1'
            })
        );
        assert_eq!(
            Identifier::<All>::try_parse("_1")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .to_case(Case::Kebab),
            "1"
        );
        assert_eq!(
            Identifier::<All>::try_parse("a1")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .to_case(Case::Kebab),
            "a1"
        );
        assert_eq!(
            Identifier::<All>::try_parse("a_1")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .to_case(Case::Kebab),
            "a-1"
        );
        assert_eq!(
            Identifier::<All>::try_parse("😈")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .check_validity(),
            Err(Error::InvalidCharacter {
                byte_offset: 0,
                invalid_char: '😈'
            })
        );
        assert_eq!(
            Identifier::<All>::try_parse("abc😈")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .check_validity(),
            Err(Error::InvalidCharacter {
                byte_offset: 3,
                invalid_char: '😈'
            })
        );
        assert_eq!(
            Identifier::<All>::try_parse("_")
                .unwrap()
                .apply_boundaries(&[Boundary::Space])
                .to_case(Case::Kebab),
            "_"
        );
        assert_eq!(
            Identifier::<All>::try_parse("_")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .check_validity(),
            Err(Error::EmptyAfterSplits)
        );
        assert_eq!(
            Identifier::<All>::try_parse("abc def")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .check_validity(),
            Err(Error::InvalidCharacter {
                byte_offset: 3,
                invalid_char: ' '
            })
        );
        Identifier::<All>::try_parse("abc def")
            .unwrap()
            .apply_boundaries(&[Boundary::Space])
            .check_validity()
            .unwrap();
        assert_eq!(
            Identifier::<All>::try_parse("abc_def")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .to_case(Case::Kebab),
            "abc-def"
        );
        assert_eq!(
            Identifier::<All>::try_parse("_abc_def")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .to_case(Case::Kebab),
            "abc-def"
        );
        assert_eq!(
            Identifier::<All>::try_parse("Bar🚩bar")
                .unwrap()
                .apply_boundaries(&[Boundary::Underscore])
                .check_validity(),
            Err(Error::InvalidCharacter {
                byte_offset: 3,
                invalid_char: '🚩'
            })
        );
    }

    #[test]
    fn default_is_empty() {
        assert!(Identifier::<All>::default().is_empty());
    }

    #[test]
    fn static_vs_runtime_equals() {
        assert_eq!(
            Identifier::<Type>::try_parse("a")
                .unwrap()
                .to_runtime_type(),
            Identifier::try_parse_with_type("a", RuntimeType::Type).unwrap()
        );

        assert_ne!(
            Identifier::<Type>::try_parse("a")
                .unwrap()
                .to_runtime_type(),
            Identifier::try_parse_with_type("a", RuntimeType::Operation).unwrap()
        );
    }

    #[test]
    fn all_vs_specific_equals() {
        assert_eq!(
            Identifier::<All>::try_parse("a").unwrap().to_runtime_type(),
            Identifier::<Type>::try_parse("a")
                .unwrap()
                .to_runtime_type(),
        );
        assert_eq!(
            Identifier::<All>::try_parse("a").unwrap().to_runtime_type(),
            Identifier::<Operation>::try_parse("a")
                .unwrap()
                .to_runtime_type(),
        );
    }

    #[test]
    fn issue_274() {
        // https://github.com/diondokter/device-driver/issues/274
        Identifier::<All>::try_parse("io_pad_i2c_b1")
            .unwrap()
            .apply_boundaries(&Boundary::defaults())
            .check_validity()
            .unwrap();

        Identifier::<All>::try_parse("io_pad_i2c-b1")
            .unwrap()
            .apply_boundaries(&[Boundary::Underscore])
            .check_validity()
            .unwrap_err();
    }
}