|
| 1 | +// Copyright (c) 2018 The predicates-rs Project Developers. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | +// http://www.apache.org/license/LICENSE-2.0> or the MIT license |
| 5 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 6 | +// option. This file may not be copied, modified, or distributed |
| 7 | +// except according to those terms. |
| 8 | + |
| 9 | +//! Render `Case` as a tree. |
| 10 | +
|
| 11 | +use std::fmt; |
| 12 | + |
| 13 | +use treeline; |
| 14 | + |
| 15 | +use reflection; |
| 16 | + |
| 17 | +/// Render `Self` as a displayable tree. |
| 18 | +pub trait CaseTreeExt { |
| 19 | + /// Render `Self` as a displayable tree. |
| 20 | + fn tree(&self) -> CaseTree; |
| 21 | +} |
| 22 | + |
| 23 | +impl<'a> CaseTreeExt for reflection::Case<'a> { |
| 24 | + fn tree(&self) -> CaseTree { |
| 25 | + CaseTree(convert(self)) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +type CaseTreeInner = treeline::Tree<Box<fmt::Display>>; |
| 30 | + |
| 31 | +fn convert<'a>(case: &reflection::Case<'a>) -> CaseTreeInner { |
| 32 | + let mut leaves: Vec<CaseTreeInner> = vec![]; |
| 33 | + |
| 34 | + leaves.extend(case.predicate().iter().flat_map(|pred| { |
| 35 | + pred.parameters().map(|item| { |
| 36 | + let root: Box<fmt::Display> = Box::new(item.to_string()); |
| 37 | + treeline::Tree::new(root, vec![]) |
| 38 | + }) |
| 39 | + })); |
| 40 | + |
| 41 | + leaves.extend(case.products().map(|item| { |
| 42 | + let root: Box<fmt::Display> = Box::new(item.to_string()); |
| 43 | + treeline::Tree::new(root, vec![]) |
| 44 | + })); |
| 45 | + |
| 46 | + leaves.extend(case.children().map(|item| convert(item))); |
| 47 | + |
| 48 | + let root = Box::new(case.predicate().map(|p| p.to_string()).unwrap_or_default()); |
| 49 | + CaseTreeInner::new(root, leaves) |
| 50 | +} |
| 51 | + |
| 52 | +/// A `Case` rendered as a tree for display. |
| 53 | +#[allow(missing_debug_implementations)] |
| 54 | +pub struct CaseTree(CaseTreeInner); |
| 55 | + |
| 56 | +impl fmt::Display for CaseTree { |
| 57 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 58 | + self.0.fmt(f) |
| 59 | + } |
| 60 | +} |
0 commit comments