reflexo/vector/ir/
layout.rs

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
use core::fmt;
use std::{
    borrow::Cow,
    collections::HashMap,
    ops::{Deref, Index},
    sync::Arc,
};

#[cfg(feature = "rkyv")]
use rkyv::{Archive, Deserialize as rDeser, Serialize as rSer};
use serde::{Deserialize, Serialize};

use super::{Module, ModuleView, Page, PageMetadata, Scalar, SourceMappingNode};
use crate::{error::prelude::*, ImmutBytes, ImmutStr, TakeAs};

/// Describing
#[derive(Debug, Clone)]
#[cfg_attr(feature = "rkyv", derive(Archive, rDeser, rSer))]
#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
#[repr(C)]
pub enum LayoutRegionNode {
    // next indirection
    Indirect(usize),
    // flat page layout
    Pages(Arc<(Vec<PageMetadata>, Vec<Page>)>),
    // source mapping node per page
    SourceMapping(Arc<(Vec<PageMetadata>, Vec<SourceMappingNode>)>),
}

impl LayoutRegionNode {
    pub fn new_pages(pages: Vec<Page>) -> Self {
        Self::Pages(Arc::new((Default::default(), pages)))
    }

    pub fn new_source_mapping(source_mapping: Vec<SourceMappingNode>) -> Self {
        Self::SourceMapping(Arc::new((Default::default(), source_mapping)))
    }

    pub fn pages_meta(&self) -> Option<&[Page]> {
        let Self::Pages(v) = self else {
            return None;
        };

        Some(&v.1)
    }

    pub fn pages<'a>(&'a self, module: &'a Module) -> Option<LayoutRegionPagesRAII<'a>> {
        let Self::Pages(v) = self else {
            return None;
        };

        Some(LayoutRegionPagesRAII {
            module: Cow::Borrowed(ModuleView::new(module)),
            meta: &v.0,
            pages: &v.1,
        })
    }

    pub fn source_mapping<'a>(
        &'a self,
        module: &'a Module,
    ) -> Option<LayoutRegionSourceMappingRAII<'a>> {
        let v = if let Self::SourceMapping(v) = self {
            v
        } else {
            return None;
        };

        if v.0.is_empty() {
            return Some(LayoutRegionSourceMappingRAII {
                module: Cow::Borrowed(ModuleView::new(module)),
                source_mapping: &v.1,
            });
        }

        None
    }

    pub fn visit_pages(&self, f: &mut impl FnMut(&(Vec<PageMetadata>, Vec<Page>))) {
        match self {
            Self::Pages(v) => f(v),
            Self::SourceMapping(..) | Self::Indirect(..) => {}
        }
    }

    pub fn mutate_pages(self, f: &mut impl FnMut(&mut (Vec<PageMetadata>, Vec<Page>))) -> Self {
        match self {
            Self::Pages(v) => Self::Pages(Arc::new({
                let mut v = v.take();
                f(&mut v);
                v
            })),
            Self::SourceMapping(..) | Self::Indirect(..) => self,
        }
    }

    pub fn customs(v: &[PageMetadata]) -> impl Iterator<Item = &'_ (ImmutStr, ImmutBytes)> {
        v.iter()
            .flat_map(move |meta| match meta {
                PageMetadata::Custom(customs) => Some(customs.iter()),
                _ => None,
            })
            .flatten()
    }
}

pub struct LayoutRegionPagesRAII<'a> {
    module: Cow<'a, ModuleView>,
    meta: &'a [PageMetadata],
    pages: &'a [Page],
    // todo: chaining module
}

impl<'a> LayoutRegionPagesRAII<'a> {
    pub fn module(&self) -> &Module {
        self.module.as_ref().as_ref()
    }

    pub fn pages(&self) -> &'a [Page] {
        self.pages
    }

    pub fn meta(&self) -> &'a [PageMetadata] {
        self.meta
    }

    pub fn customs(&self) -> impl Iterator<Item = &'_ (ImmutStr, ImmutBytes)> {
        LayoutRegionNode::customs(self.meta)
    }
}

pub struct LayoutRegionSourceMappingRAII<'a> {
    module: Cow<'a, ModuleView>,
    source_mapping: &'a [SourceMappingNode],
    // todo: chaining module
}

impl<'a> LayoutRegionSourceMappingRAII<'a> {
    pub fn module(&self) -> &Module {
        self.module.as_ref().as_ref()
    }

    pub fn source_mapping(&self) -> &'a [SourceMappingNode] {
        self.source_mapping
    }
}

pub trait LayoutSelector {
    fn select_by_scalar(
        &self,
        kind: &str,
        layouts: &[(Scalar, LayoutRegionNode)],
    ) -> ZResult<LayoutRegionNode>;

    fn select_by_str(
        &self,
        kind: &str,
        layouts: &[(ImmutStr, LayoutRegionNode)],
    ) -> ZResult<LayoutRegionNode>;

    fn resolve_indirect(&self, ind: usize) -> ZResult<&LayoutRegion> {
        Err(error_once!(
            "LayoutSelector: unimplemented indirect layout selector",
            ind: ind,
        ))
    }
}

/// Describing
#[derive(Debug, Clone)]
#[cfg_attr(feature = "rkyv", derive(Archive, rDeser, rSer))]
#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
pub struct LayoutRegionRepr<T> {
    pub kind: ImmutStr,
    pub layouts: Vec<(T, LayoutRegionNode)>,
}

/// Describing
#[derive(Clone)]
#[cfg_attr(feature = "rkyv", derive(Archive, rDeser, rSer))]
#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
pub enum LayoutRegion {
    ByScalar(LayoutRegionRepr<Scalar>),
    ByStr(LayoutRegionRepr<ImmutStr>),
}

impl LayoutRegion {
    pub fn new_single(layout: LayoutRegionNode) -> Self {
        Self::ByScalar(LayoutRegionRepr {
            kind: "_".into(),
            layouts: vec![(Default::default(), layout)],
        })
    }

    pub fn new_by_scalar(kind: ImmutStr, layouts: Vec<(Scalar, LayoutRegionNode)>) -> Self {
        Self::ByScalar(LayoutRegionRepr { kind, layouts })
    }

    pub fn is_empty(&self) -> bool {
        match self {
            Self::ByScalar(v) => v.layouts.is_empty(),
            Self::ByStr(v) => v.layouts.is_empty(),
        }
    }

    pub fn unwrap_single(&self) -> LayoutRegionNode {
        self.by_selector(&LayoutSelectorExpr::Any).unwrap()
    }

    pub fn by_scalar(&self) -> Option<&[(Scalar, LayoutRegionNode)]> {
        if let Self::ByScalar(v) = self {
            Some(&v.layouts)
        } else {
            None
        }
    }

    pub fn by_selector(&self, selector: &impl LayoutSelector) -> ZResult<LayoutRegionNode> {
        let mut t = Ok(self);
        loop {
            let next = match t? {
                Self::ByScalar(v) => selector.select_by_scalar(&v.kind, &v.layouts),
                Self::ByStr(v) => selector.select_by_str(&v.kind, &v.layouts),
            }?;

            if let LayoutRegionNode::Indirect(i) = next {
                t = selector.resolve_indirect(i);
            } else {
                return Ok(next);
            }
        }
    }

    pub fn visit_pages(&self, f: &mut impl FnMut(&(Vec<PageMetadata>, Vec<Page>))) {
        match self {
            Self::ByScalar(v) => {
                for (_, v) in v.layouts.iter() {
                    v.visit_pages(f)
                }
            }
            Self::ByStr(v) => {
                for (_, v) in v.layouts.iter() {
                    v.visit_pages(f)
                }
            }
        }
    }

    pub fn mutate_pages(self, f: &mut impl FnMut(&mut (Vec<PageMetadata>, Vec<Page>))) -> Self {
        match self {
            Self::ByScalar(v) => Self::ByScalar(LayoutRegionRepr {
                kind: v.kind,
                layouts: v
                    .layouts
                    .into_iter()
                    .map(|(k, v)| (k, v.mutate_pages(f)))
                    .collect(),
            }),
            Self::ByStr(v) => Self::ByStr(LayoutRegionRepr {
                kind: v.kind,
                layouts: v
                    .layouts
                    .into_iter()
                    .map(|(k, v)| (k, v.mutate_pages(f)))
                    .collect(),
            }),
        }
    }
}

impl Index<usize> for LayoutRegion {
    type Output = LayoutRegionNode;

    fn index(&self, index: usize) -> &Self::Output {
        match self {
            Self::ByScalar(v) => &v.layouts[index].1,
            Self::ByStr(v) => &v.layouts[index].1,
        }
    }
}

impl fmt::Debug for LayoutRegion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ByScalar(v) => {
                write!(f, "LayoutRegion({:?})", v.kind)?;

                #[allow(clippy::map_identity)]
                let vs = v.layouts.iter().map(|(k, v)| (k, v));
                f.debug_map().entries(vs).finish()
            }
            Self::ByStr(v) => {
                write!(f, "LayoutRegion({:?})", v.kind)?;

                #[allow(clippy::map_identity)]
                let vs = v.layouts.iter().map(|(k, v)| (k, v));
                f.debug_map().entries(vs).finish()
            }
        }
    }
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "rkyv", derive(Archive, rDeser, rSer))]
#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
pub struct LayoutSourceMapping(pub LayoutRegion);

impl Default for LayoutSourceMapping {
    fn default() -> Self {
        Self::new_single(Default::default())
    }
}

impl LayoutSourceMapping {
    pub fn new_single(source_mapping: Vec<SourceMappingNode>) -> Self {
        Self(LayoutRegion::new_single(
            LayoutRegionNode::new_source_mapping(source_mapping),
        ))
    }
}

impl Deref for LayoutSourceMapping {
    type Target = LayoutRegion;

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

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "t", content = "v")]
pub enum LayoutSelectorExpr {
    /// Selects any layout (smartly).
    Any,
    /// Selects the first layout.
    First,
    /// Selects the last layout.
    Last,
    /// Selects the max first layout with scalar value less than the given
    /// value.
    ScalarLB(f32),
    /// Selects the min last layout with scalar value greater than the given
    /// value.
    ScalarUB(f32),
    /// Selects the last layout with string value equal to the given value.
    StrEQ(String),
}

impl Default for LayoutSelectorExpr {
    fn default() -> Self {
        Self::Any
    }
}

impl LayoutSelector for LayoutSelectorExpr {
    fn select_by_scalar(
        &self,
        kind: &str,
        layouts: &[(Scalar, LayoutRegionNode)],
    ) -> ZResult<LayoutRegionNode> {
        let t = match self {
            LayoutSelectorExpr::Any | LayoutSelectorExpr::First => layouts.first(),
            LayoutSelectorExpr::Last => layouts.last(),
            LayoutSelectorExpr::ScalarLB(v) => {
                layouts.iter().filter(|(scalar, _)| scalar.0 < *v).last()
            }
            LayoutSelectorExpr::ScalarUB(v) => layouts
                .iter()
                .rev()
                .filter(|(scalar, _)| scalar.0 > *v)
                .last(),
            LayoutSelectorExpr::StrEQ(..) => {
                return Err(
                    error_once!("LayoutMappingSelector: cannot select kind by scalar type", kind: kind.to_owned()),
                )
            }
        };
        let t = t.map(|(_, v)| v.clone());

        t.ok_or_else(
            || error_once!("LayoutMappingSelector: no layout found by kind", kind: kind.to_owned(), is_not_found: true),
        )
    }

    fn select_by_str(
        &self,
        kind: &str,
        layouts: &[(ImmutStr, LayoutRegionNode)],
    ) -> ZResult<LayoutRegionNode> {
        let t = match self {
            LayoutSelectorExpr::Any | LayoutSelectorExpr::First => {
                layouts.first().map(|(_, v)| v.clone())
            }
            LayoutSelectorExpr::Last => layouts.last().map(|(_, v)| v.clone()),
            LayoutSelectorExpr::StrEQ(v) => layouts
                .iter()
                .filter(|(s, _)| s.as_ref() == v)
                .last()
                .map(|(_, v)| v.clone()),
            LayoutSelectorExpr::ScalarLB(..) | LayoutSelectorExpr::ScalarUB(..) => {
                return Err(
                    error_once!("LayoutMappingSelector: cannot select kind by str type", kind: kind.to_owned()),
                )
            }
        };

        t.ok_or_else(
            || error_once!("LayoutMappingSelector: no layout found by kind", kind: kind.to_owned(), is_not_found: true),
        )
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct LayoutMappingSelector {
    pub selectors: HashMap<String, LayoutSelectorExpr>,
}

impl LayoutSelector for LayoutMappingSelector {
    fn select_by_scalar(
        &self,
        kind: &str,
        layouts: &[(Scalar, LayoutRegionNode)],
    ) -> ZResult<LayoutRegionNode> {
        self.selectors
            .get(kind)
            .unwrap_or(&LayoutSelectorExpr::Any)
            .select_by_scalar(kind, layouts)
    }

    fn select_by_str(
        &self,
        kind: &str,
        layouts: &[(ImmutStr, LayoutRegionNode)],
    ) -> ZResult<LayoutRegionNode> {
        self.selectors
            .get(kind)
            .unwrap_or(&LayoutSelectorExpr::Any)
            .select_by_str(kind, layouts)
    }
}

#[derive(Default, Debug, Clone)]
pub struct LayoutNestSelector<'l, T> {
    pub layouts: &'l [LayoutRegion],
    pub inner: T,
}

impl<T: LayoutSelector> LayoutSelector for LayoutNestSelector<'_, T> {
    fn select_by_scalar(
        &self,
        kind: &str,
        layouts: &[(Scalar, LayoutRegionNode)],
    ) -> ZResult<LayoutRegionNode> {
        self.inner.select_by_scalar(kind, layouts)
    }

    fn select_by_str(
        &self,
        kind: &str,
        layouts: &[(ImmutStr, LayoutRegionNode)],
    ) -> ZResult<LayoutRegionNode> {
        self.inner.select_by_str(kind, layouts)
    }

    fn resolve_indirect(&self, ind: usize) -> ZResult<&LayoutRegion> {
        self.layouts
            .get(ind)
            .ok_or_else(|| error_once!("LayoutNestSelector: indirect layout not found", ind: ind))
    }
}