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
use std::collections::HashSet;

use crate::model::*;

pub struct InterfaceBuilder<'a> {
    lib: &'a mut LibraryBuilder,
    name: Name,
    callbacks: Vec<CallbackFunction<Unvalidated>>,
    callback_names: HashSet<String>,
    doc: Doc<Unvalidated>,
}

impl<'a> InterfaceBuilder<'a> {
    pub(crate) fn new(lib: &'a mut LibraryBuilder, name: Name, doc: Doc<Unvalidated>) -> Self {
        Self {
            lib,
            name,
            callbacks: Vec::new(),
            callback_names: Default::default(),
            doc,
        }
    }

    pub fn begin_callback<T: IntoName, D: Into<Doc<Unvalidated>>>(
        mut self,
        name: T,
        doc: D,
    ) -> BindResult<CallbackFunctionBuilder<'a>> {
        let name = name.into_name()?;
        self.check_unique_callback_name(&name)?;
        Ok(CallbackFunctionBuilder::new(self, name, doc.into()))
    }

    /// Build the interface and mark it as only used in a synchronous context.
    ///
    /// A synchronous interface is one that is invoked only during a function call which
    /// takes it as an argument. The Rust backend will NOT generate `Send` and `Sync`
    /// implementations so that it be cannot be transferred across thread boundaries.
    pub fn build_sync(self) -> BindResult<SynchronousInterface> {
        let (handle, lib) = self.build(InterfaceCategory::Synchronous);
        lib.add_statement(Statement::InterfaceDefinition(InterfaceType::Synchronous(
            handle.clone(),
        )))?;
        Ok(SynchronousInterface { inner: handle })
    }

    /// Build the interface and mark it as used in an asynchronous context.
    ///
    /// An asynchronous interface is one that is invoked some time after it is
    /// passed as a function argument. The Rust backend will mark the C representation
    /// of this interface as `Send` and `Sync` so that it be transferred across thread
    /// boundaries.
    pub fn build_async(self) -> BindResult<AsynchronousInterface> {
        let (handle, lib) = self.build(InterfaceCategory::Asynchronous);
        lib.add_statement(Statement::InterfaceDefinition(InterfaceType::Asynchronous(
            handle.clone(),
        )))?;
        Ok(AsynchronousInterface { inner: handle })
    }

    pub(crate) fn build(
        self,
        mode: InterfaceCategory,
    ) -> (InterfaceHandle, &'a mut LibraryBuilder) {
        let handle = Handle::new(Interface {
            name: self.name,
            mode,
            callbacks: self.callbacks,
            doc: self.doc,
            settings: self.lib.clone_settings(),
        });

        (handle, self.lib)
    }

    fn check_unique_callback_name(&mut self, name: &Name) -> BindResult<()> {
        if name == &self.lib.settings().interface.destroy_func_name {
            return Err(BindingErrorVariant::InterfaceMethodWithReservedName {
                name: self.lib.settings().interface.destroy_func_name.clone(),
            }
            .into());
        }

        if name == &self.lib.settings().interface.context_variable_name.clone() {
            return Err(BindingErrorVariant::InterfaceMethodWithReservedName {
                name: self.lib.settings().interface.context_variable_name.clone(),
            }
            .into());
        }

        if self.callback_names.insert(name.to_string()) {
            Ok(())
        } else {
            Err(BindingErrorVariant::InterfaceDuplicateCallbackName {
                interface_name: self.name.clone(),
                callback_name: name.clone(),
            }
            .into())
        }
    }
}

pub struct CallbackFunctionBuilder<'a> {
    builder: InterfaceBuilder<'a>,
    name: Name,
    functional_transform: FunctionalTransform,
    return_type: OptionalReturnType<CallbackReturnValue, Unvalidated>,
    default_implementation: Option<DefaultCallbackReturnValue>,
    arguments: Vec<Arg<CallbackArgument, Unvalidated>>,
    doc: Doc<Unvalidated>,
}

impl<'a> CallbackFunctionBuilder<'a> {
    pub(crate) fn new(builder: InterfaceBuilder<'a>, name: Name, doc: Doc<Unvalidated>) -> Self {
        Self {
            builder,
            name,
            functional_transform: FunctionalTransform::No,
            return_type: OptionalReturnType::new(),
            default_implementation: None,
            arguments: Vec::new(),
            doc,
        }
    }

    #[must_use]
    pub fn enable_functional_transform(mut self) -> Self {
        self.functional_transform = FunctionalTransform::Yes;
        self
    }

    pub fn param<S: IntoName, D: Into<DocString<Unvalidated>>, P: Into<CallbackArgument>>(
        mut self,
        name: S,
        arg_type: P,
        doc: D,
    ) -> BindResult<Self> {
        let arg_type = arg_type.into();
        let name = name.into_name()?;

        if name == self.builder.lib.settings().interface.context_variable_name {
            return Err(
                BindingErrorVariant::CallbackMethodArgumentWithReservedName {
                    name: self
                        .builder
                        .lib
                        .settings()
                        .interface
                        .context_variable_name
                        .clone(),
                }
                .into(),
            );
        }

        self.arguments.push(Arg::new(arg_type, name, doc.into()));
        Ok(self)
    }

    pub fn returns<T: Into<CallbackReturnValue>, D: Into<DocString<Unvalidated>>>(
        mut self,
        t: T,
        d: D,
    ) -> BindResult<Self> {
        self.return_type.set(&self.name, t.into(), d.into())?;
        Ok(self)
    }

    pub fn returns_with_default<
        T: Into<DefaultCallbackReturnValue>,
        D: Into<DocString<Unvalidated>>,
    >(
        self,
        t: T,
        d: D,
    ) -> BindResult<Self> {
        let default: DefaultCallbackReturnValue = t.into();

        let mut ret = if let Some(return_type) = default.get_callback_return_value() {
            // first, try to set the return type to ensure it hasn't previously been set
            self.returns(return_type, d)?
        } else {
            self
        };

        ret.default_implementation = Some(default);

        Ok(ret)
    }

    pub fn returns_nothing_by_default(mut self) -> BindResult<Self> {
        // return type should not already be defined
        if self.return_type.is_some() {
            return Err(BindingErrorVariant::ReturnTypeAlreadyDefined {
                func_name: self.name,
            }
            .into());
        }

        self.default_implementation = Some(DefaultCallbackReturnValue::Void);

        Ok(self)
    }

    pub fn end_callback(mut self) -> BindResult<InterfaceBuilder<'a>> {
        let cb = CallbackFunction {
            name: self.name,
            functional_transform: self.functional_transform,
            return_type: self.return_type,
            default_implementation: self.default_implementation,
            arguments: self.arguments,
            doc: self.doc,
        };

        self.builder.callbacks.push(cb);
        Ok(self.builder)
    }
}