summaryrefslogtreecommitdiff
path: root/src/chomp/mod.rs
blob: 1e307380885ab17b98a395752632813ff9a3bfba (plain)
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
use std::{fmt, hash};

use proc_macro2::{Ident, Span};
use syn::ext::IdentExt;

pub mod ast;
pub mod check;
pub mod context;
pub mod error;
pub mod set;
pub mod typed;
pub mod visit;

#[derive(Clone, Debug)]
pub enum Name {
    Spanned(Ident),
    Spanless(String),
}

impl Name {
    pub fn span(&self) -> Option<Span> {
        match self {
            Self::Spanned(i) => Some(i.span()),
            Self::Spanless(_) => None,
        }
    }

    pub fn as_ident(self, span: Span) -> Ident {
        match self {
            Self::Spanned(i) => i,
            Self::Spanless(s) => Ident::new(&s, span),
        }
    }
}

impl PartialEq for Name {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Spanned(me), Self::Spanned(them)) => me == them,
            (Self::Spanned(me), Self::Spanless(them)) => me.unraw() == them,
            (Self::Spanless(me), Self::Spanned(them)) => them.unraw() == me,
            (Self::Spanless(me), Self::Spanless(them)) => me == them,
        }
    }
}

impl<T: AsRef<str>> PartialEq<T> for Name {
    fn eq(&self, other: &T) -> bool {
        match self {
            Name::Spanned(me) => me.unraw() == other,
            Name::Spanless(me) => me == other.as_ref(),
        }
    }
}

impl Eq for Name {}

impl hash::Hash for Name {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        match self {
            Self::Spanned(i) => i.unraw().to_string().hash(state),
            Self::Spanless(s) => s.hash(state),
        }
    }
}

impl fmt::Display for Name {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Name::Spanned(i) => i.fmt(f),
            Name::Spanless(s) => s.fmt(f),
        }
    }
}

impl From<Ident> for Name {
    fn from(ident: Ident) -> Self {
        Self::Spanned(ident)
    }
}

impl From<String> for Name {
    fn from(string: String) -> Self {
        Self::Spanless(string)
    }
}