diff options
Diffstat (limited to 'crates/ra_hir/src/ty/display.rs')
-rw-r--r-- | crates/ra_hir/src/ty/display.rs | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/crates/ra_hir/src/ty/display.rs b/crates/ra_hir/src/ty/display.rs new file mode 100644 index 000000000..63ec9d7e1 --- /dev/null +++ b/crates/ra_hir/src/ty/display.rs | |||
@@ -0,0 +1,56 @@ | |||
1 | use std::fmt; | ||
2 | |||
3 | use crate::db::HirDatabase; | ||
4 | |||
5 | pub struct HirFormatter<'a, 'b, DB> { | ||
6 | pub db: &'a DB, | ||
7 | fmt: &'a mut fmt::Formatter<'b>, | ||
8 | } | ||
9 | |||
10 | pub trait HirDisplay { | ||
11 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result; | ||
12 | fn display<'a, DB>(&'a self, db: &'a DB) -> HirDisplayWrapper<'a, DB, Self> | ||
13 | where | ||
14 | Self: Sized, | ||
15 | { | ||
16 | HirDisplayWrapper(db, self) | ||
17 | } | ||
18 | } | ||
19 | |||
20 | impl<'a, 'b, DB> HirFormatter<'a, 'b, DB> | ||
21 | where | ||
22 | DB: HirDatabase, | ||
23 | { | ||
24 | pub fn write_joined<T: HirDisplay>( | ||
25 | &mut self, | ||
26 | iter: impl IntoIterator<Item = T>, | ||
27 | sep: &str, | ||
28 | ) -> fmt::Result { | ||
29 | let mut first = true; | ||
30 | for e in iter { | ||
31 | if !first { | ||
32 | write!(self, "{}", sep)?; | ||
33 | } | ||
34 | first = false; | ||
35 | e.hir_fmt(self)?; | ||
36 | } | ||
37 | Ok(()) | ||
38 | } | ||
39 | |||
40 | /// This allows using the `write!` macro directly with a `HirFormatter`. | ||
41 | pub fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { | ||
42 | fmt::write(self.fmt, args) | ||
43 | } | ||
44 | } | ||
45 | |||
46 | pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T); | ||
47 | |||
48 | impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T> | ||
49 | where | ||
50 | DB: HirDatabase, | ||
51 | T: HirDisplay, | ||
52 | { | ||
53 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
54 | self.1.hir_fmt(&mut HirFormatter { db: self.0, fmt: f }) | ||
55 | } | ||
56 | } | ||