smol lang
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
use std::ops::Deref;

use crate::lexer::Token;
use beef::lean::Cow;
use chumsky::{
    input::{SpannedInput, Stream},
    prelude::*,
};
use match_deref::match_deref;
pub type Span = SimpleSpan<usize>;
pub type Error<'s> = Rich<'s, Token<'s>, Span>;
pub type Input<'s> = SpannedInput<Token<'s>, SimpleSpan, Stream<crate::lexer::Lexer<'s>>>;

#[derive(Clone)]
pub struct FnDef<'s> {
    pub name: &'s str,
    pub args: Vec<(Type<'s>, Type<'s>)>,
    pub ret: Type<'s>,
    pub block: Option<Vec<Token<'s>>>,
    pub meta: Vec<Meta<'s>>,
}

impl std::fmt::Debug for FnDef<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {:?} -> {:?}", self.name, self.args, self.ret)?;
        if let Some(b) = &self.block {
            write!(f, " {b:?}")?;
        }
        write!(f, " {:?}", self.meta)
    }
}

#[derive(Debug, Clone)]
pub enum Stmt<'s> {
    Fn(FnDef<'s>),
}

#[derive(Debug, Clone)]
pub enum Ast<'s> {
    Module(Vec<Stmt<'s>>),
}

#[derive(Clone)]
pub enum Value<'s> {
    Float(f64),
    Int(u64),
    String(Cow<'s, str>),
    Unit,
}

impl std::fmt::Debug for Value<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Float(x) => write!(f, "{x}f"),
            Self::Int(x) => write!(f, "{x}i"),
            Self::String(x) => write!(f, "\"{x}\""),
            Self::Unit => write!(f, "()"),
        }
    }
}

#[derive(Clone, Debug, Copy)]
pub enum Associativity {
    Left,
    Right,
    None,
}

#[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Fix {
    Pre,
    Post,
    In,
}

#[derive(Clone, Copy)]
pub struct FixMetaData<'s> {
    pub looser_than: Option<Spanned<&'s str>>,
    pub tighter_than: Option<Spanned<&'s str>>,
    pub fixness: Fix,
    pub assoc: Option<Spanned<Associativity>>,
}

impl std::fmt::Debug for FixMetaData<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?} {{", self.fixness)?;
        if let Some(x) = self.assoc {
            write!(f, " assoc {x:?}")?;
        }
        if let Some(x) = self.looser_than {
            write!(f, " looser {x}")?;
        }
        if let Some(x) = self.tighter_than {
            write!(f, " tighter {x}")?;
        }
        write!(f, " }}")
    }
}

#[derive(Clone, Copy)]
pub enum FixMeta<'s> {
    Default(Spanned<Fix>), // function precedence
    Like(Fix, &'s str, Span),
    Data(Spanned<FixMetaData<'s>>),
}

impl<'s> FixMeta<'s> {
    pub fn span(&self) -> Span {
        match self {
            Self::Default(x) => x.span,
            Self::Like(_, _, x) => x,
            Self::Data(x) => x.span,
        }
    }

    pub fn fix(&self) -> Fix {
        match_deref! {
            match self {
                Self::Default(Deref @ x) => *x,
                Self::Like(x,..) => *x,
                Self::Data(Deref @ FixMetaData { fixness, .. }) => *fixness,
            }
        }
    }
}

impl std::fmt::Debug for FixMeta<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Default(x) => write!(f, "{x:?}"),
            Self::Like(x, y, _) => write!(f, "{x:?} {{ like {y} }}"),
            Self::Data(x) => write!(f, "{x:?}"),
        }
    }
}

#[derive(Clone)]
pub enum Meta<'s> {
    Fix(FixMeta<'s>),
    Alias(Vec<&'s str>),
}

impl std::fmt::Debug for Meta<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Fix(fix) => write!(f, "{fix:?}"),
            Self::Alias(what) => write!(f, "alias {what:?}"),
        }
    }
}

#[derive(Clone)]
pub enum Expr<'s> {
    Value(Value<'s>),
    Ident(&'s str),

    Let {
        name: &'s str,
        rhs: Box<Expr<'s>>,
    },
    If {
        cond: Box<Expr<'s>>,
        when: Box<Expr<'s>>,
        or: Box<Expr<'s>>,
    },
    Semicolon(Box<Expr<'s>>, Box<Expr<'s>>),
    Call(&'s str, Vec<Expr<'s>>),
}

impl std::fmt::Debug for Expr<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Value(x) => write!(f, "{x:?}"),
            Self::Ident(x) => write!(f, "{x}"),
            Self::Let { name, rhs } => write!(f, "let {name} = {rhs:?}"),
            Self::If { cond, when, or } => {
                write!(f, "if {cond:?} {{ {when:?} }} else {{ {or:?} }}")
            }
            Self::Semicolon(arg0, arg1) => f.debug_list().entries([arg0, arg1]).finish(),
            Self::Call(arg, x) => f.debug_tuple("callu").field(arg).field(x).finish(),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Spanned<T> {
    pub inner: T,
    pub span: Span,
}

impl<T> Deref for Spanned<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T> Spanned<T> {
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Spanned<U> {
        Spanned {
            inner: f(self.inner),
            span: self.span,
        }
    }

    pub fn dummy(inner: T) -> Spanned<T> {
        Spanned {
            inner,
            span: SimpleSpan::new(0, 0),
        }
    }

    pub fn copys<U>(&self, with: U) -> Spanned<U> {
        Spanned {
            inner: with,
            span: self.span,
        }
    }
}

impl<T> From<(T, Span)> for Spanned<T> {
    fn from((inner, span): (T, Span)) -> Self {
        Self { inner, span }
    }
}

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

#[derive(Clone)]
pub enum Type<'s> {
    Tuple(Box<[Type<'s>]>),
    Path(&'s str),
    Unit,
}

impl std::fmt::Debug for Type<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Tuple(x) => write!(
                f,
                "{}",
                std::iter::once("(".to_string())
                    .chain(x.iter().map(|x| format!("{x:?}")).intersperse(", ".into()),)
                    .chain([")".to_string()])
                    .reduce(|acc, x| acc + &x)
                    .unwrap()
            ),
            Self::Path(x) => write!(f, "{x}"),
            Self::Unit => write!(f, "()"),
        }
    }
}