wit_encoder/
world.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
use std::fmt;

use crate::{ident::Ident, Docs, Include, Interface, Render, RenderOpts, StandaloneFunc, Use};

#[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 World {
    /// The WIT identifier name of this world.
    name: Ident,

    /// Interface uses
    uses: Vec<Use>,

    /// All imported and exported items into this world.
    items: Vec<WorldItem>,

    /// Documentation associated with this world declaration.
    docs: Option<Docs>,
}

impl World {
    /// Create a new world.
    pub fn new(name: impl Into<Ident>) -> Self {
        Self {
            name: name.into(),
            uses: vec![],
            items: vec![],
            docs: None,
        }
    }

    /// Add a `name` to the world
    pub fn set_name(&mut self, name: impl Into<Ident>) {
        self.name = name.into();
    }

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

    pub fn items(&self) -> &[WorldItem] {
        &self.items
    }

    pub fn items_mut(&mut self) -> &mut Vec<WorldItem> {
        &mut self.items
    }

    /// Add an import or export to the world
    pub fn item(&mut self, item: WorldItem) {
        self.items.push(item);
    }

    pub fn inline_interface_import(&mut self, value: Interface) {
        self.item(WorldItem::inline_interface_import(value));
    }
    pub fn inline_interface_export(&mut self, value: Interface) {
        self.item(WorldItem::inline_interface_export(value));
    }
    pub fn named_interface_import(&mut self, value: impl Into<WorldNamedInterface>) {
        self.item(WorldItem::named_interface_import(value));
    }
    pub fn named_interface_export(&mut self, value: impl Into<WorldNamedInterface>) {
        self.item(WorldItem::named_interface_export(value));
    }
    pub fn function_import(&mut self, value: StandaloneFunc) {
        self.item(WorldItem::function_import(value));
    }
    pub fn function_export(&mut self, value: StandaloneFunc) {
        self.item(WorldItem::function_export(value));
    }
    pub fn include(&mut self, include: Include) {
        self.item(WorldItem::Include(include));
    }

    pub fn uses(&self) -> &[Use] {
        &self.uses
    }
    pub fn uses_mut(&mut self) -> &mut [Use] {
        &mut self.uses
    }
    pub fn use_(&mut self, use_: Use) {
        self.uses.push(use_);
    }
    pub fn use_type(
        &mut self,
        target: impl Into<Ident>,
        item: impl Into<Ident>,
        rename: Option<Ident>,
    ) {
        let target = target.into();
        let use_ = self.uses.iter_mut().find(|u| u.target() == &target);
        match use_ {
            Some(use_) => use_.item(item, rename),
            None => {
                self.use_({
                    let mut use_ = Use::new(target);
                    use_.item(item, rename);
                    use_
                });
            }
        }
    }

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

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

impl Render for World {
    fn render(&self, f: &mut fmt::Formatter<'_>, opts: &RenderOpts) -> fmt::Result {
        fn import(f: &mut fmt::Formatter<'_>, opts: &RenderOpts) -> fmt::Result {
            write!(f, "{}import ", opts.spaces())
        }
        fn export(f: &mut fmt::Formatter<'_>, opts: &RenderOpts) -> fmt::Result {
            write!(f, "{}export ", opts.spaces())
        }
        fn render_function(
            f: &mut fmt::Formatter<'_>,
            _opts: &RenderOpts,
            func: &StandaloneFunc,
        ) -> fmt::Result {
            write!(f, "{}: func({})", func.name, func.params)?;
            if !func.results.is_empty() {
                write!(f, " -> {}", func.results)?;
            }
            write!(f, ";\n")?;
            Ok(())
        }
        write!(f, "{}world {} {{\n", opts.spaces(), self.name)?;
        let opts = &opts.indent();
        self.uses.render(f, opts)?;
        for item in &self.items {
            match item {
                WorldItem::InlineInterfaceImport(interface) => {
                    if let Some(docs) = &interface.docs {
                        docs.render(f, opts)?;
                    }
                    import(f, opts)?;
                    write!(f, "{}: interface {{", interface.name)?;
                    if !interface.uses.is_empty() || !interface.items.is_empty() {
                        write!(f, "\n")?;
                        interface.uses.render(f, &opts.indent())?;
                        interface.items.render(f, &opts.indent())?;
                        write!(f, "{}}}\n", opts.spaces())?;
                    } else {
                        write!(f, "}}\n")?;
                    }
                }
                WorldItem::InlineInterfaceExport(interface) => {
                    if let Some(docs) = &interface.docs {
                        docs.render(f, opts)?;
                    }
                    export(f, opts)?;
                    write!(f, "{}: interface {{", interface.name)?;
                    if !interface.items.is_empty() {
                        write!(f, "\n")?;
                        interface.items.render(f, &opts.indent())?;
                        write!(f, "{}}}\n", opts.spaces())?;
                    } else {
                        write!(f, "}}\n")?;
                    }
                }
                WorldItem::NamedInterfaceImport(interface) => {
                    if let Some(docs) = &interface.docs {
                        docs.render(f, opts)?;
                    }
                    import(f, opts)?;
                    write!(f, "{};\n", interface.name)?;
                }
                WorldItem::NamedInterfaceExport(interface) => {
                    if let Some(docs) = &interface.docs {
                        docs.render(f, opts)?;
                    }
                    export(f, opts)?;
                    write!(f, "{};\n", interface.name)?;
                }
                WorldItem::FunctionImport(function) => {
                    if let Some(docs) = &function.docs {
                        docs.render(f, opts)?;
                    }
                    import(f, opts)?;
                    render_function(f, opts, function)?;
                }
                WorldItem::FunctionExport(function) => {
                    if let Some(docs) = &function.docs {
                        docs.render(f, opts)?;
                    }
                    export(f, opts)?;
                    render_function(f, opts, function)?;
                }
                WorldItem::Include(include) => include.render(f, opts)?,
            }
        }
        let opts = &opts.outdent();
        write!(f, "{}}}\n", opts.spaces())?;
        Ok(())
    }
}

#[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 WorldItem {
    /// An imported inline interface
    InlineInterfaceImport(Interface),

    /// An exported inline interface
    InlineInterfaceExport(Interface),

    /// Refers to a named interface import
    NamedInterfaceImport(WorldNamedInterface),

    /// Refers to a named interface export
    NamedInterfaceExport(WorldNamedInterface),

    /// A function is being directly imported from this world.
    FunctionImport(StandaloneFunc),

    /// A function is being directly exported from this world.
    FunctionExport(StandaloneFunc),

    /// Include type
    Include(Include),
}

impl WorldItem {
    pub fn inline_interface_import(value: Interface) -> Self {
        Self::InlineInterfaceImport(value)
    }
    pub fn inline_interface_export(value: Interface) -> Self {
        Self::InlineInterfaceExport(value)
    }
    pub fn named_interface_import(value: impl Into<WorldNamedInterface>) -> Self {
        Self::NamedInterfaceImport(value.into())
    }
    pub fn named_interface_export(value: impl Into<WorldNamedInterface>) -> Self {
        Self::NamedInterfaceExport(value.into())
    }
    pub fn function_import(value: StandaloneFunc) -> Self {
        Self::FunctionImport(value)
    }
    pub fn function_export(value: StandaloneFunc) -> Self {
        Self::FunctionExport(value)
    }
    pub fn include(value: impl Into<Ident>) -> Self {
        Self::Include(Include::new(value))
    }
}

#[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 WorldNamedInterface {
    /// Name of this interface.
    pub(crate) name: Ident,

    /// Documentation associated with this interface.
    pub(crate) docs: Option<Docs>,
}

impl<N> From<N> for WorldNamedInterface
where
    N: Into<Ident>,
{
    fn from(name: N) -> Self {
        Self::new(name)
    }
}

impl WorldNamedInterface {
    pub fn new(name: impl Into<Ident>) -> Self {
        Self {
            name: name.into(),
            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 set_docs(&mut self, docs: Option<impl Into<Docs>>) {
        self.docs = docs.map(|d| d.into());
    }

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