1use core::fmt;
2use std::{
3 borrow::Cow,
4 collections::HashMap,
5 ops::{Deref, Index},
6 sync::Arc,
7};
8
9#[cfg(feature = "rkyv")]
10use rkyv::{Archive, Deserialize as rDeser, Serialize as rSer};
11use serde::{Deserialize, Serialize};
12
13use super::{Module, ModuleView, Page, PageMetadata, Scalar, SourceMappingNode};
14use crate::{error::prelude::*, ImmutBytes, ImmutStr, TakeAs};
15
16#[derive(Debug, Clone)]
18#[cfg_attr(feature = "rkyv", derive(Archive, rDeser, rSer))]
19#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
20#[repr(C)]
21pub enum LayoutRegionNode {
22 Indirect(usize),
24 Pages(Arc<(Vec<PageMetadata>, Vec<Page>)>),
26 SourceMapping(Arc<(Vec<PageMetadata>, Vec<SourceMappingNode>)>),
28}
29
30impl LayoutRegionNode {
31 pub fn new_pages(pages: Vec<Page>) -> Self {
32 Self::Pages(Arc::new((Default::default(), pages)))
33 }
34
35 pub fn new_source_mapping(source_mapping: Vec<SourceMappingNode>) -> Self {
36 Self::SourceMapping(Arc::new((Default::default(), source_mapping)))
37 }
38
39 pub fn pages_meta(&self) -> Option<&[Page]> {
40 let Self::Pages(v) = self else {
41 return None;
42 };
43
44 Some(&v.1)
45 }
46
47 pub fn pages<'a>(&'a self, module: &'a Module) -> Option<LayoutRegionPagesRAII<'a>> {
48 let Self::Pages(v) = self else {
49 return None;
50 };
51
52 Some(LayoutRegionPagesRAII {
53 module: Cow::Borrowed(ModuleView::new(module)),
54 meta: &v.0,
55 pages: &v.1,
56 })
57 }
58
59 pub fn source_mapping<'a>(
60 &'a self,
61 module: &'a Module,
62 ) -> Option<LayoutRegionSourceMappingRAII<'a>> {
63 let v = if let Self::SourceMapping(v) = self {
64 v
65 } else {
66 return None;
67 };
68
69 if v.0.is_empty() {
70 return Some(LayoutRegionSourceMappingRAII {
71 module: Cow::Borrowed(ModuleView::new(module)),
72 source_mapping: &v.1,
73 });
74 }
75
76 None
77 }
78
79 pub fn visit_pages(&self, f: &mut impl FnMut(&(Vec<PageMetadata>, Vec<Page>))) {
80 match self {
81 Self::Pages(v) => f(v),
82 Self::SourceMapping(..) | Self::Indirect(..) => {}
83 }
84 }
85
86 pub fn mutate_pages(self, f: &mut impl FnMut(&mut (Vec<PageMetadata>, Vec<Page>))) -> Self {
87 match self {
88 Self::Pages(v) => Self::Pages(Arc::new({
89 let mut v = v.take();
90 f(&mut v);
91 v
92 })),
93 Self::SourceMapping(..) | Self::Indirect(..) => self,
94 }
95 }
96
97 pub fn customs(v: &[PageMetadata]) -> impl Iterator<Item = &'_ (ImmutStr, ImmutBytes)> {
98 v.iter()
99 .flat_map(move |meta| match meta {
100 PageMetadata::Custom(customs) => Some(customs.iter()),
101 _ => None,
102 })
103 .flatten()
104 }
105}
106
107pub struct LayoutRegionPagesRAII<'a> {
108 module: Cow<'a, ModuleView>,
109 meta: &'a [PageMetadata],
110 pages: &'a [Page],
111 }
113
114impl<'a> LayoutRegionPagesRAII<'a> {
115 pub fn module(&self) -> &Module {
116 self.module.as_ref().as_ref()
117 }
118
119 pub fn pages(&self) -> &'a [Page] {
120 self.pages
121 }
122
123 pub fn meta(&self) -> &'a [PageMetadata] {
124 self.meta
125 }
126
127 pub fn customs(&self) -> impl Iterator<Item = &'_ (ImmutStr, ImmutBytes)> {
128 LayoutRegionNode::customs(self.meta)
129 }
130}
131
132pub struct LayoutRegionSourceMappingRAII<'a> {
133 module: Cow<'a, ModuleView>,
134 source_mapping: &'a [SourceMappingNode],
135 }
137
138impl<'a> LayoutRegionSourceMappingRAII<'a> {
139 pub fn module(&self) -> &Module {
140 self.module.as_ref().as_ref()
141 }
142
143 pub fn source_mapping(&self) -> &'a [SourceMappingNode] {
144 self.source_mapping
145 }
146}
147
148pub trait LayoutSelector {
149 fn select_by_scalar(
150 &self,
151 kind: &str,
152 layouts: &[(Scalar, LayoutRegionNode)],
153 ) -> Result<LayoutRegionNode>;
154
155 fn select_by_str(
156 &self,
157 kind: &str,
158 layouts: &[(ImmutStr, LayoutRegionNode)],
159 ) -> Result<LayoutRegionNode>;
160
161 fn resolve_indirect(&self, ind: usize) -> Result<&LayoutRegion> {
162 Err(error_once!(
163 "LayoutSelector: unimplemented indirect layout selector",
164 ind: ind,
165 ))
166 }
167}
168
169#[derive(Debug, Clone)]
171#[cfg_attr(feature = "rkyv", derive(Archive, rDeser, rSer))]
172#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
173pub struct LayoutRegionRepr<T> {
174 pub kind: ImmutStr,
175 pub layouts: Vec<(T, LayoutRegionNode)>,
176}
177
178#[derive(Clone)]
180#[cfg_attr(feature = "rkyv", derive(Archive, rDeser, rSer))]
181#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
182pub enum LayoutRegion {
183 ByScalar(LayoutRegionRepr<Scalar>),
184 ByStr(LayoutRegionRepr<ImmutStr>),
185}
186
187impl LayoutRegion {
188 pub fn new_single(layout: LayoutRegionNode) -> Self {
189 Self::ByScalar(LayoutRegionRepr {
190 kind: "_".into(),
191 layouts: vec![(Default::default(), layout)],
192 })
193 }
194
195 pub fn new_by_scalar(kind: ImmutStr, layouts: Vec<(Scalar, LayoutRegionNode)>) -> Self {
196 Self::ByScalar(LayoutRegionRepr { kind, layouts })
197 }
198
199 pub fn is_empty(&self) -> bool {
200 match self {
201 Self::ByScalar(v) => v.layouts.is_empty(),
202 Self::ByStr(v) => v.layouts.is_empty(),
203 }
204 }
205
206 pub fn unwrap_single(&self) -> LayoutRegionNode {
207 self.by_selector(&LayoutSelectorExpr::Any).unwrap()
208 }
209
210 pub fn by_scalar(&self) -> Option<&[(Scalar, LayoutRegionNode)]> {
211 if let Self::ByScalar(v) = self {
212 Some(&v.layouts)
213 } else {
214 None
215 }
216 }
217
218 pub fn by_selector(&self, selector: &impl LayoutSelector) -> Result<LayoutRegionNode> {
219 let mut t = Ok(self);
220 loop {
221 let next = match t? {
222 Self::ByScalar(v) => selector.select_by_scalar(&v.kind, &v.layouts),
223 Self::ByStr(v) => selector.select_by_str(&v.kind, &v.layouts),
224 }?;
225
226 if let LayoutRegionNode::Indirect(i) = next {
227 t = selector.resolve_indirect(i);
228 } else {
229 return Ok(next);
230 }
231 }
232 }
233
234 pub fn visit_pages(&self, f: &mut impl FnMut(&(Vec<PageMetadata>, Vec<Page>))) {
235 match self {
236 Self::ByScalar(v) => {
237 for (_, v) in v.layouts.iter() {
238 v.visit_pages(f)
239 }
240 }
241 Self::ByStr(v) => {
242 for (_, v) in v.layouts.iter() {
243 v.visit_pages(f)
244 }
245 }
246 }
247 }
248
249 pub fn mutate_pages(self, f: &mut impl FnMut(&mut (Vec<PageMetadata>, Vec<Page>))) -> Self {
250 match self {
251 Self::ByScalar(v) => Self::ByScalar(LayoutRegionRepr {
252 kind: v.kind,
253 layouts: v
254 .layouts
255 .into_iter()
256 .map(|(k, v)| (k, v.mutate_pages(f)))
257 .collect(),
258 }),
259 Self::ByStr(v) => Self::ByStr(LayoutRegionRepr {
260 kind: v.kind,
261 layouts: v
262 .layouts
263 .into_iter()
264 .map(|(k, v)| (k, v.mutate_pages(f)))
265 .collect(),
266 }),
267 }
268 }
269}
270
271impl Index<usize> for LayoutRegion {
272 type Output = LayoutRegionNode;
273
274 fn index(&self, index: usize) -> &Self::Output {
275 match self {
276 Self::ByScalar(v) => &v.layouts[index].1,
277 Self::ByStr(v) => &v.layouts[index].1,
278 }
279 }
280}
281
282impl fmt::Debug for LayoutRegion {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 match self {
285 Self::ByScalar(v) => {
286 write!(f, "LayoutRegion({:?})", v.kind)?;
287
288 #[allow(clippy::map_identity)]
289 let vs = v.layouts.iter().map(|(k, v)| (k, v));
290 f.debug_map().entries(vs).finish()
291 }
292 Self::ByStr(v) => {
293 write!(f, "LayoutRegion({:?})", v.kind)?;
294
295 #[allow(clippy::map_identity)]
296 let vs = v.layouts.iter().map(|(k, v)| (k, v));
297 f.debug_map().entries(vs).finish()
298 }
299 }
300 }
301}
302
303#[derive(Debug, Clone)]
304#[cfg_attr(feature = "rkyv", derive(Archive, rDeser, rSer))]
305#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
306pub struct LayoutSourceMapping(pub LayoutRegion);
307
308impl Default for LayoutSourceMapping {
309 fn default() -> Self {
310 Self::new_single(Default::default())
311 }
312}
313
314impl LayoutSourceMapping {
315 pub fn new_single(source_mapping: Vec<SourceMappingNode>) -> Self {
316 Self(LayoutRegion::new_single(
317 LayoutRegionNode::new_source_mapping(source_mapping),
318 ))
319 }
320}
321
322impl Deref for LayoutSourceMapping {
323 type Target = LayoutRegion;
324
325 fn deref(&self) -> &Self::Target {
326 &self.0
327 }
328}
329
330#[derive(Debug, Clone, Serialize, Deserialize)]
331#[serde(tag = "t", content = "v")]
332pub enum LayoutSelectorExpr {
333 Any,
335 First,
337 Last,
339 ScalarLB(f32),
342 ScalarUB(f32),
345 StrEQ(String),
347}
348
349impl Default for LayoutSelectorExpr {
350 fn default() -> Self {
351 Self::Any
352 }
353}
354
355impl LayoutSelector for LayoutSelectorExpr {
356 fn select_by_scalar(
357 &self,
358 kind: &str,
359 layouts: &[(Scalar, LayoutRegionNode)],
360 ) -> Result<LayoutRegionNode> {
361 let t = match self {
362 LayoutSelectorExpr::Any | LayoutSelectorExpr::First => layouts.first(),
363 LayoutSelectorExpr::Last => layouts.last(),
364 LayoutSelectorExpr::ScalarLB(v) => layouts
365 .iter()
366 .filter(|(scalar, _)| scalar.0 < *v)
367 .next_back(),
368 LayoutSelectorExpr::ScalarUB(v) => layouts
369 .iter()
370 .rev()
371 .filter(|(scalar, _)| scalar.0 > *v)
372 .next_back(),
373 LayoutSelectorExpr::StrEQ(..) => {
374 return Err(
375 error_once!("LayoutMappingSelector: cannot select kind by scalar type", kind: kind.to_owned()),
376 )
377 }
378 };
379 let t = t.map(|(_, v)| v.clone());
380
381 t.ok_or_else(
382 || error_once!("LayoutMappingSelector: no layout found by kind", kind: kind.to_owned(), is_not_found: true),
383 )
384 }
385
386 fn select_by_str(
387 &self,
388 kind: &str,
389 layouts: &[(ImmutStr, LayoutRegionNode)],
390 ) -> Result<LayoutRegionNode> {
391 let t = match self {
392 LayoutSelectorExpr::Any | LayoutSelectorExpr::First => {
393 layouts.first().map(|(_, v)| v.clone())
394 }
395 LayoutSelectorExpr::Last => layouts.last().map(|(_, v)| v.clone()),
396 LayoutSelectorExpr::StrEQ(v) => layouts
397 .iter()
398 .filter(|(s, _)| s.as_ref() == v)
399 .next_back()
400 .map(|(_, v)| v.clone()),
401 LayoutSelectorExpr::ScalarLB(..) | LayoutSelectorExpr::ScalarUB(..) => {
402 return Err(
403 error_once!("LayoutMappingSelector: cannot select kind by str type", kind: kind.to_owned()),
404 )
405 }
406 };
407
408 t.ok_or_else(
409 || error_once!("LayoutMappingSelector: no layout found by kind", kind: kind.to_owned(), is_not_found: true),
410 )
411 }
412}
413
414#[derive(Default, Debug, Clone, Serialize, Deserialize)]
415pub struct LayoutMappingSelector {
416 pub selectors: HashMap<String, LayoutSelectorExpr>,
417}
418
419impl LayoutSelector for LayoutMappingSelector {
420 fn select_by_scalar(
421 &self,
422 kind: &str,
423 layouts: &[(Scalar, LayoutRegionNode)],
424 ) -> Result<LayoutRegionNode> {
425 self.selectors
426 .get(kind)
427 .unwrap_or(&LayoutSelectorExpr::Any)
428 .select_by_scalar(kind, layouts)
429 }
430
431 fn select_by_str(
432 &self,
433 kind: &str,
434 layouts: &[(ImmutStr, LayoutRegionNode)],
435 ) -> Result<LayoutRegionNode> {
436 self.selectors
437 .get(kind)
438 .unwrap_or(&LayoutSelectorExpr::Any)
439 .select_by_str(kind, layouts)
440 }
441}
442
443#[derive(Default, Debug, Clone)]
444pub struct LayoutNestSelector<'l, T> {
445 pub layouts: &'l [LayoutRegion],
446 pub inner: T,
447}
448
449impl<T: LayoutSelector> LayoutSelector for LayoutNestSelector<'_, T> {
450 fn select_by_scalar(
451 &self,
452 kind: &str,
453 layouts: &[(Scalar, LayoutRegionNode)],
454 ) -> Result<LayoutRegionNode> {
455 self.inner.select_by_scalar(kind, layouts)
456 }
457
458 fn select_by_str(
459 &self,
460 kind: &str,
461 layouts: &[(ImmutStr, LayoutRegionNode)],
462 ) -> Result<LayoutRegionNode> {
463 self.inner.select_by_str(kind, layouts)
464 }
465
466 fn resolve_indirect(&self, ind: usize) -> Result<&LayoutRegion> {
467 self.layouts
468 .get(ind)
469 .ok_or_else(|| error_once!("LayoutNestSelector: indirect layout not found", ind: ind))
470 }
471}