wgsl_parser/fmt/
display.rs

1use std::fmt;
2
3use itertools::Itertools;
4
5use crate::{
6	common::{ArgumentList, Attribute, AttributeList, TypeDecl},
7	decl::{Decl, FieldDecl},
8	expr::{Expr, IdentExpr, NamespacedIdent, PrimaryExpr},
9};
10
11use super::Tooltip;
12
13impl fmt::Display for TypeDecl {
14	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
15		write!(f, "{}", self.name)?;
16
17		if let Some(ref child_ty) = self.child_ty {
18			write!(f, "<{}>", child_ty)?;
19		}
20
21		Ok(())
22	}
23}
24
25impl fmt::Display for Attribute {
26	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27		write!(f, "@{}", self.name)?;
28
29		if let Some(ref params) = self.params {
30			write!(f, "{params}")?;
31		}
32
33		Ok(())
34	}
35}
36
37impl fmt::Display for AttributeList {
38	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39		let inner = self.attributes.iter().join(" ");
40
41		write!(f, "{}", inner)
42	}
43}
44
45// FIXME
46impl fmt::Display for Decl {
47	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48		Tooltip::fmt(self, f)
49	}
50}
51
52impl fmt::Display for FieldDecl {
53	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54		if let Some(ref attributes) = self.attributes {
55			write!(f, "{} ", attributes)?;
56		}
57		write!(f, "{}: {}", self.name, self.ty)?;
58
59		if let Some(sep) = &self.separator {
60			write!(f, "{sep}")?;
61		}
62
63		Ok(())
64	}
65}
66
67impl fmt::Display for IdentExpr {
68	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69		let mut this = self;
70		while let IdentExpr::Namespaced(NamespacedIdent { namespace, ident }) = this {
71			write!(f, "{namespace}::")?;
72			this = ident.as_ref();
73		}
74
75		let IdentExpr::Leaf(name) = this else {
76			unreachable!();
77		};
78
79		write!(f, "{name}")
80	}
81}
82
83impl fmt::Display for ArgumentList {
84	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85		write!(f, "{}", self.brace_open)?;
86
87		let len = self.arguments.len();
88		for (idx, expr) in self.arguments.iter().enumerate() {
89			match expr {
90				Expr::Primary(PrimaryExpr {
91					expr,
92					postfix: None,
93				}) => match expr.as_ref() {
94					Expr::Ident(ident) => write!(f, "{ident}"),
95					Expr::Literal(literal) => write!(f, "{literal}"),
96					_ => write!(f, "ERR"), // TODO
97				},
98				_ => write!(f, "ERR"), // TODO
99			}?;
100
101			if idx < len - 1 {
102				write!(f, ", ")?;
103			}
104		}
105
106		write!(f, "{}", self.brace_close)
107	}
108}