Skip to main content

lisette_syntax/
display.rs

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