Skip to main content

lisette_syntax/
display.rs

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