]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir/src/ty/display.rs
7910429d72ff5801c3ae2405c55f1b09af2ffa09
[rust.git] / crates / ra_hir / src / ty / display.rs
1 //! FIXME: write short doc here
2
3 use std::fmt;
4
5 use crate::db::HirDatabase;
6
7 pub struct HirFormatter<'a, 'b, DB> {
8     pub db: &'a DB,
9     fmt: &'a mut fmt::Formatter<'b>,
10 }
11
12 pub trait HirDisplay {
13     fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result;
14     fn display<'a, DB>(&'a self, db: &'a DB) -> HirDisplayWrapper<'a, DB, Self>
15     where
16         Self: Sized,
17     {
18         HirDisplayWrapper(db, self)
19     }
20 }
21
22 impl<'a, 'b, DB> HirFormatter<'a, 'b, DB>
23 where
24     DB: HirDatabase,
25 {
26     pub fn write_joined<T: HirDisplay>(
27         &mut self,
28         iter: impl IntoIterator<Item = T>,
29         sep: &str,
30     ) -> fmt::Result {
31         let mut first = true;
32         for e in iter {
33             if !first {
34                 write!(self, "{}", sep)?;
35             }
36             first = false;
37             e.hir_fmt(self)?;
38         }
39         Ok(())
40     }
41
42     /// This allows using the `write!` macro directly with a `HirFormatter`.
43     pub fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result {
44         fmt::write(self.fmt, args)
45     }
46 }
47
48 pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T);
49
50 impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T>
51 where
52     DB: HirDatabase,
53     T: HirDisplay,
54 {
55     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56         self.1.hir_fmt(&mut HirFormatter { db: self.0, fmt: f })
57     }
58 }