Skip to main content

lisette_syntax/
display.rs

1use std::fmt;
2
3use crate::ast::Annotation;
4use crate::program::is_internal_package_id;
5use crate::types::SimpleKind;
6use crate::types::{GO_IMPORT_PREFIX, Symbol, Type};
7
8#[derive(Clone, Copy, PartialEq, Eq)]
9enum Qualifier {
10    Package,
11    Path,
12}
13
14impl Type {
15    pub fn stringify(&self) -> String {
16        self.stringify_as(Qualifier::Package)
17    }
18
19    pub fn stringify_pair(first: &Self, second: &Self) -> (String, String) {
20        let (named, _) = Self::remove_vars(&[first, second]);
21        let (first, second) = (&named[0], &named[1]);
22
23        let (short_first, short_second) = (first.stringify(), second.stringify());
24        if short_first != short_second {
25            return (short_first, short_second);
26        }
27
28        let wide_first = first.stringify_as(Qualifier::Path);
29        let wide_second = second.stringify_as(Qualifier::Path);
30        if wide_first == wide_second {
31            return (short_first, short_second);
32        }
33
34        (wide_first, wide_second)
35    }
36
37    fn stringify_as(&self, qualifier: Qualifier) -> String {
38        let body = self.stringify_body(qualifier);
39        if self.is_writable() {
40            format!("mut {}", body)
41        } else {
42            body
43        }
44    }
45
46    fn stringify_body(&self, qualifier: Qualifier) -> String {
47        match self {
48            Type::Nominal {
49                id, params: args, ..
50            } => {
51                let args_formatted = args
52                    .iter()
53                    .map(|a| a.stringify_as(qualifier))
54                    .collect::<Vec<_>>()
55                    .join(", ");
56
57                let leaf = id.last_segment();
58
59                if !id.as_str().starts_with(GO_IMPORT_PREFIX) {
60                    if leaf == "Unit" {
61                        return "()".to_string();
62                    }
63
64                    if leaf == "bool" {
65                        return "bool".to_string();
66                    }
67
68                    if leaf.starts_with("Tuple") {
69                        return format!("({})", args_formatted);
70                    }
71
72                    if leaf == "Ref" {
73                        return format!("Ref<{}>", args_formatted);
74                    }
75                }
76
77                let name = qualified_name(id, qualifier);
78
79                if args.is_empty() {
80                    return name.to_string();
81                }
82
83                format!("{}<{}>", name, args_formatted)
84            }
85
86            Type::Var { id, hint } => match hint {
87                Some(name) => format!("?{}", name),
88                None => format!("?{}", id.index()),
89            },
90
91            Type::Uninferred => "?uninferred".to_string(),
92
93            Type::Ignored => "?ignored".to_string(),
94
95            Type::Function(f) => {
96                let args_formatted = f
97                    .params
98                    .iter()
99                    .map(|param| param.ty.stringify_as(qualifier))
100                    .collect::<Vec<_>>()
101                    .join(", ");
102
103                let ret_formatted = f.return_type.stringify_as(qualifier);
104
105                format!("fn ({}) -> {}", args_formatted, ret_formatted)
106            }
107
108            Type::Forall { .. } => {
109                unreachable!("Forall types are always instantiated before display")
110            }
111
112            Type::Parameter(name) => name.to_string(),
113
114            Type::Never => "Never".to_string(),
115
116            Type::Tuple(elements) => {
117                let formatted = elements
118                    .iter()
119                    .map(|e| e.stringify_as(qualifier))
120                    .collect::<Vec<_>>()
121                    .join(", ");
122                format!("({})", formatted)
123            }
124
125            Type::Array { length, element } => {
126                format!("Array<{}, {}>", element.stringify_as(qualifier), length)
127            }
128
129            Type::Error => "<error>".to_string(),
130
131            Type::ImportNamespace(package_id) if package_id.as_str() == crate::ENTRY_PACKAGE_ID => {
132                crate::ROOT_IMPORT.to_string()
133            }
134
135            Type::ImportNamespace(package_id) => {
136                let path = package_id.strip_prefix("go:").unwrap_or(package_id);
137                path.rsplit('/').next().unwrap_or(package_id).to_string()
138            }
139
140            Type::ReceiverPlaceholder => "self".to_string(),
141
142            Type::Simple(kind) => match kind {
143                SimpleKind::Unit => "()".to_string(),
144                _ => kind.leaf_name().to_string(),
145            },
146
147            Type::Compound { kind, args, .. } => {
148                let args_formatted = args
149                    .iter()
150                    .map(|a| a.stringify_as(qualifier))
151                    .collect::<Vec<_>>()
152                    .join(", ");
153                if args.is_empty() {
154                    kind.leaf_name().to_string()
155                } else {
156                    format!("{}<{}>", kind.leaf_name(), args_formatted)
157                }
158            }
159        }
160    }
161}
162
163fn qualified_name(id: &Symbol, qualifier: Qualifier) -> &str {
164    if let Some(path) = id.as_str().strip_prefix(GO_IMPORT_PREFIX) {
165        return path;
166    }
167
168    if qualifier == Qualifier::Package {
169        return id.last_segment();
170    }
171
172    match id.as_str().split_once('.') {
173        Some((package, _))
174            if package != crate::ENTRY_PACKAGE_ID && !is_internal_package_id(package) =>
175        {
176            id.as_str()
177        }
178        _ => id.last_segment(),
179    }
180}
181
182impl fmt::Display for Type {
183    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184        let (types, _generics) = Self::remove_vars(&[self]);
185        write!(f, "{}", types[0].stringify())
186    }
187}
188
189pub fn annotation_to_string(ann: &Annotation) -> String {
190    match ann {
191        Annotation::Constructor {
192            name,
193            params,
194            writable,
195            ..
196        } => {
197            let rendered = if params.is_empty() {
198                name.to_string()
199            } else {
200                format!(
201                    "{}<{}>",
202                    name,
203                    params
204                        .iter()
205                        .map(annotation_to_string)
206                        .collect::<Vec<_>>()
207                        .join(", ")
208                )
209            };
210            if *writable {
211                format!("mut {}", rendered)
212            } else {
213                rendered
214            }
215        }
216        Annotation::Function {
217            params,
218            return_type,
219            ..
220        } => {
221            let params_str = params
222                .iter()
223                .map(annotation_to_string)
224                .collect::<Vec<_>>()
225                .join(", ");
226            if matches!(return_type.as_ref(), Annotation::Unknown) {
227                return format!("fn({})", params_str);
228            }
229            let ret = annotation_to_string(return_type);
230            if ret == "Unit" || ret == "()" {
231                format!("fn({})", params_str)
232            } else {
233                format!("fn({}) -> {}", params_str, ret)
234            }
235        }
236        Annotation::Tuple { elements, .. } => {
237            let inner = elements
238                .iter()
239                .map(annotation_to_string)
240                .collect::<Vec<_>>()
241                .join(", ");
242            format!("({})", inner)
243        }
244        Annotation::Constant { value, text, .. } => {
245            text.clone().unwrap_or_else(|| value.to_string())
246        }
247        Annotation::Unknown => "Unknown".to_string(),
248        Annotation::Opaque { .. } => String::new(),
249    }
250}