ginko 0.0.6

A device-tree source parser and analyzer
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
use crate::dts::data::HasSource;
use crate::dts::tokens::Token;
use crate::dts::{HasSpan, Span};
use itertools::Itertools;
use std::fmt::{Display, Formatter, LowerHex};
use std::io;
use std::ops::Deref;
use std::path::{Path as StdPath, PathBuf};
use std::sync::Arc;

#[derive(Clone, Eq, PartialEq, Debug)]
pub struct WithToken<T> {
    item: T,
    token: Token,
}

impl<T> HasSpan for WithToken<T> {
    fn span(&self) -> Span {
        self.token.span
    }
}

impl<T> HasSource for WithToken<T> {
    fn source(&self) -> Arc<StdPath> {
        self.token.source()
    }
}

impl<T> WithToken<T> {
    pub fn new(item: T, token: Token) -> WithToken<T> {
        WithToken { item, token }
    }

    pub fn item(&self) -> &T {
        &self.item
    }
}

impl<T> Deref for WithToken<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.item
    }
}

impl<T> Display for WithToken<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.item())
    }
}

impl<T> LowerHex for WithToken<T>
where
    T: LowerHex,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:x}", self.item())
    }
}

// LRM 2.2.1 – Node Names
#[derive(Eq, PartialEq, Debug, Hash, Clone)]
pub struct NodeName {
    pub name: String,
    pub unit_address: Option<String>,
}

impl From<String> for NodeName {
    fn from(value: String) -> Self {
        if let Some((prefix, suffix)) = value.split_once('@') {
            NodeName::with_address(prefix, suffix)
        } else {
            NodeName::simple(value)
        }
    }
}

impl From<&str> for NodeName {
    fn from(value: &str) -> Self {
        if let Some((prefix, suffix)) = value.split_once('@') {
            NodeName::with_address(prefix, suffix)
        } else {
            NodeName::simple(value)
        }
    }
}

impl From<WithToken<String>> for WithToken<NodeName> {
    fn from(value: WithToken<String>) -> Self {
        WithToken::new(NodeName::from(value.item), value.token)
    }
}

impl NodeName {
    pub fn simple(name: impl Into<String>) -> NodeName {
        NodeName {
            name: name.into(),
            unit_address: None,
        }
    }

    pub fn with_address(name: impl Into<String>, address: impl Into<String>) -> NodeName {
        NodeName {
            name: name.into(),
            unit_address: Some(address.into()),
        }
    }
}

impl Display for NodeName {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)?;
        if let Some(unit_address) = &self.unit_address {
            write!(f, "@{}", unit_address)?;
        }
        Ok(())
    }
}

// LRM 2.2.3 – Paths
#[derive(Eq, PartialEq, Debug, Hash, Clone)]
pub struct Path {
    elements: Vec<NodeName>,
}

impl Display for Path {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.elements.is_empty() {
            write!(f, "/")
        } else {
            for element in &self.elements {
                write!(f, "/{}", element)?;
            }
            Ok(())
        }
    }
}

impl Path {
    pub fn new(elements: Vec<NodeName>) -> Path {
        Path { elements }
    }

    pub fn empty() -> Path {
        Path { elements: vec![] }
    }

    pub fn with_child(&self, child: NodeName) -> Path {
        let mut new_elements = self.elements.clone();
        new_elements.push(child);
        Path {
            elements: new_elements,
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = &NodeName> {
        self.elements.iter()
    }
}

impl From<&str> for Path {
    fn from(value: &str) -> Self {
        Path::new(
            value
                .split('/')
                .filter(|component| !component.is_empty())
                .map(NodeName::from)
                .collect_vec(),
        )
    }
}

#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Reference {
    Label(String),
    Path(Path),
}

impl Display for Reference {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Reference::Label(label) => write!(f, "&{label}"),
            Reference::Path(path) => write!(f, "&{{{path}}}"),
        }
    }
}

#[derive(Eq, PartialEq, Debug)]
pub enum Cell {
    Number(WithToken<u32>),
    Reference(WithToken<Reference>),
    Expression,
}

impl Display for Cell {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Cell::Number(num) => write!(f, "0x{num:x}"),
            Cell::Reference(reference) => write!(f, "{reference}"),
            Cell::Expression => write!(f, "(not implemented)"),
        }
    }
}

// LRM 2.2.4 Property Values
#[derive(Eq, PartialEq, Debug)]
pub enum PropertyValue {
    String(WithToken<String>),
    Cells(Token, Vec<Cell>, Token),
    Reference(WithToken<Reference>),
    ByteStrings(Token, Vec<WithToken<Vec<u8>>>, Token),
}

impl HasSpan for PropertyValue {
    fn span(&self) -> Span {
        match self {
            PropertyValue::String(str) => str.span(),
            PropertyValue::Cells(start, _, end) => start.start().to(end.end()),
            PropertyValue::Reference(reference) => reference.span(),
            PropertyValue::ByteStrings(start, _, end) => start.start().to(end.end()),
        }
    }
}

impl HasSource for PropertyValue {
    fn source(&self) -> Arc<StdPath> {
        match self {
            PropertyValue::String(str) => str.token.source(),
            PropertyValue::Cells(start, ..) => start.source.clone(),
            PropertyValue::Reference(reference) => reference.token.source.clone(),
            PropertyValue::ByteStrings(start, ..) => start.source.clone(),
        }
    }
}

impl Display for PropertyValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match &self {
            PropertyValue::String(string) => {
                write!(f, "\"{string}\"")
            }
            PropertyValue::Cells(_, numbers, _) => {
                write!(f, "<")?;
                for (i, num) in numbers.iter().enumerate() {
                    write!(f, "{num}")?;
                    if i != numbers.len() - 1 {
                        write!(f, " ")?;
                    }
                }
                write!(f, ">")
            }
            PropertyValue::Reference(reference) => write!(f, "{reference}",),
            PropertyValue::ByteStrings(_, strings, _) => {
                write!(f, "[")?;
                for (i, numbers) in strings.iter().enumerate() {
                    for num in &numbers.item {
                        write!(f, "{num:2x}")?;
                    }
                    if i != strings.len() - 1 {
                        write!(f, " ")?;
                    }
                }
                write!(f, "]")
            }
        }
    }
}

// LRM 2.2.4 Property Values
#[derive(Eq, PartialEq, Debug)]
pub struct Property {
    pub label: Option<WithToken<String>>,
    pub name: WithToken<String>,
    pub values: Vec<PropertyValue>,
    pub end: Token,
}

impl HasSpan for Property {
    fn span(&self) -> Span {
        self.label
            .as_ref()
            .map(|label| label.token.span())
            .unwrap_or(self.name.span())
            .start()
            .to(self.end.end())
    }
}

impl Property {
    pub fn empty(
        name: WithToken<String>,
        label: Option<WithToken<String>>,
        end: Token,
    ) -> Property {
        Property {
            label,
            name,
            values: vec![],
            end,
        }
    }

    #[cfg(test)]
    pub fn simple(
        name: WithToken<String>,
        value: PropertyValue,
        label: Option<WithToken<String>>,
        end: Token,
    ) -> Property {
        Property {
            label,
            name,
            values: vec![value],
            end,
        }
    }
}

impl Display for Property {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.values.is_empty() {
            writeln!(f, "{};", self.name)
        } else {
            write!(f, "{} = ", self.name)?;
            for (i, value) in self.values.iter().enumerate() {
                write!(f, "{value}")?;
                if i != self.values.len() - 1 {
                    write!(f, ", ")?;
                }
            }
            writeln!(f, ";")
        }
    }
}

#[derive(Eq, PartialEq, Debug)]
pub struct Node {
    pub label: Option<WithToken<String>>,
    pub name: WithToken<NodeName>,
    pub payload: NodePayload,
    pub omit_if_no_ref: Option<Token>,
}

#[derive(Eq, PartialEq, Debug)]
pub enum NodeItem {
    Property(Arc<Property>),
    Node(Arc<Node>),
    DeletedNode(Token, WithToken<NodeName>),
    DeletedProperty(Token, WithToken<String>),
}

impl Display for NodeItem {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            NodeItem::Property(property) => write!(f, "{}", property),
            NodeItem::Node(node) => write!(f, "{}", node),
            NodeItem::DeletedNode(_, node_name) => write!(f, "/delete-node/ {}", node_name),
            NodeItem::DeletedProperty(_, property_name) => {
                write!(f, "/delete-property/ {}", property_name)
            }
        }
    }
}

#[derive(Eq, PartialEq, Debug)]
pub struct NodePayload {
    pub items: Vec<NodeItem>,
    pub end: Token,
}

impl Display for NodePayload {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{{")?;
        for item in &self.items {
            writeln!(f, "    {item}")?;
        }
        write!(f, "}};")
    }
}

impl HasSpan for Node {
    fn span(&self) -> Span {
        self.label
            .as_ref()
            .map(|lbl| lbl.span())
            .unwrap_or(self.name.span())
            .start()
            .to(self.payload.end.span.end())
    }
}

impl Display for Node {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if let Some(label) = &self.label {
            write!(f, "{}: ", label.item)?;
        }
        write!(f, "{} {}", self.name.item(), self.payload)
    }
}

#[derive(Eq, PartialEq, Debug)]
pub struct Memreserve {
    address: WithToken<u64>,
    length: WithToken<u64>,
}

impl Memreserve {
    pub fn new(address: WithToken<u64>, length: WithToken<u64>) -> Memreserve {
        Memreserve { address, length }
    }
}

impl Display for Memreserve {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "/memreserve/ 0x{:x} 0x{:x};",
            *self.address, *self.length
        )
    }
}

#[derive(Eq, PartialEq, Debug)]
pub struct DtsFile {
    pub elements: Vec<Primary>,
    pub source: Arc<StdPath>,
}

impl HasSource for DtsFile {
    fn source(&self) -> Arc<StdPath> {
        self.source.clone()
    }
}

impl Display for DtsFile {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        for primary in &self.elements {
            writeln!(f, "{primary}")?;
        }
        Ok(())
    }
}

#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Include {
    pub include_token: Token,
    pub file_name: WithToken<String>,
    pub include_paths: Vec<PathBuf>,
}

impl HasSpan for Include {
    fn span(&self) -> Span {
        self.include_token.start().to(self.file_name.end())
    }
}

impl HasSource for Include {
    fn source(&self) -> Arc<StdPath> {
        self.include_token.source()
    }
}

impl Display for Include {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "/include/ \"{}\"", self.file_name)
    }
}

impl Include {
    pub fn path(&self) -> Result<PathBuf, io::Error> {
        let include_resolved = self.include_paths.iter().find_map(|include_path| {
            let path = include_path.join(self.file_name.to_string());
            dunce::canonicalize(path).ok()
        });

        if let Some(include_resolved) = include_resolved {
            Ok(include_resolved)
        } else {
            dunce::canonicalize(self.file_name.to_string())
        }
    }
}

#[derive(Eq, PartialEq, Debug)]
pub enum AnyDirective {
    DtsHeader(Token),
    Plugin(Token),
    Memreserve(Memreserve),
    Include(Include),
    DeletedNode(Token, WithToken<Reference>),
    OmitIfNoRef(Token, WithToken<Reference>),
}

impl Display for AnyDirective {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            AnyDirective::DtsHeader(_) => write!(f, "/dts-v1/;"),
            AnyDirective::Memreserve(memreserve) => write!(f, "{memreserve};"),
            AnyDirective::Include(include) => write!(f, "{include}"),
            AnyDirective::Plugin(_) => write!(f, "/plugin/;"),
            AnyDirective::DeletedNode(_, reference) => write!(f, "/delete-node/ {reference};"),
            AnyDirective::OmitIfNoRef(_, reference) => write!(f, "/omit-if-no-ref/ {reference};"),
        }
    }
}

#[derive(Eq, PartialEq, Debug)]
pub struct ReferencedNode {
    pub reference: WithToken<Reference>,
    pub payload: NodePayload,
}

impl HasSpan for ReferencedNode {
    fn span(&self) -> Span {
        self.reference.start().to(self.payload.end.end())
    }
}

impl Display for ReferencedNode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {}", self.reference, self.payload)
    }
}

#[derive(Eq, PartialEq, Debug)]
pub enum Primary {
    Directive(AnyDirective),
    Root(Arc<Node>),
    ReferencedNode(ReferencedNode),
    // C-style includes should be put into a separate pass
    CStyleInclude(String),
}

impl Primary {
    pub fn as_include(&self) -> Option<&Include> {
        match self {
            Primary::Directive(AnyDirective::Include(include)) => Some(include),
            _ => None,
        }
    }
}

impl Display for Primary {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Primary::Directive(directive) => write!(f, "{directive}"),
            Primary::Root(node) => write!(f, "{node}"),
            Primary::ReferencedNode(node) => write!(f, "{node}"),
            Primary::CStyleInclude(include) => write!(f, "#include {include}"),
        }
    }
}