1use std::fmt;
13use std::sync::Arc;
14
15use crate::module::{ModulePath, Tree};
16use crate::nested::{Fold, Nested};
17use crate::shape::{EnumShape, RecordShape};
18
19#[derive(Debug)]
27pub enum Type {
28 Int,
30 Decimal,
32 Bool,
34 Text,
36 Bytes,
38 Duration,
40 Instant,
42 Unit,
44 Never,
46 Json,
48 List(Box<Type>),
50 Set(Box<Type>),
52 Dict(Box<Type>, Box<Type>),
54 Option(Box<Type>),
56 Tuple(Vec<Type>),
58 Named(DeclId, Vec<Type>),
60 Param(u32),
63 Task(Box<Type>),
66 Function {
68 params: Vec<Type>,
70 result: Box<Type>,
72 },
73 NotData,
75}
76
77impl Type {
78 pub fn args(&self) -> &[Type] {
81 if let Type::Named(_, args) = self {
82 args
83 } else {
84 &[]
85 }
86 }
87
88 pub fn list(item: Type) -> Type {
90 Type::List(Box::new(item))
91 }
92
93 pub fn set(item: Type) -> Type {
95 Type::Set(Box::new(item))
96 }
97
98 pub fn dict(key: Type, value: Type) -> Type {
100 Type::Dict(Box::new(key), Box::new(value))
101 }
102
103 pub fn option(item: Type) -> Type {
105 Type::Option(Box::new(item))
106 }
107
108 #[must_use]
111 pub fn subst(&self, args: &[Type]) -> Type {
112 self.fold(&mut Substitution(args))
113 }
114
115 #[must_use]
119 pub fn map_parts(&self, mut part: impl FnMut(&Type) -> Type) -> Type {
120 match self {
121 Type::List(item) => Type::List(Box::new(part(item))),
122 Type::Set(item) => Type::Set(Box::new(part(item))),
123 Type::Option(item) => Type::Option(Box::new(part(item))),
124 Type::Task(item) => Type::Task(Box::new(part(item))),
125 Type::Dict(key, value) => {
126 let key = Box::new(part(key));
127 Type::Dict(key, Box::new(part(value)))
128 }
129 Type::Tuple(parts) => Type::Tuple(parts.iter().map(part).collect()),
130 Type::Named(decl, args) => Type::Named(*decl, args.iter().map(part).collect()),
131 Type::Function { params, result } => {
132 let params = params.iter().map(&mut part).collect();
133 Type::Function {
134 params,
135 result: Box::new(part(result)),
136 }
137 }
138 Type::Int => Type::Int,
139 Type::Decimal => Type::Decimal,
140 Type::Bool => Type::Bool,
141 Type::Text => Type::Text,
142 Type::Bytes => Type::Bytes,
143 Type::Duration => Type::Duration,
144 Type::Instant => Type::Instant,
145 Type::Unit => Type::Unit,
146 Type::Never => Type::Never,
147 Type::Json => Type::Json,
148 Type::Param(index) => Type::Param(*index),
149 Type::NotData => Type::NotData,
150 }
151 }
152
153 fn same_node(&self, other: &Type) -> bool {
156 match (self, other) {
157 (Type::Named(a, xs), Type::Named(b, ys)) => a == b && xs.len() == ys.len(),
158 (Type::Tuple(xs), Type::Tuple(ys))
159 | (Type::Function { params: xs, .. }, Type::Function { params: ys, .. }) => {
160 xs.len() == ys.len()
161 }
162 (Type::Param(a), Type::Param(b)) => a == b,
163 _ => std::mem::discriminant(self) == std::mem::discriminant(other),
164 }
165 }
166}
167
168impl Nested for Type {
169 const LEAF: Type = Type::NotData;
170
171 fn parts(&self) -> impl DoubleEndedIterator<Item = &Type> {
175 let (list, boxed): (&[Type], [Option<&Type>; 2]) = match self {
176 Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
177 (&[], [Some(item), None])
178 }
179 Type::Dict(key, value) => (&[], [Some(key), Some(value)]),
180 Type::Tuple(parts) | Type::Named(_, parts) => (parts, [None, None]),
181 Type::Function { params, result } => (params, [Some(result), None]),
182 Type::Int
183 | Type::Decimal
184 | Type::Bool
185 | Type::Text
186 | Type::Bytes
187 | Type::Duration
188 | Type::Instant
189 | Type::Unit
190 | Type::Never
191 | Type::Json
192 | Type::Param(_)
193 | Type::NotData => (&[], [None, None]),
194 };
195 list.iter().chain(boxed.into_iter().flatten())
196 }
197
198 fn parts_mut(&mut self) -> impl Iterator<Item = &mut Type> {
200 let (list, boxed): (&mut [Type], [Option<&mut Box<Type>>; 2]) = match self {
201 Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
202 (&mut [], [Some(item), None])
203 }
204 Type::Dict(key, value) => (&mut [], [Some(key), Some(value)]),
205 Type::Tuple(parts) | Type::Named(_, parts) => (parts, [None, None]),
206 Type::Function { params, result } => (params, [Some(result), None]),
207 Type::Int
208 | Type::Decimal
209 | Type::Bool
210 | Type::Text
211 | Type::Bytes
212 | Type::Duration
213 | Type::Instant
214 | Type::Unit
215 | Type::Never
216 | Type::Json
217 | Type::Param(_)
218 | Type::NotData => (&mut [], [None, None]),
219 };
220 list.iter_mut()
221 .chain(boxed.into_iter().flatten().map(|part| &mut **part))
222 }
223}
224
225struct Substitution<'a>(&'a [Type]);
227
228impl Fold<Type> for Substitution<'_> {
229 type Made = Type;
230
231 fn open(&mut self, ty: &Type) -> Option<Type> {
232 let Type::Param(index) = ty else {
233 return None;
234 };
235 Some(self.0.get(crate::index(*index)).unwrap_or(ty).clone())
236 }
237
238 fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Type) -> Type {
239 ty.map_parts(|ty| part(self, ty))
240 }
241}
242
243struct Cloning;
245
246impl Fold<Type> for Cloning {
247 type Made = Type;
248
249 fn open(&mut self, _: &Type) -> Option<Type> {
250 None
251 }
252
253 fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Type) -> Type {
254 ty.map_parts(|ty| part(self, ty))
255 }
256}
257
258impl Clone for Type {
259 fn clone(&self) -> Type {
260 self.fold(&mut Cloning)
261 }
262}
263
264impl PartialEq for Type {
267 fn eq(&self, other: &Type) -> bool {
268 self.same_tree(other, Type::same_node)
269 }
270}
271
272impl Eq for Type {}
273
274impl std::hash::Hash for Type {
277 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
278 self.fold(&mut Hashing(state));
279 }
280}
281
282struct Hashing<'h, H>(&'h mut H);
284
285impl<H: std::hash::Hasher> Fold<Type> for Hashing<'_, H> {
286 type Made = ();
287
288 fn open(&mut self, ty: &Type) -> Option<()> {
289 use std::hash::Hash as _;
290 std::mem::discriminant(ty).hash(self.0);
291 if let Type::Named(DeclId(number), _) | Type::Param(number) = ty {
292 number.hash(self.0);
293 }
294 ty.parts().next().is_none().then_some(())
295 }
296
297 fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type)) {
298 for ty in ty.parts() {
299 part(self, ty);
300 }
301 }
302}
303
304impl Drop for Type {
308 fn drop(&mut self) {
309 self.free_parts();
310 }
311}
312
313#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
315pub struct DeclId(pub u32);
316
317#[derive(Clone, Debug)]
326pub struct Identity {
327 pub origin: ModulePath,
329 pub version: Option<String>,
332 pub name: String,
334}
335
336impl Identity {
337 pub fn shown(&self) -> String {
340 let versions = match self.origin.tree() {
341 Tree::Std => Versions::Shown,
342 Tree::Repository(_) | Tree::Local => Versions::Hidden,
343 };
344 self.written(versions)
345 }
346
347 pub fn written(&self, versions: Versions) -> String {
349 let version = match versions {
350 Versions::Shown => self.version.as_deref(),
351 Versions::Hidden => None,
352 };
353 let module = self.origin.written(version);
354 if module.is_empty() {
355 self.name.clone()
356 } else {
357 format!("{module}.{}", self.name)
358 }
359 }
360}
361
362impl PartialEq for Identity {
363 fn eq(&self, other: &Self) -> bool {
364 self.written(Versions::Shown) == other.written(Versions::Shown)
365 }
366}
367
368impl Eq for Identity {}
369
370impl std::hash::Hash for Identity {
371 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
372 self.written(Versions::Shown).hash(state);
373 }
374}
375
376impl fmt::Display for Identity {
377 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378 f.write_str(&self.written(Versions::Shown))
379 }
380}
381
382#[derive(Clone, Debug)]
384pub struct Decl {
385 pub lexical_ordinal: u32,
387 pub identity: Identity,
389 pub doc: Option<String>,
391 pub members: Vec<MemberDoc>,
395 pub params: Vec<String>,
397 pub opaque: bool,
399 pub body: Body,
401}
402
403#[derive(Clone, Default, PartialEq, Eq, Debug)]
405pub struct MemberDoc {
406 pub doc: Option<String>,
408 pub fields: Vec<Option<String>>,
411}
412
413#[derive(Clone, Debug)]
415pub enum Body {
416 Record(Arc<RecordShape>, Vec<Type>),
418 Enum(Arc<EnumShape>, Vec<Vec<Type>>),
421 Newtype(Type),
425 Host,
427 NonData,
429}
430
431#[derive(Clone, Copy, PartialEq, Eq, Debug)]
433pub enum Versions {
434 Shown,
436 Hidden,
438}