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