wit_encoder/
ty.rs

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
use std::fmt::{self, Display};

use crate::{
    ident::Ident, Docs, Enum, EnumCase, Field, Flag, Flags, Record, Render, RenderOpts, Resource,
    ResourceFunc, Result_, Tuple, Variant,
};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum Type {
    Bool,
    U8,
    U16,
    U32,
    U64,
    S8,
    S16,
    S32,
    S64,
    F32,
    F64,
    Char,
    String,
    Borrow(Ident),
    Option(Box<Type>),
    Result(Box<Result_>),
    List(Box<Type>),
    Tuple(Tuple),
    Named(Ident),
}

impl Type {
    pub fn borrow(name: impl Into<Ident>) -> Self {
        Type::Borrow(name.into())
    }
    pub fn option(type_: Type) -> Self {
        Type::Option(Box::new(type_))
    }
    pub fn result(result: Result_) -> Self {
        Type::Result(Box::new(result))
    }
    pub fn result_ok(type_: Type) -> Self {
        Type::Result(Box::new(Result_::ok(type_)))
    }
    pub fn result_err(type_: Type) -> Self {
        Type::Result(Box::new(Result_::err(type_)))
    }
    pub fn result_both(ok: Type, err: Type) -> Self {
        Type::Result(Box::new(Result_::both(ok, err)))
    }
    pub fn result_empty() -> Self {
        Type::Result(Box::new(Result_::empty()))
    }
    pub fn list(type_: Type) -> Self {
        Type::List(Box::new(type_))
    }
    pub fn tuple(types: impl IntoIterator<Item = Type>) -> Self {
        Type::Tuple(Tuple {
            types: types.into_iter().collect(),
        })
    }
    pub fn named(name: impl Into<Ident>) -> Self {
        Type::Named(name.into())
    }
}
impl From<Result_> for Type {
    fn from(value: Result_) -> Self {
        Self::result(value)
    }
}
impl From<Tuple> for Type {
    fn from(value: Tuple) -> Self {
        Type::Tuple(value)
    }
}
impl From<Ident> for Type {
    fn from(value: Ident) -> Self {
        Self::named(value)
    }
}

impl Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Type::Bool => write!(f, "bool"),
            Type::U8 => write!(f, "u8"),
            Type::U16 => write!(f, "u16"),
            Type::U32 => write!(f, "u32"),
            Type::U64 => write!(f, "u64"),
            Type::S8 => write!(f, "s8"),
            Type::S16 => write!(f, "s16"),
            Type::S32 => write!(f, "s32"),
            Type::S64 => write!(f, "s64"),
            Type::F32 => write!(f, "f32"),
            Type::F64 => write!(f, "f64"),
            Type::Char => write!(f, "char"),
            Type::String => write!(f, "string"),
            Type::Named(name) => write!(f, "{}", name),
            Type::Borrow(type_) => {
                write!(f, "borrow<{type_}>")
            }
            Type::Option(type_) => {
                write!(f, "option<{type_}>")
            }
            Type::Result(result) => result.fmt(f),
            Type::List(type_) => {
                write!(f, "list<{type_}>")
            }
            Type::Tuple(tuple) => tuple.fmt(f),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub struct VariantCase {
    name: Ident,
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    type_: Option<Type>,
    docs: Option<Docs>,
}

impl VariantCase {
    pub fn empty(name: impl Into<Ident>) -> Self {
        Self {
            name: name.into(),
            type_: None,
            docs: None,
        }
    }

    pub fn value(name: impl Into<Ident>, ty: Type) -> Self {
        Self {
            name: name.into(),
            type_: Some(ty),
            docs: None,
        }
    }

    pub fn set_name(&mut self, name: impl Into<Ident>) {
        self.name = name.into();
    }

    pub fn name(&self) -> &Ident {
        &self.name
    }

    pub fn name_mut(&mut self) -> &mut Ident {
        &mut self.name
    }

    pub fn type_(&self) -> Option<&Type> {
        self.type_.as_ref()
    }

    pub fn type_mut(&mut self) -> &mut Option<Type> {
        &mut self.type_
    }

    pub fn set_docs(&mut self, docs: Option<impl Into<Docs>>) {
        self.docs = docs.map(|d| d.into());
    }

    pub fn docs(&self) -> &Option<Docs> {
        &self.docs
    }
}

impl<N> Into<VariantCase> for (N,)
where
    N: Into<Ident>,
{
    fn into(self) -> VariantCase {
        VariantCase::empty(self.0)
    }
}

impl<N> Into<VariantCase> for (N, Type)
where
    N: Into<Ident>,
{
    fn into(self) -> VariantCase {
        VariantCase::value(self.0, self.1)
    }
}

impl<N, D> Into<VariantCase> for (N, Type, D)
where
    N: Into<Ident>,
    D: Into<Docs>,
{
    fn into(self) -> VariantCase {
        let mut field = VariantCase::value(self.0, self.1);
        field.set_docs(Some(self.2.into()));
        field
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub struct TypeDef {
    name: Ident,
    kind: TypeDefKind,
    docs: Option<Docs>,
}

impl TypeDef {
    pub fn new(name: impl Into<Ident>, kind: TypeDefKind) -> Self {
        TypeDef {
            name: name.into(),
            kind,
            docs: None,
        }
    }

    pub fn record(
        name: impl Into<Ident>,
        fields: impl IntoIterator<Item = impl Into<Field>>,
    ) -> Self {
        TypeDef {
            name: name.into(),
            kind: TypeDefKind::record(fields),
            docs: None,
        }
    }

    pub fn resource(
        name: impl Into<Ident>,
        funcs: impl IntoIterator<Item = impl Into<ResourceFunc>>,
    ) -> Self {
        TypeDef {
            name: name.into(),
            kind: TypeDefKind::resource(funcs),
            docs: None,
        }
    }

    pub fn flags(name: impl Into<Ident>, flags: impl IntoIterator<Item = impl Into<Flag>>) -> Self {
        TypeDef {
            name: name.into(),
            kind: TypeDefKind::flags(flags),
            docs: None,
        }
    }

    pub fn variant(
        name: impl Into<Ident>,
        cases: impl IntoIterator<Item = impl Into<VariantCase>>,
    ) -> Self {
        TypeDef {
            name: name.into(),
            kind: TypeDefKind::variant(cases),
            docs: None,
        }
    }

    pub fn enum_(
        name: impl Into<Ident>,
        cases: impl IntoIterator<Item = impl Into<EnumCase>>,
    ) -> Self {
        TypeDef {
            name: name.into(),
            kind: TypeDefKind::enum_(cases),
            docs: None,
        }
    }

    pub fn type_(name: impl Into<Ident>, type_: Type) -> Self {
        TypeDef {
            name: name.into(),
            kind: TypeDefKind::type_(type_),
            docs: None,
        }
    }

    pub fn name(&self) -> &Ident {
        &self.name
    }

    pub fn name_mut(&mut self) -> &mut Ident {
        &mut self.name
    }

    pub fn kind(&self) -> &TypeDefKind {
        &self.kind
    }

    pub fn kind_mut(&mut self) -> &mut TypeDefKind {
        &mut self.kind
    }

    pub fn set_docs(&mut self, docs: Option<impl Into<Docs>>) {
        self.docs = docs.map(|d| d.into());
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum TypeDefKind {
    Record(Record),
    Resource(Resource),
    Flags(Flags),
    Variant(Variant),
    Enum(Enum),
    Type(Type),
}

impl TypeDefKind {
    pub fn record(fields: impl IntoIterator<Item = impl Into<Field>>) -> Self {
        Self::Record(Record {
            fields: fields.into_iter().map(|c| c.into()).collect(),
        })
    }

    pub fn resource(funcs: impl IntoIterator<Item = impl Into<ResourceFunc>>) -> Self {
        Self::Resource(Resource {
            funcs: funcs.into_iter().map(|f| f.into()).collect(),
        })
    }

    pub fn flags(flags: impl IntoIterator<Item = impl Into<Flag>>) -> Self {
        Self::Flags(Flags {
            flags: flags.into_iter().map(|f| f.into()).collect(),
        })
    }

    pub fn variant(cases: impl IntoIterator<Item = impl Into<VariantCase>>) -> Self {
        Self::Variant(Variant {
            cases: cases.into_iter().map(|c| c.into()).collect(),
        })
    }

    pub fn enum_(cases: impl IntoIterator<Item = impl Into<EnumCase>>) -> Self {
        Self::Enum(Enum {
            cases: cases.into_iter().map(|c| c.into()).collect(),
        })
    }

    pub fn type_(type_: Type) -> Self {
        Self::Type(type_)
    }
}

impl Render for TypeDef {
    fn render(&self, f: &mut fmt::Formatter<'_>, opts: &RenderOpts) -> fmt::Result {
        match &self.kind {
            TypeDefKind::Record(record) => {
                if let Some(docs) = &self.docs {
                    docs.render(f, opts)?;
                }
                write!(f, "{}record {} {{", opts.spaces(), self.name)?;
                for (index, field) in record.fields.iter().enumerate() {
                    if index == 0 {
                        write!(f, "\n")?;
                    }
                    let opts = opts.indent();
                    if let Some(docs) = &field.docs {
                        docs.render(f, &opts)?;
                    }
                    write!(f, "{}{}: {},\n", opts.spaces(), field.name, field.type_)?;
                }
                write!(f, "{}}}\n", opts.spaces())?;
            }
            TypeDefKind::Resource(resource) => {
                if let Some(docs) = &self.docs {
                    docs.render(f, opts)?;
                }
                write!(f, "{}resource {} {{\n", opts.spaces(), self.name)?;
                for func in &resource.funcs {
                    let opts = opts.indent();
                    if let Some(docs) = &func.docs {
                        docs.render(f, &opts)?;
                    }
                    match &func.kind {
                        crate::ResourceFuncKind::Method(name, results) => {
                            write!(f, "{}{}: func({})", opts.spaces(), name, func.params)?;
                            if !results.is_empty() {
                                write!(f, " -> {}", results)?;
                            }
                            write!(f, ";\n")?;
                        }
                        crate::ResourceFuncKind::Static(name, results) => {
                            write!(f, "{}{}: static func({})", opts.spaces(), name, func.params)?;
                            if !results.is_empty() {
                                write!(f, " -> {}", results)?;
                            }
                            write!(f, ";\n")?;
                        }
                        crate::ResourceFuncKind::Constructor => {
                            write!(f, "{}constructor({});\n", opts.spaces(), func.params)?;
                        }
                    }
                }
                write!(f, "{}}}\n", opts.spaces())?;
            }
            TypeDefKind::Flags(flags) => {
                if let Some(docs) = &self.docs {
                    docs.render(f, opts)?;
                }
                write!(f, "{}flags {} {{\n", opts.spaces(), self.name)?;
                for flag in &flags.flags {
                    let opts = opts.indent();
                    if let Some(docs) = &flag.docs {
                        docs.render(f, &opts)?;
                    }
                    write!(f, "{}{},\n", opts.spaces(), flag.name)?;
                }
                write!(f, "{}}}\n", opts.spaces())?;
            }
            TypeDefKind::Variant(variant) => {
                if let Some(docs) = &self.docs {
                    docs.render(f, opts)?;
                }
                write!(f, "{}variant {} {{\n", opts.spaces(), self.name)?;
                for case in &variant.cases {
                    let opts = opts.indent();
                    if let Some(docs) = &case.docs {
                        docs.render(f, &opts)?;
                    }
                    match &case.type_ {
                        Some(type_) => {
                            write!(f, "{}{}({}),\n", opts.spaces(), case.name, type_)?;
                        }
                        None => {
                            write!(f, "{}{},\n", opts.spaces(), case.name)?;
                        }
                    }
                }
                write!(f, "{}}}\n", opts.spaces())?;
            }
            TypeDefKind::Enum(enum_) => {
                if let Some(docs) = &self.docs {
                    docs.render(f, opts)?;
                }
                write!(f, "{}enum {} {{\n", opts.spaces(), self.name)?;
                for case in &enum_.cases {
                    let opts = opts.indent();
                    if let Some(docs) = &case.docs {
                        docs.render(f, &opts)?;
                    }
                    write!(f, "{}{},\n", opts.spaces(), case.name)?;
                }
                write!(f, "{}}}\n", opts.spaces())?;
            }
            TypeDefKind::Type(type_) => {
                if let Some(docs) = &self.docs {
                    docs.render(f, opts)?;
                }
                write!(f, "{}type {} = {};\n", opts.spaces(), self.name, type_)?;
            }
        }
        Ok(())
    }
}