spade-typeinference 0.16.0

Helper crate for https://spade-lang.org/
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
use std::collections::BTreeMap;

use itertools::Itertools;
type HashMap<K, V> =
    imbl::GenericHashMap<K, V, rustc_hash::FxBuildHasher, imbl::shared_ptr::DefaultSharedPtr>;

use num::BigInt;
use serde::{Deserialize, Serialize};
use spade_common::{id_tracker::ExprID, location_info::Loc, name::NameID};
use spade_types::{meta_types::MetaType, KnownType};

use crate::{
    traits::{TraitList, TraitReq},
    HasType, TypeState,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct TypeVarID {
    pub inner: usize,
    /// Key from the TypeState from which this var originates. See the `key` field
    /// of the type state for details
    pub type_state_key: u64,
}

impl TypeVarID {
    pub fn resolve(self, state: &TypeState) -> TypeVar {
        assert!(
            state.owned.keys.contains(&self.type_state_key),
            "Type var key mismatch. Type states are being mixed incorrectly. Type state has {:?}, var has {}", state.owned.keys, self.type_state_key
        );
        // In case our ID is stale, we'll need to look up the final ID
        let final_id = self.get_type(state);
        state
            .shared
            .read_type_vars(|type_vars| type_vars.get(final_id.inner).unwrap().clone())
    }

    pub fn replace_inside(
        self,
        from: TypeVarID,
        to: TypeVarID,
        state: &mut TypeState,
    ) -> TypeVarID {
        if self.get_type(state) == from.get_type(state) {
            to
        } else {
            let mut new = self.resolve(state).clone();
            match &mut new {
                TypeVar::Known(_, _known_type, params) => {
                    params
                        .iter_mut()
                        .for_each(|var| *var = var.replace_inside(from, to, state));
                }
                TypeVar::Unknown(_, _, trait_list, _) => {
                    trait_list.inner.iter_mut().for_each(|var| {
                        let TraitReq {
                            name: _,
                            type_params,
                        } = &mut var.inner;

                        type_params
                            .iter_mut()
                            .for_each(|t| *t = t.replace_inside(from, to, state));
                    })
                }
            };

            // NOTE: For performance we could consider not doing replacement if none
            // of the inner types changed. For now, we only use this in diagnostics,
            // so even for performance, it won't make a difference
            new.insert(state)
        }
    }

    pub fn display(self, type_state: &TypeState) -> String {
        self.display_with_meta(false, type_state)
    }

    pub fn display_with_meta(self, meta: bool, type_state: &TypeState) -> String {
        match self.resolve(type_state) {
            TypeVar::Known(_, KnownType::Error, _) => "{unknown}".to_string(),
            TypeVar::Known(_, KnownType::Named(t), params) => {
                let generics = if params.is_empty() {
                    String::new()
                } else {
                    format!(
                        "<{}>",
                        params
                            .iter()
                            .map(|p| format!("{}", p.display_with_meta(meta, type_state)))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                };
                format!("{}{}", t, generics)
            }
            TypeVar::Known(_, KnownType::Integer(inner), _) => {
                format!("{inner}")
            }
            TypeVar::Known(_, KnownType::Bool(inner), _) => {
                format!("{inner}")
            }
            TypeVar::Known(_, KnownType::String(inner), _) => {
                format!("{inner:?}")
            }
            TypeVar::Known(_, KnownType::Tuple, params) => {
                format!(
                    "({})",
                    params
                        .iter()
                        .map(|t| format!("{}", t.display_with_meta(meta, type_state)))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
            TypeVar::Known(_, KnownType::Array, params) => {
                format!(
                    "[{}; {}]",
                    params[0].display_with_meta(meta, type_state),
                    params[1].display_with_meta(meta, type_state)
                )
            }
            TypeVar::Known(_, KnownType::Wire, params) => {
                format!("&{}", params[0].display_with_meta(meta, type_state))
            }
            TypeVar::Known(_, KnownType::Inverted, params) => {
                format!("inv {}", params[0].display_with_meta(meta, type_state))
            }
            TypeVar::Unknown(_, _, traits, meta_type) => match meta_type {
                MetaType::Type => {
                    if !traits.inner.is_empty() {
                        traits
                            .inner
                            .iter()
                            .map(|t| t.display_with_meta(meta, type_state))
                            .join(" + ")
                    } else {
                        "_".to_string()
                    }
                }
                _ => {
                    if meta {
                        format!("{}", meta_type)
                    } else {
                        format!("_")
                    }
                }
            },
        }
    }

    pub fn debug_resolve(self, state: &TypeState) -> TypeVarString {
        match self.resolve(state) {
            TypeVar::Known(_, base, params) => {
                let params = if params.is_empty() {
                    "".to_string()
                } else {
                    format!(
                        "<{}>",
                        params.iter().map(|t| t.debug_resolve(state).0).join(", ")
                    )
                };
                let base = match base {
                    KnownType::Named(name_id) => format!("{name_id}"),
                    KnownType::Integer(big_int) => format!("{big_int}"),
                    KnownType::Bool(val) => format!("{val}"),
                    KnownType::String(val) => format!("{val:?}"),
                    KnownType::Tuple => format!("Tuple"),
                    KnownType::Array => format!("Array"),
                    KnownType::Wire => format!("&"),
                    KnownType::Inverted => format!("inv &"),
                    KnownType::Error => format!("{{error}}"),
                };
                TypeVarString(format!("{base}{params}"), self)
            }
            TypeVar::Unknown(_, id, traits, _meta_type) => {
                let traits = if traits.inner.is_empty() {
                    "".to_string()
                } else {
                    format!(
                        "({})",
                        traits
                            .inner
                            .iter()
                            .map(|t| t.debug_display(state))
                            .join(" + ")
                    )
                };
                TypeVarString(format!("t{id}{traits}"), self)
            }
        }
    }
}

/// A type which which should not be resolved directly but can be used to create new
/// copies with unique type var ids
#[derive(Clone, Copy, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct TemplateTypeVarID {
    inner: TypeVarID,
}

impl TemplateTypeVarID {
    pub fn new(inner: TypeVarID) -> Self {
        Self { inner }
    }

    pub fn make_copy(&self, state: &mut TypeState) -> TypeVarID {
        self.make_copy_with_mapping(state, &mut BTreeMap::new())
    }

    pub fn make_copy_with_mapping(
        &self,
        state: &mut TypeState,
        mapped: &mut BTreeMap<TemplateTypeVarID, TypeVarID>,
    ) -> TypeVarID {
        if let Some(prev) = mapped.get(self) {
            return *prev;
        }

        let new = match self.inner.resolve(state).clone() {
            TypeVar::Known(loc, base, params) => TypeVar::Known(
                loc,
                base,
                params
                    .into_iter()
                    .map(|p| TemplateTypeVarID { inner: p }.make_copy_with_mapping(state, mapped))
                    .collect(),
            ),
            TypeVar::Unknown(loc, id, TraitList { inner: tl }, meta_type) => TypeVar::Unknown(
                loc,
                id,
                TraitList {
                    inner: tl
                        .into_iter()
                        .map(|loc| {
                            loc.map(|req| TraitReq {
                                name: req.name,
                                type_params: req
                                    .type_params
                                    .into_iter()
                                    .map(|p| {
                                        TemplateTypeVarID { inner: p }
                                            .make_copy_with_mapping(state, mapped)
                                    })
                                    .collect(),
                            })
                        })
                        .collect(),
                },
                meta_type,
            ),
        };
        let result = state.add_type_var(new);
        mapped.insert(*self, result);
        result
    }
}

pub type TypeEquations = HashMap<TypedExpression, TypeVarID>;

/// A frozen TypeVar that can be printed for debugging purposes
#[derive(Debug, Clone)]
pub struct TypeVarString(pub String, pub TypeVarID);

impl std::fmt::Display for TypeVarString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A type variable represents the type of something in the program. It is mapped
/// to expressions by type equations in the TypeState.
///
/// When TypeVars are passed externally into TypeState, they must be checked for replacement,
/// as the type inference process might have refined them.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Debug)]
pub enum TypeVar {
    /// The base type is known and has a list of parameters
    Known(Loc<()>, KnownType, Vec<TypeVarID>),
    /// The type is unknown, but must satisfy the specified traits. When the generic substitution
    /// is done, the TypeVars will be carried over to the KnownType type vars
    Unknown(Loc<()>, u64, TraitList, MetaType),
}

impl TypeVar {
    pub fn into_known(&self, type_state: &TypeState) -> Option<KnownTypeVar> {
        match self {
            TypeVar::Known(loc, base, params) => Some(KnownTypeVar(
                loc.clone(),
                base.clone(),
                params
                    .iter()
                    .map(|t| t.resolve(type_state).into_known(type_state))
                    .collect::<Option<_>>()?,
            )),
            TypeVar::Unknown(_, _, _, _) => None,
        }
    }

    pub fn insert(self, into: &mut TypeState) -> TypeVarID {
        into.add_type_var(self)
    }

    pub fn array(loc: Loc<()>, inner: TypeVarID, size: TypeVarID) -> Self {
        TypeVar::Known(loc, KnownType::Array, vec![inner, size])
    }

    pub fn tuple(loc: Loc<()>, inner: Vec<TypeVarID>) -> Self {
        TypeVar::Known(loc, KnownType::Tuple, inner)
    }

    pub fn unit(loc: Loc<()>) -> Self {
        TypeVar::Known(loc, KnownType::Tuple, Vec::new())
    }

    pub fn wire(loc: Loc<()>, inner: TypeVarID) -> Self {
        TypeVar::Known(loc, KnownType::Wire, vec![inner])
    }

    pub fn backward(loc: Loc<()>, inner: TypeVarID, type_state: &mut TypeState) -> Self {
        TypeVar::Known(
            loc,
            KnownType::Inverted,
            vec![type_state.add_type_var(TypeVar::Known(loc, KnownType::Wire, vec![inner]))],
        )
    }

    pub fn inverted(loc: Loc<()>, inner: TypeVarID) -> Self {
        TypeVar::Known(loc, KnownType::Inverted, vec![inner])
    }

    pub fn expect_known<T, U, K, O>(&self, on_known: K, on_unknown: U) -> T
    where
        U: FnOnce() -> T,
        K: FnOnce(&KnownType, &[TypeVarID]) -> T,
    {
        match self {
            TypeVar::Unknown(_, _, _, _) => on_unknown(),
            TypeVar::Known(_, k, v) => on_known(k, v),
        }
    }

    pub fn expect_named<T, E, U, K, O>(
        &self,
        on_named: K,
        on_unknown: U,
        on_other: O,
        on_error: E,
    ) -> T
    where
        U: FnOnce() -> T,
        K: FnOnce(&NameID, &[TypeVarID]) -> T,
        E: FnOnce() -> T,
        O: FnOnce(&TypeVar) -> T,
    {
        match self {
            TypeVar::Unknown(_, _, _, _) => on_unknown(),
            TypeVar::Known(_, KnownType::Named(name), params) => on_named(name, params),
            TypeVar::Known(_, KnownType::Error, _) => on_error(),
            other => on_other(other),
        }
    }

    /// Expect a named type, or TypeVar::Inverted(named), or a recursive inversion.
    /// inverted_now is stateful and used to track if we are currently in an
    /// inverted context.
    pub fn resolve_named_or_inverted(
        &self,
        inverted_now: bool,
        type_state: &TypeState,
    ) -> ResolvedNamedOrInverted {
        match self {
            TypeVar::Unknown(_, _, _, _) => ResolvedNamedOrInverted::Unknown,
            TypeVar::Known(_, KnownType::Inverted, params) => {
                if params.len() != 1 {
                    panic!("Found wire with {} params", params.len())
                }
                params[0]
                    .resolve(type_state)
                    .resolve_named_or_inverted(!inverted_now, type_state)
            }
            TypeVar::Known(_, KnownType::Named(name), params) => {
                ResolvedNamedOrInverted::Named(inverted_now, name.clone(), params.clone())
            }
            _ => ResolvedNamedOrInverted::Other,
        }
    }

    pub fn expect_specific_named<T, U, K, O>(
        &self,
        name: NameID,
        on_correct: K,
        on_unknown: U,
        on_other: O,
    ) -> T
    where
        U: FnOnce() -> T,
        K: FnOnce(&[TypeVarID]) -> T,
        O: FnOnce(&TypeVar) -> T,
    {
        match self {
            TypeVar::Unknown(_, _, _, _) => on_unknown(),
            TypeVar::Known(_, k, v) if k == &KnownType::Named(name) => on_correct(v),
            other => on_other(other),
        }
    }

    /// Assumes that this type is KnownType::Integer(size) and calls on_integer then. Otherwise
    /// calls on_unknown or on_other depending on the type. If the integer is given type params,
    /// panics
    pub fn expect_integer<T, E, U, K, O>(
        &self,
        on_integer: K,
        on_unknown: U,
        on_other: O,
        on_error: E,
    ) -> T
    where
        U: FnOnce() -> T,
        E: FnOnce() -> T,
        K: FnOnce(BigInt) -> T,
        O: FnOnce(&TypeVar) -> T,
    {
        match self {
            TypeVar::Known(_, KnownType::Integer(size), params) => {
                assert!(params.is_empty());
                on_integer(size.clone())
            }
            TypeVar::Known(_, KnownType::Error, _) => on_error(),
            TypeVar::Unknown(_, _, _, _) => on_unknown(),
            other => on_other(other),
        }
    }

    /// Assumes that this type is KnownType::String(val) and calls on_string then. Otherwise
    /// calls on_unknown or on_other depending on the type. If the integer is given type params,
    /// panics
    pub fn expect_string<T, E, U, K, O>(
        &self,
        on_string: K,
        on_unknown: U,
        on_other: O,
        on_error: E,
    ) -> T
    where
        U: FnOnce() -> T,
        E: FnOnce() -> T,
        K: FnOnce(String) -> T,
        O: FnOnce(&TypeVar) -> T,
    {
        match self {
            TypeVar::Known(_, KnownType::String(val), params) => {
                assert!(params.is_empty());
                on_string(val.clone())
            }
            TypeVar::Known(_, KnownType::Error, _) => on_error(),
            TypeVar::Unknown(_, _, _, _) => on_unknown(),
            other => on_other(other),
        }
    }

    pub fn display(&self, type_state: &TypeState) -> String {
        self.display_with_meta(false, type_state)
    }

    pub fn display_with_meta(&self, display_meta: bool, type_state: &TypeState) -> String {
        match self {
            TypeVar::Known(_, KnownType::Error, _) => "{unknown}".to_string(),
            TypeVar::Known(_, KnownType::Named(t), params) => {
                let generics = if params.is_empty() {
                    String::new()
                } else {
                    format!(
                        "<{}>",
                        params
                            .iter()
                            .map(|p| format!("{}", p.display_with_meta(display_meta, type_state)))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                };
                format!("{}{}", t, generics)
            }
            TypeVar::Known(_, KnownType::Integer(inner), _) => {
                format!("{inner}")
            }
            TypeVar::Known(_, KnownType::Bool(inner), _) => {
                format!("{inner}")
            }
            TypeVar::Known(_, KnownType::String(inner), _) => {
                format!("{inner:?}")
            }
            TypeVar::Known(_, KnownType::Tuple, params) => {
                format!(
                    "({})",
                    params
                        .iter()
                        .map(|t| format!("{}", t.display_with_meta(display_meta, type_state)))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
            TypeVar::Known(_, KnownType::Array, params) => {
                format!(
                    "[{}; {}]",
                    params[0].display_with_meta(display_meta, type_state),
                    params[1].display_with_meta(display_meta, type_state)
                )
            }
            TypeVar::Known(_, KnownType::Wire, params) => {
                format!("&{}", params[0].display_with_meta(display_meta, type_state))
            }
            TypeVar::Known(_, KnownType::Inverted, params) => {
                format!(
                    "inv {}",
                    params[0].display_with_meta(display_meta, type_state)
                )
            }
            TypeVar::Unknown(_, _, traits, meta) if traits.inner.is_empty() => {
                if display_meta {
                    format!("{meta}")
                } else {
                    "_".to_string()
                }
            }
            // If we have traits, we know this is a type
            TypeVar::Unknown(_, _, traits, _meta) => {
                format!(
                    "{}",
                    traits
                        .inner
                        .iter()
                        .map(|t| format!("{}", t.display_with_meta(display_meta, type_state)))
                        .join("+"),
                )
            }
        }
    }
}

#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct KnownTypeVar(pub Loc<()>, pub KnownType, pub Vec<KnownTypeVar>);

impl KnownTypeVar {
    pub fn insert(&self, type_state: &mut TypeState) -> TypeVarID {
        let KnownTypeVar(loc, base, params) = self;
        TypeVar::Known(
            loc.clone(),
            base.clone(),
            params.into_iter().map(|p| p.insert(type_state)).collect(),
        )
        .insert(type_state)
    }
}

impl std::fmt::Display for KnownTypeVar {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let KnownTypeVar(_, base, params) = self;

        match base {
            KnownType::Error => {
                write!(f, "{{unknown}}")
            }
            KnownType::Named(name_id) => {
                write!(f, "{name_id}")?;
                if !params.is_empty() {
                    write!(f, "<{}>", params.iter().map(|t| format!("{t}")).join(", "))?;
                }
                Ok(())
            }
            KnownType::Integer(val) => write!(f, "{val}"),
            KnownType::Bool(val) => write!(f, "{val}"),
            KnownType::String(val) => write!(f, "{val:?}"),
            KnownType::Tuple => {
                write!(f, "({})", params.iter().map(|t| format!("{t}")).join(", "))
            }
            KnownType::Array => write!(f, "[{}; {}]", params[0], params[1]),
            KnownType::Wire => write!(f, "&{}", params[0]),
            KnownType::Inverted => write!(f, "inv {}", params[0]),
        }
    }
}

pub enum ResolvedNamedOrInverted {
    Unknown,
    Named(bool, NameID, Vec<TypeVarID>),
    Other,
}

#[derive(Eq, PartialEq, Hash, Debug, Clone, Serialize, Deserialize)]
pub enum TypedExpression {
    Id(ExprID),
    Name(NameID),
}

impl std::fmt::Display for TypedExpression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TypedExpression::Id(i) => {
                write!(f, "%{}", i.0)
            }
            TypedExpression::Name(p) => {
                write!(f, "{}#{}", p, p.0)
            }
        }
    }
}