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
use std::borrow::Cow;
use std::collections::HashSet;
use std::convert::AsRef;
use std::ffi::{c_void, CStr};
use std::hash::{Hash, Hasher};
use std::ptr::NonNull;

use crate::core::Intern;
use crate::def::{ConstantNameError, EnclosingRubyScope, Method, NotDefinedError};
use crate::error::Error;
use crate::method;
use crate::sys;
use crate::Artichoke;

#[derive(Debug)]
pub struct Builder<'a> {
    interp: &'a mut Artichoke,
    spec: &'a Spec,
    methods: HashSet<method::Spec>,
}

impl<'a> Builder<'a> {
    #[must_use]
    pub fn for_spec(interp: &'a mut Artichoke, spec: &'a Spec) -> Self {
        Self {
            interp,
            spec,
            methods: HashSet::default(),
        }
    }

    pub fn add_method<T>(mut self, name: T, method: Method, args: sys::mrb_aspec) -> Result<Self, ConstantNameError>
    where
        T: Into<Cow<'static, str>>,
    {
        let spec = method::Spec::new(method::Type::Instance, name.into(), method, args)?;
        self.methods.insert(spec);
        Ok(self)
    }

    pub fn add_self_method<T>(
        mut self,
        name: T,
        method: Method,
        args: sys::mrb_aspec,
    ) -> Result<Self, ConstantNameError>
    where
        T: Into<Cow<'static, str>>,
    {
        let spec = method::Spec::new(method::Type::Class, name.into(), method, args)?;
        self.methods.insert(spec);
        Ok(self)
    }

    pub fn add_module_method<T>(
        mut self,
        name: T,
        method: Method,
        args: sys::mrb_aspec,
    ) -> Result<Self, ConstantNameError>
    where
        T: Into<Cow<'static, str>>,
    {
        let spec = method::Spec::new(method::Type::Module, name.into(), method, args)?;
        self.methods.insert(spec);
        Ok(self)
    }

    pub fn define(self) -> Result<(), NotDefinedError> {
        let name = self.spec.name_c_str().as_ptr();

        let rclass = self.spec.rclass();
        let rclass = unsafe { self.interp.with_ffi_boundary(|mrb| rclass.resolve(mrb)) };

        let mut rclass = if let Ok(Some(rclass)) = rclass {
            rclass
        } else if let Some(enclosing_scope) = self.spec.enclosing_scope() {
            let scope = unsafe { self.interp.with_ffi_boundary(|mrb| enclosing_scope.rclass(mrb)) };
            if let Ok(Some(mut scope)) = scope {
                let rclass = unsafe {
                    self.interp
                        .with_ffi_boundary(|mrb| sys::mrb_define_module_under(mrb, scope.as_mut(), name))
                };
                let rclass = rclass.map_err(|_| NotDefinedError::module(self.spec.name()))?;
                NonNull::new(rclass).ok_or_else(|| NotDefinedError::module(self.spec.name()))?
            } else {
                return Err(NotDefinedError::enclosing_scope(enclosing_scope.fqname().into_owned()));
            }
        } else {
            let rclass = unsafe { self.interp.with_ffi_boundary(|mrb| sys::mrb_define_module(mrb, name)) };
            let rclass = rclass.map_err(|_| NotDefinedError::module(self.spec.name()))?;
            NonNull::new(rclass).ok_or_else(|| NotDefinedError::module(self.spec.name()))?
        };

        for method in self.methods {
            unsafe {
                method.define(self.interp, rclass.as_mut())?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rclass {
    sym: u32,
    name: &'static CStr,
    enclosing_scope: Option<EnclosingRubyScope>,
}

impl Rclass {
    #[must_use]
    pub const fn new(sym: u32, name: &'static CStr, enclosing_scope: Option<EnclosingRubyScope>) -> Self {
        Self {
            sym,
            name,
            enclosing_scope,
        }
    }

    /// Resolve a type's [`sys::RClass`] using its enclosing scope and name.
    ///
    /// # Safety
    ///
    /// This function must be called within an [`Artichoke::with_ffi_boundary`]
    /// closure because the FFI APIs called in this function may require access
    /// to the Artichoke [`State`](crate::state::State).
    pub unsafe fn resolve(&self, mrb: *mut sys::mrb_state) -> Option<NonNull<sys::RClass>> {
        let module_name = self.name.as_ptr();
        if let Some(ref scope) = self.enclosing_scope {
            // Short circuit if enclosing scope does not exist.
            let mut scope = scope.rclass(mrb)?;
            let is_defined_under =
                sys::mrb_const_defined_at(mrb, sys::mrb_sys_obj_value(scope.cast::<c_void>().as_mut()), self.sym);
            if is_defined_under {
                // Enclosing scope exists.
                // Module is defined under the enclosing scope.
                let module = sys::mrb_module_get_under(mrb, scope.as_mut(), module_name);
                NonNull::new(module)
            } else {
                // Enclosing scope exists.
                // Module is not defined under the enclosing scope.
                None
            }
        } else {
            let is_defined = sys::mrb_const_defined_at(
                mrb,
                sys::mrb_sys_obj_value((*mrb).object_class.cast::<c_void>()),
                self.sym,
            );
            if is_defined {
                // Module exists in root scope.
                let module = sys::mrb_module_get(mrb, module_name);
                NonNull::new(module)
            } else {
                // Class does not exist in root scope.
                None
            }
        }
    }
}

#[derive(Debug)]
pub struct Spec {
    name: Cow<'static, str>,
    name_cstr: &'static CStr,
    sym: u32,
    enclosing_scope: Option<EnclosingRubyScope>,
}

impl Spec {
    pub fn new<T>(
        interp: &mut Artichoke,
        name: T,
        name_cstr: &'static CStr,
        enclosing_scope: Option<EnclosingRubyScope>,
    ) -> Result<Self, Error>
    where
        T: Into<Cow<'static, str>>,
    {
        let name = name.into();
        let sym = match name {
            Cow::Borrowed(name) => interp.intern_string(name)?,
            Cow::Owned(ref name) => interp.intern_string(name.clone())?,
        };
        Ok(Self {
            name,
            name_cstr,
            sym,
            enclosing_scope,
        })
    }

    #[must_use]
    pub fn name(&self) -> Cow<'static, str> {
        match &self.name {
            Cow::Borrowed(name) => Cow::Borrowed(name),
            Cow::Owned(name) => name.clone().into(),
        }
    }

    #[must_use]
    pub fn name_c_str(&self) -> &'static CStr {
        self.name_cstr
    }

    #[must_use]
    pub fn enclosing_scope(&self) -> Option<&EnclosingRubyScope> {
        self.enclosing_scope.as_ref()
    }

    #[must_use]
    pub fn name_symbol(&self) -> u32 {
        self.sym
    }

    #[must_use]
    pub fn fqname(&self) -> Cow<'_, str> {
        if let Some(scope) = self.enclosing_scope() {
            let mut fqname = String::from(scope.fqname());
            fqname.push_str("::");
            fqname.push_str(self.name.as_ref());
            fqname.into()
        } else {
            self.name.as_ref().into()
        }
    }

    #[must_use]
    pub fn rclass(&self) -> Rclass {
        Rclass::new(self.sym, self.name_cstr, self.enclosing_scope.clone())
    }
}

impl Hash for Spec {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name().hash(state);
        self.enclosing_scope().hash(state);
    }
}

impl Eq for Spec {}

impl PartialEq for Spec {
    fn eq(&self, other: &Self) -> bool {
        self.fqname() == other.fqname()
    }
}

#[cfg(test)]
mod tests {
    use crate::module::Spec;
    use crate::test::prelude::*;

    #[test]
    fn rclass_for_undef_root_module() {
        let mut interp = interpreter();
        let spec = Spec::new(&mut interp, "Foo", qed::const_cstr_from_str!("Foo\0"), None).unwrap();
        let rclass = unsafe { interp.with_ffi_boundary(|mrb| spec.rclass().resolve(mrb)) }.unwrap();
        assert!(rclass.is_none());
    }

    #[test]
    fn rclass_for_undef_nested_module() {
        let mut interp = interpreter();
        let scope = Spec::new(&mut interp, "Kernel", qed::const_cstr_from_str!("Kernel\0"), None).unwrap();
        let scope = EnclosingRubyScope::module(&scope);
        let spec = Spec::new(&mut interp, "Foo", qed::const_cstr_from_str!("Foo\0"), Some(scope)).unwrap();
        let rclass = unsafe { interp.with_ffi_boundary(|mrb| spec.rclass().resolve(mrb)) }.unwrap();
        assert!(rclass.is_none());
    }

    #[test]
    fn rclass_for_root_module() {
        let mut interp = interpreter();
        let spec = Spec::new(&mut interp, "Kernel", qed::const_cstr_from_str!("Kernel\0"), None).unwrap();
        let rclass = unsafe { interp.with_ffi_boundary(|mrb| spec.rclass().resolve(mrb)) }.unwrap();
        assert!(rclass.is_some());
    }

    #[test]
    fn rclass_for_nested_module() {
        let mut interp = interpreter();
        interp.eval(b"module Foo; module Bar; end; end").unwrap();
        let scope = Spec::new(&mut interp, "Foo", qed::const_cstr_from_str!("Foo\0"), None).unwrap();
        let scope = EnclosingRubyScope::module(&scope);
        let spec = Spec::new(&mut interp, "Bar", qed::const_cstr_from_str!("Bar\0"), Some(scope)).unwrap();
        let rclass = unsafe { interp.with_ffi_boundary(|mrb| spec.rclass().resolve(mrb)) }.unwrap();
        assert!(rclass.is_some());
    }

    #[test]
    fn rclass_for_nested_module_under_class() {
        let mut interp = interpreter();
        interp.eval(b"class Foo; module Bar; end; end").unwrap();
        let scope = class::Spec::new("Foo", qed::const_cstr_from_str!("Foo\0"), None, None).unwrap();
        let scope = EnclosingRubyScope::class(&scope);
        let spec = Spec::new(&mut interp, "Bar", qed::const_cstr_from_str!("Bar\0"), Some(scope)).unwrap();
        let rclass = unsafe { interp.with_ffi_boundary(|mrb| spec.rclass().resolve(mrb)) }.unwrap();
        assert!(rclass.is_some());
    }
}