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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
use std::convert::From;

use binding::{module, class};
use binding::global::rb_cObject;
use typed_data::DataTypeWrapper;
use types::{Value, ValueType, Callback};

use {AnyObject, Array, Object, Class, VerifiedObject};

/// `Module`
///
/// Also see `def`, `def_self`, `define` and some more functions from `Object` trait.
///
/// ```rust
/// #[macro_use] extern crate rutie;
///
/// use std::error::Error;
///
/// use rutie::{Module, Fixnum, Object, Exception, VM};
///
/// module!(Example);
///
/// methods!(
///    Example,
///    itself,
///
///     fn square(exp: Fixnum) -> Fixnum {
///         // `exp` is not a valid `Fixnum`, raise an exception
///         if let Err(ref error) = exp {
///             VM::raise(error.class(), &error.message());
///         }
///
///         // We can safely unwrap here, because an exception was raised if `exp` is `Err`
///         let exp = exp.unwrap().to_i64();
///
///         Fixnum::new(exp * exp)
///     }
/// );
///
/// fn main() {
///     # VM::init();
///     Module::new("Example").define(|itself| {
///         itself.def("square", square);
///     });
/// }
/// ```
///
/// Ruby:
///
/// ```ruby
/// module Example
///   def square(exp)
///     raise TypeError unless exp.is_a?(Fixnum)
///
///     exp * exp
///   end
/// end
/// ```
#[derive(Debug)]
pub struct Module {
    value: Value,
}

impl Module {
    /// Creates a new `Module`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, VM};
    /// # VM::init();
    ///
    /// let basic_record_module = Module::new("BasicRecord");
    ///
    /// assert_eq!(basic_record_module, Module::from_existing("BasicRecord"));
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module BasicRecord
    /// end
    /// ```
    pub fn new(name: &str) -> Self {
        Self::from(module::define_module(name))
    }

    /// Retrieves an existing `Module` object.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, VM};
    /// # VM::init();
    ///
    /// let module = Module::new("Record");
    ///
    /// assert_eq!(module, Module::from_existing("Record"));
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Record
    /// end
    ///
    /// # get module
    ///
    /// Record
    ///
    /// # or
    ///
    /// Object.const_get('Record')
    /// ```
    pub fn from_existing(name: &str) -> Self {
        let object_module = unsafe { rb_cObject };

        Self::from(class::const_get(object_module, name))
    }

    /// Returns a Vector of ancestors of current module
    ///
    /// # Examples
    ///
    /// ### Getting all the ancestors
    ///
    /// ```
    /// use rutie::{Module, VM};
    /// # VM::init();
    ///
    /// let process_module_ancestors = Module::from_existing("Process").ancestors();
    ///
    /// let expected_ancestors = vec![
    ///     Module::from_existing("Process")
    /// ];
    ///
    /// assert_eq!(process_module_ancestors, expected_ancestors);
    /// ```
    ///
    /// ### Searching for an ancestor
    ///
    /// ```
    /// use rutie::{Module, VM};
    /// # VM::init();
    ///
    /// let record_module = Module::new("Record");
    ///
    /// let ancestors = record_module.ancestors();
    ///
    /// assert!(ancestors.iter().any(|module| *module == record_module));
    /// ```
    // Using unsafe conversions is ok, because MRI guarantees to return an `Array` of `Module`es
    pub fn ancestors(&self) -> Vec<Module> {
        let ancestors = Array::from(class::ancestors(self.value()));

        ancestors
            .into_iter()
            .map(|module| unsafe { module.to::<Self>() })
            .collect()
    }

    /// Retrieves a `Module` nested to current `Module`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, Object, VM};
    /// # VM::init();
    ///
    /// Module::new("Outer").define(|itself| {
    ///     itself.define_nested_module("Inner");
    /// });
    ///
    /// Module::from_existing("Outer").get_nested_module("Inner");
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Outer
    ///   module Inner
    ///   end
    /// end
    ///
    /// Outer::Inner
    ///
    /// # or
    ///
    /// Outer.const_get('Inner')
    /// ```
    pub fn get_nested_module(&self, name: &str) -> Self {
        Self::from(class::const_get(self.value(), name))
    }

    /// Retrieves a `Class` nested to current `Module`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Class, Module, Object, VM};
    /// # VM::init();
    ///
    /// Module::new("Outer").define(|itself| {
    ///     itself.define_nested_class("Inner", None);
    /// });
    ///
    /// Module::from_existing("Outer").get_nested_class("Inner");
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Outer
    ///   class Inner
    ///   end
    /// end
    ///
    /// Outer::Inner
    ///
    /// # or
    ///
    /// Outer.const_get('Inner')
    /// ```
    pub fn get_nested_class(&self, name: &str) -> Class {
        Class::from(class::const_get(self.value(), name))
    }

    /// Creates a new `Module` nested into current `Module`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, Object, VM};
    /// # VM::init();
    ///
    /// Module::new("Outer").define(|itself| {
    ///     itself.define_nested_module("Inner");
    /// });
    ///
    /// Module::from_existing("Outer").get_nested_module("Inner");
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Outer
    ///   module Inner
    ///   end
    /// end
    ///
    /// Outer::Inner
    ///
    /// # or
    ///
    /// Outer.const_get('Inner')
    /// ```
    pub fn define_nested_module(&mut self, name: &str) -> Self {
        Self::from(module::define_nested_module(self.value(), name))
    }

    /// Creates a new `Class` nested into current module.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Class, Module, Object, VM};
    /// # VM::init();
    ///
    /// Module::new("Outer").define(|itself| {
    ///     itself.define_nested_class("Inner", None);
    /// });
    ///
    /// Module::from_existing("Outer").get_nested_class("Inner");
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Outer
    ///   class Inner
    ///   end
    /// end
    ///
    /// Outer::Inner
    ///
    /// # or
    ///
    /// Outer.const_get('Inner')
    /// ```
    pub fn define_nested_class(&mut self, name: &str, superclass: Option<&Class>) -> Class {
        let superclass = Self::superclass_to_value(superclass);

        Class::from(class::define_nested_class(self.value(), name, superclass))
    }

    /// Defines an instance method for the given module.
    ///
    /// Use `methods!` macro to define a `callback`.
    ///
    /// You can also use `def()` alias for this function combined with `Module::define()` for a
    /// nicer DSL.
    ///
    /// # Panics
    ///
    /// Ruby can raise an exception if you try to define instance method directly on an instance
    /// of some class (like `Fixnum`, `String`, `Array` etc).
    ///
    /// Use this method only on classes (or singleton classes of objects).
    ///
    /// # Examples
    ///
    /// ### The famous String#blank? method
    ///
    /// ```rust
    /// #[macro_use] extern crate rutie;
    ///
    /// use rutie::{Boolean, Module, Class, Object, RString, VM};
    ///
    /// methods!(
    ///    RString,
    ///    itself,
    ///
    ///    fn is_blank() -> Boolean {
    ///        Boolean::new(itself.to_str().chars().all(|c| c.is_whitespace()))
    ///    }
    /// );
    ///
    /// fn main() {
    ///     # VM::init();
    ///     Module::new("Blank").define(|itself| {
    ///         itself.mod_func("blank?", is_blank);
    ///     });
    ///
    ///     Class::from_existing("String").include("Blank");
    /// }
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Blank
    ///   def blank?
    ///     # simplified
    ///     self.chars.all? { |c| c == ' ' }
    ///   end
    ///   module_function :blank?
    /// end
    ///
    /// String.include Blank
    /// ```
    ///
    /// ### Receiving arguments
    ///
    /// Raise `Fixnum` to the power of `exp`.
    ///
    /// ```rust
    /// #[macro_use] extern crate rutie;
    ///
    /// use std::error::Error;
    ///
    /// use rutie::{Module, Fixnum, Object, Exception, VM};
    ///
    /// methods!(
    ///     Fixnum,
    ///     itself,
    ///
    ///     fn pow(exp: Fixnum) -> Fixnum {
    ///         // `exp` is not a valid `Fixnum`, raise an exception
    ///         if let Err(ref error) = exp {
    ///             VM::raise(error.class(), &error.message());
    ///         }
    ///
    ///         // We can safely unwrap here, because an exception was raised if `exp` is `Err`
    ///         let exp = exp.unwrap().to_i64() as u32;
    ///
    ///         Fixnum::new(itself.to_i64().pow(exp))
    ///     }
    ///
    ///     fn pow_with_default_argument(exp: Fixnum) -> Fixnum {
    ///         let default_exp = 0;
    ///         let exp = exp.map(|exp| exp.to_i64()).unwrap_or(default_exp);
    ///
    ///         let result = itself.to_i64().pow(exp as u32);
    ///
    ///         Fixnum::new(result)
    ///     }
    /// );
    ///
    /// fn main() {
    ///     # VM::init();
    ///     Module::from_existing("Fixnum").define(|itself| {
    ///         itself.mod_func("pow", pow);
    ///         itself.mod_func("pow_with_default_argument", pow_with_default_argument);
    ///     });
    /// }
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Fixnum
    ///   def pow(exp)
    ///     raise ArgumentError unless exp.is_a?(Fixnum)
    ///
    ///     self ** exp
    ///   end
    ///   module_function :pow
    ///
    ///   def pow_with_default_argument(exp)
    ///     default_exp = 0
    ///     exp = default_exp unless exp.is_a?(Fixnum)
    ///
    ///     self ** exp
    ///   end
    ///   module_function :pow_with_default_argument
    /// end
    /// ```
    pub fn define_module_function<I: Object, O: Object>(&mut self, name: &str, callback: Callback<I, O>) {
        module::define_module_function(self.value(), name, callback);
    }

    /// An alias for `define_module_function` (similar to Ruby `module_function :some_method`).
    pub fn mod_func<I: Object, O: Object>(&mut self, name: &str, callback: Callback<I, O>) {
        self.define_module_function(name, callback);
    }

    /// Retrieves a constant from module.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, Object, RString, VM};
    /// # VM::init();
    ///
    /// Module::new("Greeter").define(|itself| {
    ///     itself.const_set("GREETING", &RString::new_utf8("Hello, World!"));
    /// });
    ///
    /// let greeting = Module::from_existing("Greeter")
    ///     .const_get("GREETING")
    ///     .try_convert_to::<RString>()
    ///     .unwrap();
    ///
    /// assert_eq!(greeting.to_str(), "Hello, World!");
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Greeter
    ///   GREETING = 'Hello, World!'
    /// end
    ///
    /// # or
    ///
    /// Greeter = Module.new
    /// Greeter.const_set('GREETING', 'Hello, World!')
    ///
    /// # ...
    ///
    /// Greeter::GREETING == 'Hello, World!'
    ///
    /// # or
    ///
    /// Greeter.const_get('GREETING') == 'Hello, World'
    /// ```
    pub fn const_get(&self, name: &str) -> AnyObject {
        let value = class::const_get(self.value(), name);

        AnyObject::from(value)
    }

    /// Defines a constant for module.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, Object, RString, VM};
    /// # VM::init();
    ///
    /// Module::new("Greeter").define(|itself| {
    ///     itself.const_set("GREETING", &RString::new_utf8("Hello, World!"));
    /// });
    ///
    /// let greeting = Module::from_existing("Greeter")
    ///     .const_get("GREETING")
    ///     .try_convert_to::<RString>()
    ///     .unwrap();
    ///
    /// assert_eq!(greeting.to_str(), "Hello, World!");
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Greeter
    ///   GREETING = 'Hello, World!'
    /// end
    ///
    /// # or
    ///
    /// Greeter = Module.new
    /// Greeter.const_set('GREETING', 'Hello, World!')
    ///
    /// # ...
    ///
    /// Greeter::GREETING == 'Hello, World!'
    ///
    /// # or
    ///
    /// Greeter.const_get('GREETING') == 'Hello, World'
    /// ```
    pub fn const_set<T: Object>(&mut self, name: &str, value: &T) {
        class::const_set(self.value(), name, value.value());
    }

    /// Includes module into current module
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, VM};
    /// # VM::init();
    ///
    /// Module::new("A");
    /// Module::new("B").include("A");
    ///
    /// let b_module_ancestors = Module::from_existing("B").ancestors();
    ///
    /// let expected_ancestors = vec![
    ///     Module::from_existing("B"),
    ///     Module::from_existing("A")
    /// ];
    ///
    /// assert_eq!(b_module_ancestors, expected_ancestors);
    /// ```
    pub fn include(&self, md: &str) {
        module::include_module(self.value(), md);
    }

    /// Prepends module into current module
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, VM};
    /// # VM::init();
    ///
    /// Module::new("A");
    /// Module::new("B").prepend("A");
    ///
    /// let b_module_ancestors = Module::from_existing("B").ancestors();
    ///
    /// let expected_ancestors = vec![
    ///     Module::from_existing("A"),
    ///     Module::from_existing("B")
    /// ];
    ///
    /// assert_eq!(b_module_ancestors, expected_ancestors);
    /// ```
    pub fn prepend(&self, md: &str) {
        module::prepend_module(self.value(), md);
    }

    /// Defines an `attr_reader` for module
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, Object, VM};
    /// # VM::init();
    ///
    /// Module::new("Test").define(|itself| {
    ///     itself.attr_reader("reader");
    /// });
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Test
    ///   attr_reader :reader
    /// end
    /// ```
    pub fn attr_reader(&mut self, name: &str) {
        class::define_attribute(self.value(), name, true, false);
    }

    /// Defines an `attr_writer` for module
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, Object, VM};
    /// # VM::init();
    ///
    /// Module::new("Test").define(|itself| {
    ///     itself.attr_writer("writer");
    /// });
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Test
    ///   attr_writer :writer
    /// end
    /// ```
    pub fn attr_writer(&mut self, name: &str) {
        class::define_attribute(self.value(), name, false, true);
    }

    /// Defines an `attr_accessor` for module
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Module, Object, VM};
    /// # VM::init();
    ///
    /// Module::new("Test").define(|itself| {
    ///     itself.attr_accessor("accessor");
    /// });
    /// ```
    ///
    /// Ruby:
    ///
    /// ```ruby
    /// module Test
    ///   attr_accessor :accessor
    /// end
    /// ```
    pub fn attr_accessor(&mut self, name: &str) {
        class::define_attribute(self.value(), name, true, true);
    }

    /// Wraps Rust structure into a new Ruby object of the current module.
    ///
    /// See the documentation for `wrappable_struct!` macro for more information.
    ///
    /// # Examples
    ///
    /// Wrap `Server` structs to `RubyServer` objects.  Note: Example shows use
    /// with class but the method still applies to module.
    ///
    /// ```
    /// #[macro_use] extern crate rutie;
    /// #[macro_use] extern crate lazy_static;
    ///
    /// use rutie::{AnyObject, Class, Fixnum, Object, RString, VM};
    ///
    /// // The structure which we want to wrap
    /// pub struct Server {
    ///     host: String,
    ///     port: u16,
    /// }
    ///
    /// impl Server {
    ///     fn new(host: String, port: u16) -> Self {
    ///         Server {
    ///             host: host,
    ///             port: port,
    ///         }
    ///     }
    ///
    ///     fn host(&self) -> &str {
    ///         &self.host
    ///     }
    ///
    ///     fn port(&self) -> u16 {
    ///         self.port
    ///     }
    /// }
    ///
    /// wrappable_struct!(Server, ServerWrapper, SERVER_WRAPPER);
    ///
    /// class!(RubyServer);
    ///
    /// methods!(
    ///     RubyServer,
    ///     itself,
    ///
    ///     fn ruby_server_new(host: RString, port: Fixnum) -> AnyObject {
    ///         let server = Server::new(host.unwrap().to_string(),
    ///                                  port.unwrap().to_i64() as u16);
    ///
    ///         Class::from_existing("RubyServer").wrap_data(server, &*SERVER_WRAPPER)
    ///     }
    ///
    ///     fn ruby_server_host() -> RString {
    ///         let host = itself.get_data(&*SERVER_WRAPPER).host();
    ///
    ///         RString::new_utf8(host)
    ///     }
    ///
    ///     fn ruby_server_port() -> Fixnum {
    ///         let port = itself.get_data(&*SERVER_WRAPPER).port();
    ///
    ///         Fixnum::new(port as i64)
    ///     }
    /// );
    ///
    /// fn main() {
    ///     # VM::init();
    ///     let data_class = Class::from_existing("Object");
    ///
    ///     Class::new("RubyServer", None).define(|itself| {
    ///         itself.def_self("new", ruby_server_new);
    ///
    ///         itself.def("host", ruby_server_host);
    ///         itself.def("port", ruby_server_port);
    ///     });
    /// }
    /// ```
    ///
    /// To use the `RubyServer` class in Ruby:
    ///
    /// ```ruby
    /// server = RubyServer.new("127.0.0.1", 3000)
    ///
    /// server.host == "127.0.0.1"
    /// server.port == 3000
    /// ```
    pub fn wrap_data<T, O: Object>(&self, data: T, wrapper: &DataTypeWrapper<T>) -> O {
        let value = class::wrap_data(self.value(), data, wrapper);

        O::from(value)
    }

    fn superclass_to_value(superclass: Option<&Class>) -> Value {
        match superclass {
            Some(class) => class.value(),
            None => unsafe { rb_cObject },
        }
    }
}

impl From<Value> for Module {
    fn from(value: Value) -> Self {
        Module { value: value }
    }
}

impl Into<Value> for Module {
    fn into(self) -> Value {
        self.value
    }
}

impl Into<AnyObject> for Module {
    fn into(self) -> AnyObject {
        AnyObject::from(self.value)
    }
}

impl Object for Module {
    #[inline]
    fn value(&self) -> Value {
        self.value
    }
}

impl VerifiedObject for Module {
    fn is_correct_type<T: Object>(object: &T) -> bool {
        object.value().ty() == ValueType::Module
    }

    fn error_message() -> &'static str {
        "Error converting to Module"
    }
}

impl PartialEq for Module {
    fn eq(&self, other: &Self) -> bool {
        self.equals(other)
    }
}