Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! Derive and proc macros for magnus.
2 //!
3 //! ```
4 //! #[magnus::wrap(class = "RbPoint", free_immediately, size)]
5 //! struct Point {
6 //! x: isize,
7 //! y: isize,
8 //! }
9 //!
10 //! #[magnus::init]
11 //! fn init(ruby: &magnus::Ruby) -> Result<(), magnus::Error> {
12 //! ruby.define_class("RbPoint", ruby.class_object())?;
13 //! Ok(())
14 //! }
15 //! ```
16
17 #![warn(missing_docs)]
18
19 use proc_macro::TokenStream;
20 use syn::parse_macro_input;
21
22 mod init;
23 mod typed_data;
24 mod util;
25
26 /// Mark a function as the 'init' function to be run for a library when it is
27 /// `require`d by Ruby code.
28 ///
29 /// The init function is used to define your Ruby modules & classes, bind
30 /// functions as Ruby methods, etc.
31 ///
32 /// # Attributes
33 ///
34 /// * `name = "..."` - sets the name of the init function exported for Ruby.
35 /// This default's to the current crate's name. The name will be prepended
36 /// with `Init_` and `-` will be replaced with `_`. This (minus the `Init_`
37 /// prefix) must match the name of the final `.so`/`.bundle` file.
38 ///
39 /// # Examples
40 ///
41 /// ```
42 /// fn distance(a: (f64, f64), b: (f64, f64)) -> f64 {
43 /// ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
44 /// }
45 ///
46 /// #[magnus::init]
47 /// fn init(ruby: &magnus::Ruby) {
48 /// ruby.define_global_function("distance", magnus::function!(distance, 2));
49 /// }
50 /// ```
51 /// The init function can also return `Result<(), magnus::Error>`.
52 /// ```
53 /// use magnus::{function, method, prelude::*, Error, Ruby};
54 ///
55 /// #[magnus::wrap(class = "Euclid::Point", free_immediately, size)]
56 /// struct Point {
57 /// x: isize,
58 /// y: isize,
59 /// }
60 ///
61 /// impl Point {
62 /// fn new(x: isize, y: isize) -> Self {
63 /// Self { x, y }
64 /// }
65 ///
66 /// fn x(&self) -> isize {
67 /// self.x
68 /// }
69 ///
70 /// fn y(&self) -> isize {
71 /// self.y
72 /// }
73 /// }
74 ///
75 /// #[magnus::init]
76 /// fn init(ruby: &Ruby) -> Result<(), Error> {
77 /// let module = ruby.define_module("Euclid")?;
78 /// let class = module.define_class("Point", ruby.class_object())?;
79 /// class.define_singleton_method("new", function!(Point::new, 2))?;
80 /// class.define_method("x", method!(Point::x, 0))?;
81 /// class.define_method("y", method!(Point::y, 0))?;
82 /// Ok(())
83 /// }
84 /// ```
85 /// Setting the name.
86 /// ```
87 /// #[magnus::init(name = "example")]
88 /// fn init() {
89 /// ()
90 /// }
91 /// ```
92 #[proc_macro_attribute]
93 pub fn init(attrs: TokenStream, item: TokenStream) -> TokenStream {
94 let mut name = None;
95 if !attrs.is_empty() {
96 let attr_parser = syn::meta::parser(|meta| {
97 if meta.path.is_ident("name") {
98 name = Some(meta.value()?.parse::<syn::LitStr>()?.value());
99 Ok(())
100 } else {
101 Err(meta.error("unsupported attribute"))
102 }
103 });
104 parse_macro_input!(attrs with attr_parser);
105 }
106 match init::expand(name, parse_macro_input!(item)) {
107 Ok(tokens) => tokens,
108 Err(e) => e.into_compile_error(),
109 }
110 .into()
111 }
112
113 /// Allows a Rust type to be passed to Ruby, where it is automatically wrapped
114 /// as a Ruby object.
115 ///
116 /// For more control over the wrapping behavior, see [`TypedData`].
117 ///
118 /// # Attributes
119 ///
120 /// The `#[wrap]` macro supports several attributes to configure its behavior:
121 ///
122 /// * `class = "..."` (required):
123 /// Specifies the Ruby class associated with the Rust type. Supports module
124 /// paths, such as `Foo::Bar::Baz`, to locate nested classes.
125 ///
126 /// * `name = "..."`:
127 /// Specifies a debug name for the type. This name must be unique and
128 /// defaults to the class name if not explicitly provided.
129 ///
130 /// * `free_immediately`:
131 /// Indicates that the Rust type should be dropped as soon as the Ruby object
132 /// is garbage collected. This is only safe if the type's [`Drop`]
133 /// implementation does not call Ruby, as calling Ruby during the garbage
134 /// collection process is unsafe and can lead to undefined behavior.
135 ///
136 /// * `size`:
137 /// Reports the [`std::mem::size_of_val`] of the type to Ruby, helping Ruby's
138 /// garbage collector determine when to run.
139 ///
140 /// * `unsafe_generics`:
141 /// Disables compile-time checks for types with generics, allowing their use
142 /// with `#[wrap]`. This should only be used if you are confident that the
143 /// derived implementation of [`TypedData`] is correct for your generic type.
144 ///
145 /// # Variant Attributes
146 ///
147 /// When wrapping enums, the `#[magnus(...)]` attribute can also be applied to
148 /// individual variants to define specific behavior for them:
149 ///
150 /// * `class = "..."`:
151 /// Specifies the Ruby class associated with a particular variant. This is
152 /// useful for defining subclasses for the variants.
153 ///
154 /// # Examples
155 ///
156 /// Wrapping a struct:
157 ///
158 /// ```
159 /// use magnus::{function, prelude::*, wrap, Ruby};
160 ///
161 /// #[wrap(class = "Point", free_immediately, size)]
162 /// struct Point {
163 /// x: isize,
164 /// y: isize,
165 /// }
166 ///
167 /// fn point(x: isize, y: isize) -> Point {
168 /// Point { x, y }
169 /// }
170 ///
171 /// fn distance(a: &Point, b: &Point) -> f64 {
172 /// (((b.x - a.x).pow(2) + (b.y - a.y).pow(2)) as f64).sqrt()
173 /// }
174 ///
175 /// #[magnus::init]
176 /// fn init(ruby: &Ruby) {
177 /// ruby.define_global_function("point", function!(point, 2));
178 /// ruby.define_global_function("distance", function!(distance, 2));
179 /// }
180 /// ```
181 ///
182 /// See [`examples/point.rs`] for the complete example.
183 ///
184 /// [`examples/point.rs`]: https://github.com/matsadler/magnus/blob/main/examples/point.rs
185 ///
186 /// Handling mutability:
187 ///
188 /// ```
189 /// use std::cell::RefCell;
190 ///
191 /// use magnus::{prelude::*, wrap};
192 ///
193 /// struct Point {
194 /// x: isize,
195 /// y: isize,
196 /// }
197 ///
198 /// #[wrap(class = "Point")]
199 /// struct MutPoint(RefCell<Point>);
200 ///
201 /// impl MutPoint {
202 /// fn set_x(&self, i: isize) {
203 /// self.0.borrow_mut().x = i;
204 /// }
205 /// }
206 /// ```
207 ///
208 /// See [`examples/mut_point.rs`] for the complete example.
209 ///
210 /// [`examples/mut_point.rs`]: https://github.com/matsadler/magnus/blob/main/examples/mut_point.rs
211 ///
212 /// Supporting subclassing:
213 ///
214 /// ```
215 /// use std::cell::RefCell;
216 ///
217 /// use magnus::{function, method, prelude::*, wrap, Error, Ruby};
218 ///
219 /// #[derive(Default)]
220 /// struct Point {
221 /// x: isize,
222 /// y: isize,
223 /// }
224 ///
225 /// #[derive(Default)]
226 /// #[wrap(class = "Point")]
227 /// struct MutPoint(RefCell<Point>);
228 ///
229 /// impl MutPoint {
230 /// fn initialize(&self, x: isize, y: isize) {
231 /// let mut this = self.0.borrow_mut();
232 /// this.x = x;
233 /// this.y = y;
234 /// }
235 /// }
236 ///
237 /// #[magnus::init]
238 /// fn init(ruby: &Ruby) -> Result<(), Error> {
239 /// let class = ruby.define_class("Point", ruby.class_object()).unwrap();
240 /// class.define_alloc_func::<MutPoint>();
241 /// class.define_method("initialize", method!(MutPoint::initialize, 2))?;
242 /// Ok(())
243 /// }
244 /// ```
245 ///
246 /// Error handling:
247 ///
248 /// ```
249 /// use std::cell::RefCell;
250 ///
251 /// use magnus::{prelude::*, wrap, Error, Ruby};
252 ///
253 /// struct Point {
254 /// x: isize,
255 /// y: isize,
256 /// }
257 ///
258 /// #[wrap(class = "Point")]
259 /// struct MutPoint(RefCell<Point>);
260 ///
261 /// impl MutPoint {
262 /// fn add_x(ruby: &Ruby, rb_self: &Self, val: isize) -> Result<isize, Error> {
263 /// if let Some(sum) = rb_self.0.borrow().x.checked_add(val) {
264 /// rb_self.0.borrow_mut().x = sum;
265 /// Ok(sum)
266 /// } else {
267 /// return Err(Error::new(
268 /// ruby.exception_range_error(),
269 /// "result out of range",
270 /// ));
271 /// }
272 /// }
273 /// }
274 /// ```
275 ///
276 /// Wrapping an enum with subclasses:
277 ///
278 /// ```
279 /// use std::f64::consts::PI;
280 ///
281 /// use magnus::{function, method, prelude::*, wrap, Ruby};
282 ///
283 /// #[wrap(class = "Shape")]
284 /// enum Shape {
285 /// #[magnus(class = "Circle")]
286 /// Circle { r: f64 },
287 /// #[magnus(class = "Rectangle")]
288 /// Rectangle { x: f64, y: f64 },
289 /// }
290 ///
291 /// impl Shape {
292 /// fn area(&self) -> f64 {
293 /// match self {
294 /// Shape::Circle { r } => PI * r * r,
295 /// Shape::Rectangle { x, y } => x * y,
296 /// }
297 /// }
298 /// }
299 ///
300 /// #[magnus::init]
301 /// fn init(ruby: &Ruby) -> Result<(), magnus::Error> {
302 /// let shape = ruby.define_class("Shape", ruby.class_object())?;
303 /// shape.define_method("area", method!(Shape::area, 0))?;
304 ///
305 /// let circle = ruby.define_class("Circle", shape)?;
306 /// circle.define_singleton_method("new", function!(|r| Shape::Circle { r }, 1))?;
307 ///
308 /// let rectangle = ruby.define_class("Rectangle", shape)?;
309 /// rectangle.define_singleton_method("new", function!(|x, y| Shape::Rectangle { x, y }, 2))?;
310 ///
311 /// Ok(())
312 /// }
313 /// ```
314 ///
315 /// See [`examples/inheritance.rs`] for the complete example.
316 ///
317 /// [`examples/inheritance.rs`]: https://github.com/matsadler/magnus/blob/main/examples/inheritance.rs
318 #[proc_macro_attribute]
319 pub fn wrap(attrs: TokenStream, item: TokenStream) -> TokenStream {
320 typed_data::expand(parse_macro_input!(attrs), parse_macro_input!(item)).into()
321 }
322
323 /// Derives `DataTypeFunctions` with default implementations, for simple uses
324 /// of [`TypedData`].
325 ///
326 /// For cases where no custom `DataTypeFunctions` are required a default
327 /// implementation can be derived. The [`macro@wrap`] macro may be a simpler
328 /// alternative in this use case.
329 #[proc_macro_derive(DataTypeFunctions)]
330 pub fn derive_data_type_functions(input: TokenStream) -> TokenStream {
331 typed_data::expand_derive_data_type_functions(parse_macro_input!(input)).into()
332 }
333
334 /// Derives `TypedData`, allowing a Rust type to be passed to Ruby and
335 /// automatically wrapped as a Ruby object.
336 ///
337 /// For simpler use cases, consider using [`macro@wrap`].
338 ///
339 /// # Attributes
340 ///
341 /// The `#[magnus(...)]` attribute supports the following values to configure
342 /// its behavior:
343 ///
344 /// * `class = "..."` (required):
345 /// Specifies the Ruby class associated with the Rust type. Supports module
346 /// paths, such as `Foo::Bar::Baz`.
347 ///
348 /// * `name = "..."`:
349 /// Specifies a debug name for the type. This name must be unique and
350 /// defaults to the class name if not explicitly provided.
351 ///
352 /// * `free_immediately`:
353 /// Indicates that the Rust type should be dropped as soon as the Ruby object
354 /// is garbage collected. This is only safe if the type's [`Drop`] and
355 /// `DataTypeFunctions::free` implementations do not call Ruby.
356 /// If safe this should be enabled as this performs better and is more
357 /// memory efficient.
358 ///
359 /// * `mark`:
360 /// Enables Ruby to call the `DataTypeFunctions::mark` function.
361 ///
362 /// * `size`:
363 /// Enables Ruby to call the `DataTypeFunctions::size` function.
364 ///
365 /// * `compact`:
366 /// Enables Ruby to call the `DataTypeFunctions::compact` function.
367 ///
368 /// * `wb_protected`:
369 /// Enable the 'write barrier protected' flag.
370 ///
371 /// Types that contain Ruby values by default do not participate in
372 /// generational GC (they are scanned every GC). This flag asserts all
373 /// operations that write Ruby values to this type are protected with
374 /// write barriers (see `typed_data::Writebarrier::writebarrier`) so this
375 /// type can participate in generational GC.
376 ///
377 /// The write barrier is hard to get right. Magnus recommends you do not use
378 /// this flag.
379 ///
380 /// * `frozen_shareable`:
381 /// Sets the `frozen_shareable` flag for objects that can be safely accessed
382 /// concurrently from multiple threads when frozen. This allows objects to
383 /// shared between Ractors.
384 ///
385 /// * `unsafe_generics`:
386 /// Disables compile-time checks for types with generics, allowing their use
387 /// with `#[magnus(...)]`. Use this only if you are confident the derived
388 /// implementation is correct for your generic type.
389 ///
390 /// # Field Attributes
391 ///
392 /// The `#[magnus(...)]` attribute can be set on struct fields with the
393 /// following values:
394 ///
395 /// * `opaque_attr_reader`:
396 /// For a Ruby value wrapped in `Opaque`, creates an accessor method that
397 /// returns the unwrapped Ruby value.
398 ///
399 /// # Variant Attributes
400 ///
401 /// The `#[magnus(...)]` attribute can be set on enum variants with the
402 /// following values:
403 ///
404 /// * `class = "..."`:
405 /// Specifies the Ruby class associated with the variant. Supports module
406 /// paths, such as `Foo::Bar::Baz`.
407 ///
408 /// # Examples
409 ///
410 /// Wrapping a struct
411 ///
412 /// ```
413 /// use magnus::{function, prelude::*, DataTypeFunctions, Ruby, TypedData};
414 ///
415 /// #[derive(DataTypeFunctions, TypedData)]
416 /// #[magnus(class = "Point", size, free_immediately)]
417 /// struct Point {
418 /// x: isize,
419 /// y: isize,
420 /// }
421 ///
422 /// // wraps `Point` struct in a Ruby `Point` object when returned to Ruby.
423 /// fn point(x: isize, y: isize) -> Point {
424 /// Point { x, y }
425 /// }
426 ///
427 /// // automatically unwraps `Point` objects to references to `Point`` structs
428 /// // when invoking the function.
429 /// fn distance(a: &Point, b: &Point) -> f64 {
430 /// (((b.x - a.x).pow(2) + (b.y - a.y).pow(2)) as f64).sqrt()
431 /// }
432 ///
433 /// #[magnus::init]
434 /// fn init(ruby: &Ruby) {
435 /// ruby.define_global_function("point", function!(point, 2));
436 /// ruby.define_global_function("distance", function!(distance, 2));
437 /// }
438 /// ```
439 ///
440 /// Wrapping an enum with subclasses:
441 ///
442 /// ```
443 /// use magnus::{class, prelude::*, wrap, Error, Ruby};
444 ///
445 /// #[wrap(class = "Shape")]
446 /// enum Shape {
447 /// #[magnus(class = "Circle")]
448 /// Circle { r: f64 },
449 /// #[magnus(class = "Rectangle")]
450 /// Rectangle { x: f64, y: f64 },
451 /// }
452 ///
453 /// #[magnus::init]
454 /// fn init(ruby: &Ruby) -> Result<(), Error> {
455 /// let shape = ruby.define_class("Shape", ruby.class_object())?;
456 /// ruby.define_class("Circle", shape)?;
457 /// ruby.define_class("Rectangle", shape)?;
458 /// Ok(())
459 /// }
460 /// ```
461 ///
462 /// Custom `DataTypeFunctions` implementation:
463 ///
464 /// ```
465 /// use std::mem::size_of_val;
466 ///
467 /// use magnus::{DataTypeFunctions, TypedData};
468 ///
469 /// #[derive(TypedData)]
470 /// #[magnus(class = "Name", size, free_immediately)]
471 /// struct Name {
472 /// first: String,
473 /// last: String,
474 /// }
475 ///
476 /// impl DataTypeFunctions for Name {
477 /// fn size(&self) -> usize {
478 /// size_of_val(&self.first) + size_of_val(&self.last)
479 /// }
480 /// }
481 /// ```
482 ///
483 /// Struct containing Ruby values:
484 ///
485 /// ```
486 /// use magnus::{
487 /// class, function, gc, method, prelude::*, typed_data::Obj, value::Opaque, DataTypeFunctions,
488 /// Ruby, TypedData,
489 /// };
490 ///
491 /// #[derive(DataTypeFunctions, TypedData)]
492 /// #[magnus(class = "Point", size, free_immediately)]
493 /// struct Point {
494 /// x: isize,
495 /// y: isize,
496 /// }
497 ///
498 /// #[derive(TypedData)]
499 /// #[magnus(class = "Line", free_immediately, mark)]
500 /// struct Line {
501 /// #[magnus(opaque_attr_reader)]
502 /// start: Opaque<Obj<Point>>,
503 /// #[magnus(opaque_attr_reader)]
504 /// end: Opaque<Obj<Point>>,
505 /// }
506 ///
507 /// impl Line {
508 /// fn new(start: Obj<Point>, end: Obj<Point>) -> Self {
509 /// Self {
510 /// start: start.into(),
511 /// end: end.into(),
512 /// }
513 /// }
514 ///
515 /// fn length(&self) -> f64 {
516 /// let start = self.start();
517 /// let end = self.end();
518 ///
519 /// (((end.x - start.x).pow(2) + (end.y - start.y).pow(2)) as f64).sqrt()
520 /// }
521 /// }
522 ///
523 /// impl DataTypeFunctions for Line {
524 /// fn mark(&self, marker: &gc::Marker) {
525 /// marker.mark(self.start);
526 /// marker.mark(self.end);
527 /// }
528 /// }
529 ///
530 /// #[magnus::init]
531 /// fn init(ruby: &Ruby) -> Result<(), magnus::Error> {
532 /// let line = ruby.define_class("Line", ruby.class_object())?;
533 /// line.define_singleton_method("new", function!(Line::new, 2))?;
534 /// line.define_method("length", method!(Line::length, 0))?;
535 /// Ok(())
536 /// }
537 /// ```
538 #[proc_macro_derive(TypedData, attributes(magnus))]
539 pub fn derive_typed_data(input: TokenStream) -> TokenStream {
540 match typed_data::expand_derive_typed_data(parse_macro_input!(input)) {
541 Ok(tokens) => tokens,
542 Err(e) => e.into_compile_error(),
543 }
544 .into()
545 }