1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::fmt;
4
5use crate::ast::*;
6use crate::ids::IndexVec;
7use crate::pretty::FmtWithCtx;
8use crate::utils::TAB_INCR;
9
10pub trait IntoFormatter {
11 type C: AstFormatter;
12 fn into_fmt(self) -> Self::C;
13}
14
15pub trait AstFormatter: Sized {
18 type Reborrow<'a>: AstFormatter + 'a
19 where
20 Self: 'a;
21
22 fn get_crate(&self) -> Option<&TranslatedCrate>;
23
24 fn include_layouts(&self) -> bool {
25 false
26 }
27 fn include_safety(&self) -> bool {
28 false
29 }
30 fn hide_storage_statements(&self) -> bool {
31 false
32 }
33
34 fn no_generics<'a>(&'a self) -> Self::Reborrow<'a>;
35 fn set_generics<'a>(&'a self, generics: &'a GenericParams) -> Self::Reborrow<'a>;
36 fn set_current_type<'a>(&'a self, type_id: TypeDeclId) -> Self::Reborrow<'a>;
37 fn set_locals<'a>(&'a self, locals: &'a Locals) -> Self::Reborrow<'a>;
38 fn push_binder<'a>(&'a self, new_params: Cow<'a, GenericParams>) -> Self::Reborrow<'a>;
39 fn push_bound_regions<'a>(
40 &'a self,
41 regions: &'a IndexVec<RegionId, RegionParam>,
42 ) -> Self::Reborrow<'a> {
43 self.push_binder(Cow::Owned(GenericParams {
44 regions: regions.clone(),
45 ..Default::default()
46 }))
47 }
48 fn binder_depth(&self) -> usize;
50
51 fn increase_indent<'a>(&'a self) -> Self::Reborrow<'a>;
52 fn reset_indent<'a>(&'a self) -> Self::Reborrow<'a>;
53 fn indent(&self) -> String;
54
55 fn format_local_id(&self, f: &mut fmt::Formatter<'_>, id: LocalId) -> fmt::Result;
56 fn format_bound_var<Id: TypeLevelVar>(
57 &self,
58 f: &mut fmt::Formatter<'_>,
59 var: DeBruijnVar<Id>,
60 var_prefix: &str,
61 fmt_var: impl Fn(&Id::Param) -> Option<String>,
62 ) -> fmt::Result;
63
64 fn format_method_name(
65 &self,
66 f: &mut fmt::Formatter<'_>,
67 trait_id: TraitDeclId,
68 method_id: TraitMethodId,
69 ) -> fmt::Result {
70 if let Some(translated) = self.get_crate()
71 && let Some(names) = translated.assoc_item_names.get(trait_id)
72 && let Some(name) = names.methods.get(method_id).copied()
73 {
74 write!(f, "{name}")
75 } else {
76 write!(f, "{}", method_id.to_pretty_string())
77 }
78 }
79 fn format_assoc_type_name(
80 &self,
81 f: &mut fmt::Formatter<'_>,
82 trait_id: TraitDeclId,
83 type_id: AssocTypeId,
84 ) -> fmt::Result {
85 if let Some(translated) = self.get_crate()
86 && let Some(names) = translated.assoc_item_names.get(trait_id)
87 && let Some(name) = names.types.get(type_id).copied()
88 {
89 write!(f, "{name}")
90 } else {
91 write!(f, "{}", type_id.to_pretty_string())
92 }
93 }
94 fn format_assoc_const_name(
95 &self,
96 f: &mut fmt::Formatter<'_>,
97 trait_id: TraitDeclId,
98 const_id: AssocConstId,
99 ) -> fmt::Result {
100 if let Some(translated) = self.get_crate()
101 && let Some(names) = translated.assoc_item_names.get(trait_id)
102 && let Some(name) = names.consts.get(const_id).copied()
103 {
104 write!(f, "{name}")
105 } else {
106 write!(f, "{}", const_id.to_pretty_string())
107 }
108 }
109 fn format_assoc_item_name(
110 &self,
111 f: &mut fmt::Formatter<'_>,
112 trait_id: TraitDeclId,
113 item_id: AssocItemId,
114 ) -> fmt::Result {
115 match item_id {
116 AssocItemId::Type(id) => self.format_assoc_type_name(f, trait_id, id),
117 AssocItemId::Method(id) => self.format_method_name(f, trait_id, id),
118 AssocItemId::Const(id) => self.format_assoc_const_name(f, trait_id, id),
119 }
120 }
121
122 fn format_enum_variant_name(
123 &self,
124 f: &mut fmt::Formatter<'_>,
125 type_id: TypeDeclId,
126 variant_id: VariantId,
127 ) -> fmt::Result {
128 let variant = if let Some(translated) = self.get_crate()
129 && let Some(def) = translated.type_decls.get(type_id)
130 {
131 match &def.kind {
132 TypeDeclKind::Enum(variants) => &variants.get(variant_id).unwrap().name,
133 TypeDeclKind::Struct(..) | TypeDeclKind::Union(..) => "_",
134 TypeDeclKind::Opaque | TypeDeclKind::Alias(..) | TypeDeclKind::Error(..) => {
135 &variant_id.to_pretty_string()
136 }
137 }
138 } else {
139 &variant_id.to_pretty_string()
140 };
141 write!(f, "{variant}")
142 }
143 fn format_current_variant_name(
144 &self,
145 f: &mut fmt::Formatter<'_>,
146 variant_id: VariantId,
147 ) -> fmt::Result;
148 fn format_enum_variant(
149 &self,
150 f: &mut fmt::Formatter<'_>,
151 type_id: TypeDeclId,
152 variant_id: VariantId,
153 ) -> fmt::Result {
154 write!(f, "{}::", type_id.with_ctx(self))?;
155 self.format_enum_variant_name(f, type_id, variant_id)?;
156 Ok(())
157 }
158
159 fn format_field_name(
160 &self,
161 f: &mut fmt::Formatter<'_>,
162 type_id: TypeDeclId,
163 opt_variant_id: Option<VariantId>,
164 field_id: FieldId,
165 ) -> fmt::Result {
166 let field_name = if let Some(translated) = self.get_crate()
167 && let Some(def) = translated.type_decls.get(type_id)
168 {
169 match (&def.kind, opt_variant_id) {
170 (TypeDeclKind::Enum(variants), Some(variant_id)) => {
171 Some(&variants[variant_id].fields[field_id].name)
172 }
173 (TypeDeclKind::Struct(fields) | TypeDeclKind::Union(fields), _) => {
174 Some(&fields[field_id].name)
175 }
176 _ => None,
177 }
178 } else {
179 None
180 };
181 if let Some(field_name) = field_name {
182 write!(f, "{field_name}")
183 } else {
184 write!(f, "{field_id}")
185 }
186 }
187 fn format_current_field_name(
188 &self,
189 f: &mut fmt::Formatter<'_>,
190 _variant_id: VariantId,
191 field_id: FieldId,
192 ) -> fmt::Result;
193}
194
195#[derive(Default)]
197pub struct FmtCtx<'a> {
198 pub translated: Option<&'a TranslatedCrate>,
199 pub include_layouts: bool,
200 pub include_safety: bool,
201 pub hide_storage_statements: bool,
202 pub current_type: Option<TypeDeclId>,
203 pub generics: BindingStack<Cow<'a, GenericParams>>,
206 pub local_names: Option<Cow<'a, IndexVec<LocalId, String>>>,
207 pub indent_level: usize,
208}
209
210impl<'c> AstFormatter for FmtCtx<'c> {
211 type Reborrow<'a>
212 = FmtCtx<'a>
213 where
214 Self: 'a;
215
216 fn get_crate(&self) -> Option<&TranslatedCrate> {
217 self.translated
218 }
219
220 fn include_layouts(&self) -> bool {
221 self.include_layouts
222 }
223 fn include_safety(&self) -> bool {
224 self.include_safety
225 }
226 fn hide_storage_statements(&self) -> bool {
227 self.hide_storage_statements
228 }
229
230 fn no_generics<'a>(&'a self) -> Self::Reborrow<'a> {
231 FmtCtx {
232 generics: BindingStack::empty(),
233 ..self.reborrow()
234 }
235 }
236 fn set_generics<'a>(&'a self, generics: &'a GenericParams) -> Self::Reborrow<'a> {
237 FmtCtx {
238 generics: BindingStack::new(Cow::Borrowed(generics)),
239 ..self.reborrow()
240 }
241 }
242 fn set_current_type<'a>(&'a self, type_id: TypeDeclId) -> Self::Reborrow<'a> {
243 FmtCtx {
244 current_type: Some(type_id),
245 ..self.reborrow()
246 }
247 }
248 fn set_locals<'a>(&'a self, locals: &'a Locals) -> Self::Reborrow<'a> {
249 FmtCtx {
250 local_names: Some(Cow::Owned(compute_local_names(locals))),
251 ..self.reborrow()
252 }
253 }
254 fn push_binder<'a>(&'a self, new_params: Cow<'a, GenericParams>) -> Self::Reborrow<'a> {
255 let mut ret = self.reborrow();
256 ret.generics.push(new_params);
257 ret
258 }
259 fn binder_depth(&self) -> usize {
260 self.generics.len()
261 }
262
263 fn increase_indent<'a>(&'a self) -> Self::Reborrow<'a> {
264 FmtCtx {
265 indent_level: self.indent_level + 1,
266 ..self.reborrow()
267 }
268 }
269 fn reset_indent<'a>(&'a self) -> Self::Reborrow<'a> {
270 FmtCtx {
271 indent_level: 0,
272 ..self.reborrow()
273 }
274 }
275 fn indent(&self) -> String {
276 TAB_INCR.repeat(self.indent_level)
277 }
278
279 fn format_local_id(&self, f: &mut fmt::Formatter<'_>, id: LocalId) -> fmt::Result {
280 if let Some(local_names) = &self.local_names {
281 write!(f, "{}", local_names[id])
282 } else {
283 write!(f, "_{id}")
284 }
285 }
286
287 fn format_current_variant_name(
288 &self,
289 f: &mut fmt::Formatter<'_>,
290 variant_id: VariantId,
291 ) -> fmt::Result {
292 match self.current_type {
293 Some(type_id) => self.format_enum_variant_name(f, type_id, variant_id),
294 None => write!(f, "{variant_id}"),
295 }
296 }
297
298 fn format_current_field_name(
299 &self,
300 f: &mut fmt::Formatter<'_>,
301 variant_id: VariantId,
302 field_id: FieldId,
303 ) -> fmt::Result {
304 match self.current_type {
305 Some(type_id) => self.format_field_name(f, type_id, Some(variant_id), field_id),
306 None => write!(f, "{field_id}"),
307 }
308 }
309
310 fn format_bound_var<Id: TypeLevelVar>(
311 &self,
312 f: &mut fmt::Formatter<'_>,
313 var: DeBruijnVar<Id>,
314 var_prefix: &str,
315 fmt_var: impl Fn(&Id::Param) -> Option<String>,
316 ) -> fmt::Result {
317 if self.generics.is_empty() {
318 return write!(f, "{var_prefix}{var}");
319 }
320 match self.generics.get_var_with_outermost_free(var) {
321 None => write!(f, "missing({var_prefix}{var})"),
322 Some(v) => match fmt_var(v) {
323 Some(name) => write!(f, "{name}"),
324 None => {
325 write!(f, "{var_prefix}")?;
326 let (dbid, varid) = self.generics.as_bound_var_with_outermost_free(var);
327 let depth = self.generics.depth().index - dbid.index;
328 if depth == 0 {
329 write!(f, "{varid}")
330 } else {
331 write!(f, "{varid}_{depth}")
332 }
333 }
334 },
335 }
336 }
337}
338
339impl<'a> FmtCtx<'a> {
340 pub fn new() -> Self {
341 FmtCtx::default()
342 }
343
344 pub fn get_item(&self, id: ItemId) -> Result<ItemRef<'_>, Option<&Name>> {
345 let Some(translated) = &self.translated else {
346 return Err(None);
347 };
348 translated
349 .get_item(id)
350 .ok_or_else(|| Some(translated.item_short_name(id)))
351 }
352
353 pub fn format_decl_id(&self, id: impl Into<ItemId>) -> String {
355 let id = id.into();
356 match self.get_item(id) {
357 Ok(d) => d.to_string_with_ctx(self),
358 Err(opt_name) => {
359 let opt_name = opt_name
360 .map(|n| format!(" ({})", n.with_ctx(self)))
361 .unwrap_or_default();
362 format!("Missing decl: {id:?}{opt_name}")
363 }
364 }
365 }
366
367 fn reborrow<'b>(&'b self) -> FmtCtx<'b> {
368 FmtCtx {
369 translated: self.translated,
370 include_layouts: self.include_layouts,
371 include_safety: self.include_safety,
372 hide_storage_statements: self.hide_storage_statements,
373 current_type: self.current_type,
374 generics: self.generics.map_ref(|g| Cow::Borrowed(g.as_ref())),
376 local_names: self.local_names.as_deref().map(Cow::Borrowed),
377 indent_level: self.indent_level,
378 }
379 }
380}
381
382pub fn compute_local_names(locals: &Locals) -> IndexVec<LocalId, String> {
384 let mut local_names = locals.locals.map_ref(|local| {
385 format!(
386 "{}_{}",
387 local.name.as_deref().unwrap_or_default(),
388 local.index
389 )
390 });
391
392 let mut name_counts = HashMap::<String, usize>::new();
393 for local in &locals.locals {
394 *name_counts
395 .entry(local_names[local.index].clone())
396 .or_default() += 1;
397 if let Some(name) = &local.name {
398 *name_counts.entry(name.clone()).or_default() += 1;
399 }
400 }
401
402 for (id, local) in locals.locals.iter_enumerated() {
403 if let Some(name) = &local.name
404 && !name.is_empty()
405 && name_counts[name] == 1
406 {
407 local_names[id] = name.clone();
408 }
409 }
410 local_names
411}