1use std::borrow::Cow;
2use std::fmt;
3
4use crate::ast::Annotation;
5use crate::program::is_internal_package_id;
6use crate::program::{go_import_default_name, is_go_import, strip_go_prefix};
7use crate::types::SimpleKind;
8use crate::types::{Symbol, Type, TypeKind};
9
10#[derive(Clone, Copy, PartialEq, Eq)]
11enum Qualifier {
12 Package,
13 Path,
14}
15
16impl Type {
17 pub fn stringify(&self) -> String {
18 self.stringify_as(Qualifier::Package)
19 }
20
21 pub fn stringify_pair(first: &Self, second: &Self) -> (String, String) {
22 let (named, _) = Self::remove_vars(&[first, second]);
23 let (first, second) = (&named[0], &named[1]);
24
25 let (short_first, short_second) = (first.stringify(), second.stringify());
26 if short_first != short_second {
27 return (short_first, short_second);
28 }
29
30 let wide_first = first.stringify_as(Qualifier::Path);
31 let wide_second = second.stringify_as(Qualifier::Path);
32 if wide_first == wide_second {
33 return (short_first, short_second);
34 }
35
36 (wide_first, wide_second)
37 }
38
39 fn stringify_as(&self, qualifier: Qualifier) -> String {
40 let body = self.stringify_body(qualifier);
41 if self.is_writable() {
42 format!("mut {}", body)
43 } else {
44 body
45 }
46 }
47
48 fn stringify_body(&self, qualifier: Qualifier) -> String {
49 if let Some(spelling) = self.spelling() {
50 let name = qualified_name(&spelling.alias, qualifier);
51 if spelling.args.is_empty() {
52 return name.into_owned();
53 }
54 let args = spelling
55 .args
56 .iter()
57 .map(|argument| argument.stringify_as(qualifier))
58 .collect::<Vec<_>>()
59 .join(", ");
60 return format!("{name}<{args}>");
61 }
62 match self.kind() {
63 TypeKind::Nominal {
64 id, params: args, ..
65 } => {
66 let args_formatted = args
67 .iter()
68 .map(|a| a.stringify_as(qualifier))
69 .collect::<Vec<_>>()
70 .join(", ");
71
72 let leaf = id.last_segment();
73
74 if !is_go_import(id) {
75 if leaf == "Unit" {
76 return "()".to_string();
77 }
78
79 if leaf == "bool" {
80 return "bool".to_string();
81 }
82
83 if leaf.starts_with("Tuple") {
84 return format!("({})", args_formatted);
85 }
86
87 if leaf == "Ref" {
88 return format!("Ref<{}>", args_formatted);
89 }
90 }
91
92 let name = qualified_name(id, qualifier);
93
94 if args.is_empty() {
95 return name.into_owned();
96 }
97
98 format!("{}<{}>", name, args_formatted)
99 }
100
101 TypeKind::Var { id, hint } => match hint {
102 Some(name) => format!("?{}", name),
103 None => format!("?{}", id.index()),
104 },
105
106 TypeKind::Uninferred => "?uninferred".to_string(),
107
108 TypeKind::Function(f) => {
109 let args_formatted = f
110 .params
111 .iter()
112 .map(|param| param.ty.stringify_as(qualifier))
113 .collect::<Vec<_>>()
114 .join(", ");
115
116 let ret_formatted = f.return_type.stringify_as(qualifier);
117
118 format!("fn ({}) -> {}", args_formatted, ret_formatted)
119 }
120
121 TypeKind::Parameter(name) => name.to_string(),
122
123 TypeKind::Never => "Never".to_string(),
124
125 TypeKind::Tuple(elements) => {
126 let formatted = elements
127 .iter()
128 .map(|e| e.stringify_as(qualifier))
129 .collect::<Vec<_>>()
130 .join(", ");
131 format!("({})", formatted)
132 }
133
134 TypeKind::Array { length, element } => {
135 format!("Array<{}, {}>", element.stringify_as(qualifier), length)
136 }
137
138 TypeKind::Error(_) => "<error>".to_string(),
139
140 TypeKind::ImportNamespace(package_id)
141 if package_id.as_str() == crate::ENTRY_PACKAGE_ID =>
142 {
143 crate::ROOT_IMPORT.to_string()
144 }
145
146 TypeKind::ImportNamespace(package_id) => {
147 let path = strip_go_prefix(package_id).unwrap_or(package_id);
148 path.rsplit('/').next().unwrap_or(package_id).to_string()
149 }
150
151 TypeKind::ReceiverPlaceholder => "self".to_string(),
152
153 TypeKind::Simple(kind) => match kind {
154 SimpleKind::Unit => "()".to_string(),
155 _ => kind.leaf_name().to_string(),
156 },
157
158 TypeKind::Compound { kind, args, .. } => {
159 let args_formatted = args
160 .iter()
161 .map(|a| a.stringify_as(qualifier))
162 .collect::<Vec<_>>()
163 .join(", ");
164 if args.is_empty() {
165 kind.leaf_name().to_string()
166 } else {
167 format!("{}<{}>", kind.leaf_name(), args_formatted)
168 }
169 }
170 }
171 }
172}
173
174fn qualified_name(id: &Symbol, qualifier: Qualifier) -> Cow<'_, str> {
175 if let Some(path) = strip_go_prefix(id) {
176 if qualifier == Qualifier::Package
177 && let Some(short) = go_package_qualified_name(path, id.last_segment())
178 {
179 return Cow::Owned(short);
180 }
181 return Cow::Borrowed(path);
182 }
183
184 if qualifier == Qualifier::Package {
185 return Cow::Borrowed(id.last_segment());
186 }
187
188 match id.as_str().split_once('.') {
189 Some((package, _))
190 if package != crate::ENTRY_PACKAGE_ID && !is_internal_package_id(package) =>
191 {
192 Cow::Borrowed(id.as_str())
193 }
194 _ => Cow::Borrowed(id.last_segment()),
195 }
196}
197
198pub fn type_display_name(id: &Symbol) -> String {
199 qualified_name(id, Qualifier::Package).into_owned()
200}
201
202fn go_package_qualified_name(path: &str, leaf: &str) -> Option<String> {
203 let package_path = path.strip_suffix(leaf)?.strip_suffix('.')?;
204 let package = go_import_default_name(package_path);
205 let is_identifier = package
206 .chars()
207 .next()
208 .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
209 && package
210 .chars()
211 .all(|c| c.is_ascii_alphanumeric() || c == '_');
212 is_identifier.then(|| format!("{package}.{leaf}"))
213}
214
215impl fmt::Display for Type {
216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217 let (types, _generics) = Self::remove_vars(&[self]);
218 write!(f, "{}", types[0].stringify())
219 }
220}
221
222pub fn annotation_to_string(ann: &Annotation) -> String {
223 match ann {
224 Annotation::Constructor {
225 name,
226 params,
227 writable,
228 ..
229 } => {
230 let rendered = if params.is_empty() {
231 name.to_string()
232 } else {
233 format!(
234 "{}<{}>",
235 name,
236 params
237 .iter()
238 .map(annotation_to_string)
239 .collect::<Vec<_>>()
240 .join(", ")
241 )
242 };
243 if *writable {
244 format!("mut {}", rendered)
245 } else {
246 rendered
247 }
248 }
249 Annotation::Function {
250 params,
251 return_type,
252 ..
253 } => {
254 let params_str = params
255 .iter()
256 .map(annotation_to_string)
257 .collect::<Vec<_>>()
258 .join(", ");
259 if matches!(return_type.as_ref(), Annotation::Unknown) {
260 return format!("fn({})", params_str);
261 }
262 let ret = annotation_to_string(return_type);
263 if ret == "Unit" || ret == "()" {
264 format!("fn({})", params_str)
265 } else {
266 format!("fn({}) -> {}", params_str, ret)
267 }
268 }
269 Annotation::Tuple { elements, .. } => {
270 let inner = elements
271 .iter()
272 .map(annotation_to_string)
273 .collect::<Vec<_>>()
274 .join(", ");
275 format!("({})", inner)
276 }
277 Annotation::Constant { value, text, .. } => {
278 text.clone().unwrap_or_else(|| value.to_string())
279 }
280 Annotation::Unknown => "Unknown".to_string(),
281 Annotation::Opaque { .. } => String::new(),
282 }
283}
284
285#[cfg(test)]
286mod tests {
287 use super::go_package_qualified_name;
288
289 #[test]
290 fn a_go_type_takes_the_name_of_an_unaliased_import() {
291 assert_eq!(
292 go_package_qualified_name("net/http.Request", "Request").as_deref(),
293 Some("http.Request")
294 );
295 assert_eq!(
296 go_package_qualified_name("github.com/jackc/pgx/v5.Conn", "Conn").as_deref(),
297 Some("pgx.Conn")
298 );
299 }
300
301 #[test]
302 fn a_package_name_that_is_not_an_identifier_keeps_the_path() {
303 assert_eq!(
304 go_package_qualified_name("gopkg.in/yaml.v3.Node", "Node"),
305 None
306 );
307 assert_eq!(
308 go_package_qualified_name("github.com/google/go-github.Client", "Client"),
309 None
310 );
311 }
312}