glib_macros/
lib.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3mod async_test;
4mod boxed_derive;
5mod clone;
6mod clone_old;
7mod closure;
8mod closure_old;
9mod derived_properties_attribute;
10mod downgrade_derive;
11mod enum_derive;
12mod error_domain_derive;
13mod flags_attribute;
14mod object_impl_attributes;
15mod properties;
16mod shared_boxed_derive;
17mod value_delegate_derive;
18mod variant_derive;
19
20mod utils;
21
22use flags_attribute::AttrInput;
23use proc_macro::{TokenStream, TokenTree};
24use proc_macro2::Span;
25use syn::{parse_macro_input, DeriveInput};
26use utils::{parse_nested_meta_items_from_stream, NestedMetaItem};
27
28/// Macro for passing variables as strong or weak references into a closure.
29///
30/// This macro can be useful in combination with closures, e.g. signal handlers, to reduce the
31/// boilerplate required for passing strong or weak references into the closure. It will
32/// automatically create the new reference and pass it with the same name into the closure.
33///
34/// If upgrading the weak reference to a strong reference inside the closure is failing, the
35/// closure is immediately returning an optional default return value. If none is provided, `()` is
36/// returned.
37///
38/// **⚠️ IMPORTANT ⚠️**
39///
40/// `glib` needs to be in scope, so unless it's one of the direct crate dependencies, you need to
41/// import it because `clone!` is using it. For example:
42///
43/// ```rust,ignore
44/// use gtk::glib;
45/// ```
46///
47/// ### Debugging
48///
49/// In case something goes wrong inside the `clone!` macro, we use the [`g_debug`] macro. Meaning
50/// that if you want to see these debug messages, you'll have to set the `G_MESSAGES_DEBUG`
51/// environment variable when running your code (either in the code directly or when running the
52/// binary) to either "all" or [`CLONE_MACRO_LOG_DOMAIN`]:
53///
54/// [`g_debug`]: ../glib/macro.g_debug.html
55/// [`CLONE_MACRO_LOG_DOMAIN`]: ../glib/constant.CLONE_MACRO_LOG_DOMAIN.html
56///
57/// ```rust,ignore
58/// use glib::CLONE_MACRO_LOG_DOMAIN;
59///
60/// std::env::set_var("G_MESSAGES_DEBUG", CLONE_MACRO_LOG_DOMAIN);
61/// std::env::set_var("G_MESSAGES_DEBUG", "all");
62/// ```
63///
64/// Or:
65///
66/// ```bash
67/// $ G_MESSAGES_DEBUG=all ./binary
68/// ```
69///
70/// ### Passing a strong reference
71///
72/// ```
73/// use glib;
74/// use glib_macros::clone;
75/// use std::rc::Rc;
76///
77/// let v = Rc::new(1);
78/// let closure = clone!(
79///     #[strong] v,
80///     move |x| {
81///         println!("v: {}, x: {}", v, x);
82///     },
83/// );
84///
85/// closure(2);
86/// ```
87///
88/// ### Passing a weak reference
89///
90/// ```
91/// use glib;
92/// use glib_macros::clone;
93/// use std::rc::Rc;
94///
95/// let u = Rc::new(2);
96/// let closure = clone!(
97///     #[weak]
98///     u,
99///     move |x| {
100///         println!("u: {}, x: {}", u, x);
101///     },
102/// );
103///
104/// closure(3);
105/// ```
106///
107/// #### Allowing a nullable weak reference
108///
109/// In some cases, even if the weak references can't be retrieved, you might want to still have
110/// your closure called. In this case, you need to use `#[weak_allow_none]` instead of `#[weak]`:
111///
112/// ```
113/// use glib;
114/// use glib_macros::clone;
115/// use std::rc::Rc;
116///
117/// let closure = {
118///     // This `Rc` won't be available in the closure because it's dropped at the end of the
119///     // current block
120///     let u = Rc::new(2);
121///     clone!(
122///         #[weak_allow_none]
123///         u,
124///         move |x| {
125///             // We need to use a Debug print for `u` because it'll be an `Option`.
126///             println!("u: {:?}, x: {}", u, x);
127///             true
128///         },
129///     )
130/// };
131///
132/// assert_eq!(closure(3), true);
133/// ```
134///
135/// ### Creating owned values from references (`ToOwned`)
136///
137/// ```
138/// use glib;
139/// use glib_macros::clone;
140///
141/// let v = "123";
142/// let closure = clone!(
143///     #[to_owned] v,
144///     move |x| {
145///         // v is passed as `String` here
146///         println!("v: {}, x: {}", v, x);
147///     },
148/// );
149///
150/// closure(2);
151/// ```
152///
153/// ### Renaming variables
154///
155/// ```
156/// use glib;
157/// use glib_macros::clone;
158/// use std::rc::Rc;
159///
160/// let v = Rc::new(1);
161/// let u = Rc::new(2);
162/// let closure = clone!(
163///     #[strong(rename_to = y)]
164///     v,
165///     #[weak] u,
166///     move |x| {
167///         println!("v as y: {}, u: {}, x: {}", y, u, x);
168///     },
169/// );
170///
171/// closure(3);
172/// ```
173///
174/// ### Providing a return value if upgrading a weak reference fails
175///
176/// By default, `()` is returned if upgrading a weak reference fails. This behaviour can be
177/// adjusted in two different ways:
178///
179/// Either by providing the value yourself using one of
180///
181///   * `#[upgrade_or]`: Requires an expression that returns a `Copy` value of the expected return type,
182///   * `#[upgrade_or_else]`: Requires a closure that returns a value of the expected return type,
183///   * `#[upgrade_or_default]`: Requires that the return type implements `Default` and returns that.
184///
185/// ```
186/// use glib;
187/// use glib_macros::clone;
188/// use std::rc::Rc;
189///
190/// let v = Rc::new(1);
191/// let closure = clone!(
192///     #[weak] v,
193///     #[upgrade_or]
194///     false,
195///     move |x| {
196///         println!("v: {}, x: {}", v, x);
197///         true
198///     },
199/// );
200///
201/// // Drop value so that the weak reference can't be upgraded.
202/// drop(v);
203///
204/// assert_eq!(closure(2), false);
205/// ```
206///
207/// Or by using `#[upgrade_or_panic]`: If the value fails to get upgraded, it'll panic.
208///
209/// ```should_panic
210/// # use glib;
211/// # use glib_macros::clone;
212/// # use std::rc::Rc;
213/// # let v = Rc::new(1);
214/// let closure = clone!(
215///     #[weak] v,
216///     #[upgrade_or_panic]
217///     move |x| {
218///         println!("v: {}, x: {}", v, x);
219///         true
220///     },
221/// );
222/// # drop(v);
223/// # assert_eq!(closure(2), false);
224/// ```
225///
226/// ### Errors
227///
228/// Here is a list of errors you might encounter:
229///
230/// **Missing `#[weak]` or `#[strong]`**:
231///
232/// ```compile_fail
233/// # use glib;
234/// # use glib_macros::clone;
235/// # use std::rc::Rc;
236/// let v = Rc::new(1);
237///
238/// let closure = clone!(
239///     v,
240///     move |x| println!("v: {}, x: {}", v, x),
241/// );
242/// # drop(v);
243/// # closure(2);
244/// ```
245///
246/// **Passing `self` as an argument**:
247///
248/// ```compile_fail
249/// # use glib;
250/// # use glib_macros::clone;
251/// # use std::rc::Rc;
252/// #[derive(Debug)]
253/// struct Foo;
254///
255/// impl Foo {
256///     fn foo(&self) {
257///         let closure = clone!(
258///             #[strong] self,
259///             move |x| {
260///                 println!("self: {:?}", self);
261///             },
262///         );
263///         # closure(2);
264///     }
265/// }
266/// ```
267///
268/// If you want to use `self` directly, you'll need to rename it:
269///
270/// ```
271/// # use glib;
272/// # use glib_macros::clone;
273/// # use std::rc::Rc;
274/// #[derive(Debug)]
275/// struct Foo;
276///
277/// impl Foo {
278///     fn foo(&self) {
279///         let closure = clone!(
280///             #[strong(rename_to = this)]
281///             self,
282///             move |x| {
283///                 println!("self: {:?}", this);
284///             },
285///         );
286///         # closure(2);
287///     }
288/// }
289/// ```
290///
291/// **Passing fields directly**
292///
293/// ```compile_fail
294/// # use glib;
295/// # use glib_macros::clone;
296/// # use std::rc::Rc;
297/// #[derive(Debug)]
298/// struct Foo {
299///     v: Rc<usize>,
300/// }
301///
302/// impl Foo {
303///     fn foo(&self) {
304///         let closure = clone!(
305///             #[strong] self.v,
306///             move |x| {
307///                 println!("self.v: {:?}", v);
308///             },
309///         );
310///         # closure(2);
311///     }
312/// }
313/// ```
314///
315/// You can do it by renaming it:
316///
317/// ```
318/// # use glib;
319/// # use glib_macros::clone;
320/// # use std::rc::Rc;
321/// # struct Foo {
322/// #     v: Rc<usize>,
323/// # }
324/// impl Foo {
325///     fn foo(&self) {
326///         let closure = clone!(
327///             #[strong(rename_to = v)]
328///             self.v,
329///             move |x| {
330///                 println!("self.v: {}", v);
331///             },
332///         );
333///         # closure(2);
334///     }
335/// }
336/// ```
337#[proc_macro]
338pub fn clone(item: TokenStream) -> TokenStream {
339    // Check if this is an old-style clone macro invocation.
340    // These always start with an '@' punctuation.
341    let Some(first) = item.clone().into_iter().next() else {
342        return syn::Error::new(Span::call_site(), "expected a closure or async block")
343            .to_compile_error()
344            .into();
345    };
346
347    match first {
348        TokenTree::Punct(ref p) if p.to_string() == "@" => clone_old::clone_inner(item),
349        _ => clone::clone_inner(item),
350    }
351}
352
353/// Macro for creating a [`Closure`] object. This is a wrapper around [`Closure::new`] that
354/// automatically type checks its arguments at run-time.
355///
356/// A `Closure` takes [`Value`] objects as inputs and output. This macro will automatically convert
357/// the inputs to Rust types when invoking its callback, and then will convert the output back to a
358/// `Value`. All inputs must implement the [`FromValue`] trait, and outputs must either implement
359/// the [`ToValue`] trait or be the unit type `()`. Type-checking of inputs is done at run-time; if
360/// incorrect types are passed via [`Closure::invoke`] then the closure will panic. Note that when
361/// passing input types derived from [`Object`] or [`Interface`], you must take care to upcast to
362/// the exact object or interface type that is being received.
363///
364/// Similarly to [`clone!`](crate::clone!), this macro can be useful in combination with signal
365/// handlers to reduce boilerplate when passing references. Unique to `Closure` objects is the
366/// ability to watch an object using the `#[watch]` attribute. Only an [`Object`] value can be
367/// passed to `#[watch]`, and only one object can be watched per closure. When an object is watched,
368/// a weak reference to the object is held in the closure. When the object is destroyed, the
369/// closure will become invalidated: all signal handlers connected to the closure will become
370/// disconnected, and any calls to [`Closure::invoke`] on the closure will be silently ignored.
371/// Internally, this is accomplished using [`Object::watch_closure`] on the watched object.
372///
373/// The `#[weak]`, `#[weak_allow_none]`, `#[strong]`, `#[to_owned]` captures are also supported and
374/// behave the same as in [`clone!`](crate::clone!), as is aliasing captures via `rename_to`.
375/// Similarly, upgrade failure of weak references can be adjusted via `#[upgrade_or]`,
376/// `#[upgrade_or_else]`, `#[upgrade_or_default]` and `#[upgrade_or_panic]`.
377///
378/// Notably, these captures are able to reference `Rc` and `Arc` values in addition to `Object`
379/// values.
380///
381/// [`Closure`]: ../glib/closure/struct.Closure.html
382/// [`Closure::new`]: ../glib/closure/struct.Closure.html#method.new
383/// [`Closure::new_local`]: ../glib/closure/struct.Closure.html#method.new_local
384/// [`Closure::invoke`]: ../glib/closure/struct.Closure.html#method.invoke
385/// [`Value`]: ../glib/value/struct.Value.html
386/// [`FromValue`]: ../glib/value/trait.FromValue.html
387/// [`ToValue`]: ../glib/value/trait.ToValue.html
388/// [`Interface`]: ../glib/object/struct.Interface.html
389/// [`Object`]: ../glib/object/struct.Object.html
390/// [`Object::watch_closure`]: ../glib/object/trait.ObjectExt.html#tymethod.watch_closure
391/// **⚠️ IMPORTANT ⚠️**
392///
393/// `glib` needs to be in scope, so unless it's one of the direct crate dependencies, you need to
394/// import it because `closure!` is using it. For example:
395///
396/// ```rust,ignore
397/// use gtk::glib;
398/// ```
399///
400/// ### Using as a closure object
401///
402/// ```
403/// use glib_macros::closure;
404///
405/// let concat_str = closure!(|s: &str| s.to_owned() + " World");
406/// let result = concat_str.invoke::<String>(&[&"Hello"]);
407/// assert_eq!(result, "Hello World");
408/// ```
409///
410/// ### Connecting to a signal
411///
412/// For wrapping closures that can't be sent across threads, the
413/// [`closure_local!`](crate::closure_local!) macro can be used. It has the same syntax as
414/// `closure!`, but instead uses [`Closure::new_local`] internally.
415///
416/// ```
417/// use glib;
418/// use glib::prelude::*;
419/// use glib_macros::closure_local;
420///
421/// let obj = glib::Object::new::<glib::Object>();
422/// obj.connect_closure(
423///     "notify", false,
424///     closure_local!(|_obj: glib::Object, pspec: glib::ParamSpec| {
425///         println!("property notify: {}", pspec.name());
426///     }));
427/// ```
428///
429/// ### Object Watching
430///
431/// ```
432/// use glib;
433/// use glib::prelude::*;
434/// use glib_macros::closure_local;
435///
436/// let closure = {
437///     let obj = glib::Object::new::<glib::Object>();
438///     let closure = closure_local!(
439///         #[watch] obj,
440///         move || {
441///             obj.type_().name()
442///         },
443///     );
444///     assert_eq!(closure.invoke::<String>(&[]), "GObject");
445///     closure
446/// };
447/// // `obj` is dropped, closure invalidated so it always does nothing and returns None
448/// closure.invoke::<()>(&[]);
449/// ```
450///
451/// `#[watch]` has special behavior when connected to a signal:
452///
453/// ```
454/// use glib;
455/// use glib::prelude::*;
456/// use glib_macros::closure_local;
457///
458/// let obj = glib::Object::new::<glib::Object>();
459/// {
460///     let other = glib::Object::new::<glib::Object>();
461///     obj.connect_closure(
462///         "notify", false,
463///         closure_local!(
464///             #[watch(rename_to = b)]
465///             other,
466///             move |a: glib::Object, pspec: glib::ParamSpec| {
467///                 let value = a.property_value(pspec.name());
468///                 b.set_property(pspec.name(), &value);
469///             },
470///         ),
471///     );
472///     // The signal handler will disconnect automatically at the end of this
473///     // block when `other` is dropped.
474/// }
475/// ```
476///
477/// ### Weak and Strong References
478///
479/// ```
480/// use glib;
481/// use glib::prelude::*;
482/// use glib_macros::closure;
483/// use std::sync::Arc;
484///
485/// let closure = {
486///     let a = Arc::new(String::from("Hello"));
487///     let b = Arc::new(String::from("World"));
488///     let c = "!";
489///     let closure = closure!(
490///         #[strong] a,
491///         #[weak_allow_none]
492///         b,
493///         #[to_owned]
494///         c,
495///         move || {
496///             // `a` is Arc<String>, `b` is Option<Arc<String>>, `c` is a `String`
497///             format!("{} {}{}", a, b.as_ref().map(|b| b.as_str()).unwrap_or_else(|| "Moon"), c)
498///         },
499///     );
500///     assert_eq!(closure.invoke::<String>(&[]), "Hello World!");
501///     closure
502/// };
503/// // `a`, `c` still kept alive, `b` is dropped
504/// assert_eq!(closure.invoke::<String>(&[]), "Hello Moon!");
505/// ```
506#[proc_macro]
507pub fn closure(item: TokenStream) -> TokenStream {
508    // Check if this is an old-style closure macro invocation.
509    // These always start with an '@' punctuation.
510    let Some(first) = item.clone().into_iter().next() else {
511        return syn::Error::new(Span::call_site(), "expected a closure")
512            .to_compile_error()
513            .into();
514    };
515
516    match first {
517        TokenTree::Punct(ref p) if p.to_string() == "@" => closure_old::closure_inner(item, "new"),
518        _ => closure::closure_inner(item, "new"),
519    }
520}
521
522/// The same as [`closure!`](crate::closure!) but uses [`Closure::new_local`] as a constructor.
523/// This is useful for closures which can't be sent across threads. See the documentation of
524/// [`closure!`](crate::closure!) for details.
525///
526/// [`Closure::new_local`]: ../glib/closure/struct.Closure.html#method.new_local
527#[proc_macro]
528pub fn closure_local(item: TokenStream) -> TokenStream {
529    // Check if this is an old-style closure macro invocation.
530    // These always start with an '@' punctuation.
531    let Some(first) = item.clone().into_iter().next() else {
532        return syn::Error::new(Span::call_site(), "expected a closure")
533            .to_compile_error()
534            .into();
535    };
536
537    match first {
538        TokenTree::Punct(ref p) if p.to_string() == "@" => {
539            closure_old::closure_inner(item, "new_local")
540        }
541        _ => closure::closure_inner(item, "new_local"),
542    }
543}
544
545/// Derive macro to register a Rust enum in the GLib type system and derive the
546/// [`glib::Value`] traits.
547///
548/// # Example
549///
550/// ```
551/// use glib::prelude::*;
552/// use glib::subclass::prelude::*;
553///
554/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
555/// #[enum_type(name = "MyEnum")]
556/// enum MyEnum {
557///     Val,
558///     #[enum_value(name = "My Val")]
559///     ValWithCustomName,
560///     #[enum_value(name = "My Other Val", nick = "other")]
561///     ValWithCustomNameAndNick,
562/// }
563/// ```
564///
565/// An enum can be registered as a dynamic type by setting the derive macro
566/// helper attribute `enum_dynamic`:
567///
568/// ```ignore
569/// use glib::prelude::*;
570/// use glib::subclass::prelude::*;
571///
572/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
573/// #[enum_type(name = "MyEnum")]
574/// #[enum_dynamic]
575/// enum MyEnum {
576///     ...
577/// }
578/// ```
579///
580/// As a dynamic type, an enum must be explicitly registered when the system
581/// loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
582/// Therefore, whereas an enum can be registered only once as a static type,
583/// it can be registered several times as a dynamic type.
584///
585/// An enum registered as a dynamic type is never unregistered. The system
586/// calls [`TypePluginExt::unuse`] to unload the implementation. If the
587/// [`TypePlugin`] subclass is a [`TypeModule`], the enum registered as a
588/// dynamic type is marked as unloaded and must be registered again when the
589/// module is reloaded.
590///
591/// The derive macro helper attribute `enum_dynamic` provides two behaviors
592/// when registering an enum as a dynamic type:
593///
594/// - lazy registration: by default an enum is registered as a dynamic type
595///   when the system loads the implementation (e.g. when the module is loaded).
596///   Optionally setting `lazy_registration` to `true` postpones registration on
597///   the first use (when `static_type()` is called for the first time):
598///
599/// ```ignore
600/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
601/// #[enum_type(name = "MyEnum")]
602/// #[enum_dynamic(lazy_registration = true)]
603/// enum MyEnum {
604///     ...
605/// }
606/// ```
607///
608/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
609///   subclass: an enum is usually registered as a dynamic type within a
610///   [`TypeModule`] subclass:
611///
612/// ```ignore
613/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
614/// #[enum_type(name = "MyModuleEnum")]
615/// #[enum_dynamic]
616/// enum MyModuleEnum {
617///     ...
618/// }
619/// ...
620/// #[derive(Default)]
621/// pub struct MyModule;
622/// ...
623/// impl TypeModuleImpl for MyModule {
624///     fn load(&self) -> bool {
625///         // registers enums as dynamic types.
626///         let my_module = self.obj();
627///         let type_module: &glib::TypeModule = my_module.upcast_ref();
628///         MyModuleEnum::on_implementation_load(type_module)
629///     }
630///     ...
631/// }
632/// ```
633///
634/// Optionally setting `plugin_type` allows to register an enum as a dynamic
635/// type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
636///
637/// ```ignore
638/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
639/// #[enum_type(name = "MyPluginEnum")]
640/// #[enum_dynamic(plugin_type = MyPlugin)]
641/// enum MyPluginEnum {
642///     ...
643/// }
644/// ...
645/// #[derive(Default)]
646/// pub struct MyPlugin;
647/// ...
648/// impl TypePluginImpl for MyPlugin {
649///     fn use_plugin(&self) {
650///         // register enums as dynamic types.
651///         let my_plugin = self.obj();
652///         MyPluginEnum::on_implementation_load(my_plugin.as_ref());
653///     }
654///     ...
655/// }
656/// ```
657///
658/// [`glib::Value`]: ../glib/value/struct.Value.html
659/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
660/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
661/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.
662#[proc_macro_derive(Enum, attributes(enum_type, enum_dynamic, enum_value))]
663pub fn enum_derive(input: TokenStream) -> TokenStream {
664    let input = parse_macro_input!(input as DeriveInput);
665    enum_derive::impl_enum(&input)
666        .unwrap_or_else(syn::Error::into_compile_error)
667        .into()
668}
669
670/// Attribute macro for defining flags using the `bitflags` crate.
671/// This macro will also define a `GFlags::type_` function and
672/// the [`glib::Value`] traits.
673///
674/// The expected `GType` name has to be passed as macro attribute.
675/// The name and nick of each flag can also be optionally defined.
676/// Default name is the flag identifier in CamelCase and default nick
677/// is the identifier in kebab-case.
678/// Combined flags should not be registered with the `GType` system
679/// and so need to be tagged with the `#[flags_value(skip)]` attribute.
680///
681/// # Example
682///
683/// ```
684/// use glib::prelude::*;
685/// use glib::subclass::prelude::*;
686///
687/// #[glib::flags(name = "MyFlags")]
688/// enum MyFlags {
689///     #[flags_value(name = "Flag A", nick = "nick-a")]
690///     A = 0b00000001,
691///     #[flags_value(name = "Flag B")]
692///     B = 0b00000010,
693///     #[flags_value(skip)]
694///     AB = Self::A.bits() | Self::B.bits(),
695///     C = 0b00000100,
696/// }
697/// ```
698///
699/// The flags can be registered as a dynamic type by setting the macro helper
700/// attribute `flags_dynamic`:
701/// ```ignore
702/// use glib::prelude::*;
703/// use glib::subclass::prelude::*;
704///
705/// #[glib::flags(name = "MyFlags")]
706/// #[flags_dynamic]
707/// enum MyFlags {
708///     ...
709/// }
710/// ```
711///
712/// As a dynamic type, the flags must be explicitly registered when the system
713/// loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
714/// Therefore, whereas the flags can be registered only once as a static type,
715/// they can be registered several times as a dynamic type.
716///
717/// The flags registered as a dynamic type are never unregistered. The system
718/// calls [`TypePluginExt::unuse`] to unload the implementation. If the
719/// [`TypePlugin`] subclass is a [`TypeModule`], the flags registered as a
720/// dynamic type are marked as unloaded and must be registered again when the
721/// module is reloaded.
722///
723/// The macro helper attribute `flags_dynamic` provides two behaviors when
724/// registering the flags as a dynamic type:
725///
726/// - lazy registration: by default the flags are registered as a dynamic type
727///   when the system loads the implementation (e.g. when the module is loaded).
728///   Optionally setting `lazy_registration` to `true` postpones registration on
729///   the first use (when `static_type()` is called for the first time):
730///
731/// ```ignore
732/// #[glib::flags(name = "MyFlags")]
733/// #[flags_dynamic(lazy_registration = true)]
734/// enum MyFlags {
735///     ...
736/// }
737/// ```
738///
739/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
740///   subclass: the flags are usually registered as a dynamic type within a
741///   [`TypeModule`] subclass:
742///
743/// ```ignore
744/// #[glib::flags(name = "MyModuleFlags")]
745/// #[flags_dynamic]
746/// enum MyModuleFlags {
747///     ...
748/// }
749/// ...
750/// #[derive(Default)]
751/// pub struct MyModule;
752/// ...
753/// impl TypeModuleImpl for MyModule {
754///     fn load(&self) -> bool {
755///         // registers flags as dynamic types.
756///         let my_module = self.obj();
757///         let type_module: &glib::TypeModule = my_module.upcast_ref();
758///         MyModuleFlags::on_implementation_load(type_module)
759///     }
760///     ...
761/// }
762/// ```
763///
764/// Optionally setting `plugin_type` allows to register the flags as a dynamic
765/// type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
766/// ```ignore
767/// #[glib::flags(name = "MyModuleFlags")]
768/// #[flags_dynamic(plugin_type = MyPlugin)]
769/// enum MyModuleFlags {
770///     ...
771/// }
772/// ...
773/// #[derive(Default)]
774/// pub struct MyPlugin;
775/// ...
776/// impl TypePluginImpl for MyPlugin {
777///     fn use_plugin(&self) {
778///         // register flags as dynamic types.
779///         let my_plugin = self.obj();
780///         MyPluginFlags::on_implementation_load(my_plugin.as_ref());
781///     }
782///     ...
783/// }
784/// ```
785///
786/// [`glib::Value`]: ../glib/value/struct.Value.html
787/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
788/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
789/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.
790#[proc_macro_attribute]
791pub fn flags(attr: TokenStream, item: TokenStream) -> TokenStream {
792    let mut name = NestedMetaItem::<syn::LitStr>::new("name")
793        .required()
794        .value_required();
795    let mut allow_name_conflict_attr =
796        NestedMetaItem::<syn::LitBool>::new("allow_name_conflict").value_optional();
797
798    if let Err(e) = parse_nested_meta_items_from_stream(
799        attr.into(),
800        &mut [&mut name, &mut allow_name_conflict_attr],
801    ) {
802        return e.to_compile_error().into();
803    }
804
805    let allow_name_conflict = allow_name_conflict_attr.found
806        || allow_name_conflict_attr
807            .value
808            .map(|b| b.value())
809            .unwrap_or(false);
810
811    let attr_meta = AttrInput {
812        enum_name: name.value.unwrap(),
813        allow_name_conflict,
814    };
815
816    syn::parse::<syn::ItemEnum>(item)
817        .map_err(|_| syn::Error::new(Span::call_site(), flags_attribute::WRONG_PLACE_MSG))
818        .map(|mut input| flags_attribute::impl_flags(attr_meta, &mut input))
819        .unwrap_or_else(syn::Error::into_compile_error)
820        .into()
821}
822
823/// Derive macro for defining a GLib error domain and its associated
824/// [`ErrorDomain`] trait.
825///
826/// # Example
827///
828/// ```
829/// use glib::prelude::*;
830/// use glib::subclass::prelude::*;
831///
832/// #[derive(Debug, Copy, Clone, glib::ErrorDomain)]
833/// #[error_domain(name = "ex-foo")]
834/// enum Foo {
835///     Blah,
836///     Baaz,
837/// }
838/// ```
839///
840/// [`ErrorDomain`]: ../glib/error/trait.ErrorDomain.html
841#[proc_macro_derive(ErrorDomain, attributes(error_domain))]
842pub fn error_domain_derive(input: TokenStream) -> TokenStream {
843    let input = parse_macro_input!(input as DeriveInput);
844    error_domain_derive::impl_error_domain(&input)
845        .unwrap_or_else(syn::Error::into_compile_error)
846        .into()
847}
848
849/// Derive macro for defining a [`BoxedType`]`::type_` function and
850/// the [`glib::Value`] traits. Optionally, the type can be marked as
851/// `nullable` to get an implementation of `glib::value::ToValueOptional`.
852///
853/// # Example
854///
855/// ```
856/// use glib::prelude::*;
857/// use glib::subclass::prelude::*;
858///
859/// #[derive(Clone, Debug, PartialEq, Eq, glib::Boxed)]
860/// #[boxed_type(name = "MyBoxed")]
861/// struct MyBoxed(String);
862///
863/// #[derive(Clone, Debug, PartialEq, Eq, glib::Boxed)]
864/// #[boxed_type(name = "MyNullableBoxed", nullable)]
865/// struct MyNullableBoxed(String);
866/// ```
867///
868/// [`BoxedType`]: ../glib/subclass/boxed/trait.BoxedType.html
869/// [`glib::Value`]: ../glib/value/struct.Value.html
870#[proc_macro_derive(Boxed, attributes(boxed_type))]
871pub fn boxed_derive(input: TokenStream) -> TokenStream {
872    let input = parse_macro_input!(input as DeriveInput);
873    boxed_derive::impl_boxed(&input)
874        .unwrap_or_else(syn::Error::into_compile_error)
875        .into()
876}
877
878/// Derive macro for defining a [`SharedType`]`::get_type` function and
879/// the [`glib::Value`] traits. Optionally, the type can be marked as
880/// `nullable` to get an implementation of `glib::value::ToValueOptional`.
881///
882/// # Example
883///
884/// ```
885/// use glib::prelude::*;
886/// use glib::subclass::prelude::*;
887///
888/// #[derive(Clone, Debug, PartialEq, Eq)]
889/// struct MySharedInner {
890///   foo: String,
891/// }
892///
893/// #[derive(Clone, Debug, PartialEq, Eq, glib::SharedBoxed)]
894/// #[shared_boxed_type(name = "MySharedBoxed")]
895/// struct MySharedBoxed(std::sync::Arc<MySharedInner>);
896///
897/// #[derive(Clone, Debug, PartialEq, Eq, glib::SharedBoxed)]
898/// #[shared_boxed_type(name = "MyNullableSharedBoxed", nullable)]
899/// struct MyNullableSharedBoxed(std::sync::Arc<MySharedInner>);
900/// ```
901///
902/// [`SharedType`]: ../glib/subclass/shared/trait.SharedType.html
903/// [`glib::Value`]: ../glib/value/struct.Value.html
904#[proc_macro_derive(SharedBoxed, attributes(shared_boxed_type))]
905pub fn shared_boxed_derive(input: TokenStream) -> TokenStream {
906    let input = parse_macro_input!(input as DeriveInput);
907    shared_boxed_derive::impl_shared_boxed(&input)
908        .unwrap_or_else(syn::Error::into_compile_error)
909        .into()
910}
911
912/// Macro for boilerplate of [`ObjectSubclass`] implementations.
913///
914/// This adds implementations for the `type_data()` and `type_()` methods,
915/// which should probably never be defined differently.
916///
917/// It provides default values for the `Instance`, `Class`, and `Interfaces`
918/// type parameters. If these are present, the macro will use the provided value
919/// instead of the default.
920///
921/// Usually the defaults for `Instance` and `Class` will work. `Interfaces` is
922/// necessary for types that implement interfaces.
923///
924/// ```ignore
925/// type Instance = glib::subclass::basic::InstanceStruct<Self>;
926/// type Class = glib::subclass::basic::ClassStruct<Self>;
927/// type Interfaces = ();
928/// ```
929///
930/// If no `new()` or `with_class()` method is provided, the macro adds a `new()`
931/// implementation calling `Default::default()`. So the type needs to implement
932/// `Default`, or this should be overridden.
933///
934/// ```ignore
935/// fn new() -> Self {
936///     Default::default()
937/// }
938/// ```
939///
940/// An object subclass can be registered as a dynamic type by setting the macro
941/// helper attribute `object_class_dynamic`:
942///
943/// ```ignore
944/// #[derive(Default)]
945/// pub struct MyType;
946///
947/// #[glib::object_subclass]
948/// #[object_subclass_dynamic]
949/// impl ObjectSubclass for MyType { ... }
950/// ```
951///
952/// As a dynamic type, an object subclass must be explicitly registered when
953/// the system loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
954/// Therefore, whereas an object subclass can be registered only once as a
955/// static type, it can be registered several times as a dynamic type.
956///
957/// An object subclass registered as a dynamic type is never unregistered. The
958/// system calls [`TypePluginExt::unuse`] to unload the implementation. If the
959/// [`TypePlugin`] subclass is a [`TypeModule`], the object subclass registered
960/// as a dynamic type is marked as unloaded and must be registered again when
961/// the module is reloaded.
962///
963/// The macro helper attribute `object_class_dynamic` provides two behaviors
964/// when registering an object subclass as a dynamic type:
965///
966/// - lazy registration: by default an object subclass is registered as a
967///   dynamic type when the system loads the implementation (e.g. when the module
968///   is loaded). Optionally setting `lazy_registration` to `true` postpones
969///   registration on the first use (when `static_type()` is called for the first
970///   time):
971///
972/// ```ignore
973/// #[derive(Default)]
974/// pub struct MyType;
975///
976/// #[glib::object_subclass]
977/// #[object_subclass_dynamic(lazy_registration = true)]
978/// impl ObjectSubclass for MyType { ... }
979/// ```
980///
981/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
982///   subclass: an object subclass is usually registered as a dynamic type within
983///   a [`TypeModule`] subclass:
984///
985/// ```ignore
986/// #[derive(Default)]
987/// pub struct MyModuleType;
988///
989/// #[glib::object_subclass]
990/// #[object_subclass_dynamic]
991/// impl ObjectSubclass for MyModuleType { ... }
992/// ...
993/// #[derive(Default)]
994/// pub struct MyModule;
995/// ...
996/// impl TypeModuleImpl for MyModule {
997///     fn load(&self) -> bool {
998///         // registers object subclasses as dynamic types.
999///         let my_module = self.obj();
1000///         let type_module: &glib::TypeModule = my_module.upcast_ref();
1001///         MyModuleType::on_implementation_load(type_module)
1002///     }
1003///     ...
1004/// }
1005/// ```
1006///
1007/// Optionally setting `plugin_type` allows to register an object subclass as a
1008/// dynamic type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
1009///
1010/// ```ignore
1011/// #[derive(Default)]
1012/// pub struct MyPluginType;
1013///
1014/// #[glib::object_subclass]
1015/// #[object_subclass_dynamic(plugin_type = MyPlugin)]
1016/// impl ObjectSubclass for MyPluginType { ... }
1017/// ...
1018/// #[derive(Default)]
1019/// pub struct MyPlugin;
1020/// ...
1021/// impl TypePluginImpl for MyPlugin {
1022///     fn use_plugin(&self) {
1023///         // register object subclasses as dynamic types.
1024///         let my_plugin = self.obj();
1025///         MyPluginType::on_implementation_load(my_plugin.as_ref());
1026///     }
1027///     ...
1028/// }
1029/// ```
1030///
1031/// [`ObjectSubclass`]: ../glib/subclass/types/trait.ObjectSubclass.html
1032/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
1033/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
1034/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.html#method.unuse
1035#[proc_macro_attribute]
1036pub fn object_subclass(_attr: TokenStream, item: TokenStream) -> TokenStream {
1037    let input = parse_macro_input!(item with object_impl_attributes::Input::parse_subclass);
1038    object_impl_attributes::subclass::impl_object_subclass(input).into()
1039}
1040
1041/// Macro for boilerplate of [`ObjectInterface`] implementations.
1042///
1043/// This adds implementations for the `get_type()` method, which should probably never be defined
1044/// differently.
1045///
1046/// It provides default values for the `Prerequisites` type parameter. If this is present, the macro
1047/// will use the provided value instead of the default.
1048///
1049/// `Prerequisites` are interfaces for types that require a specific base class or interfaces.
1050///
1051/// ```ignore
1052/// type Prerequisites = ();
1053/// ```
1054///
1055/// An object interface can be registered as a dynamic type by setting the
1056/// macro helper attribute `object_interface_dynamic`:
1057/// ```ignore
1058/// pub struct MyInterface {
1059///     parent: glib::gobject_ffi::GTypeInterface,
1060/// }
1061/// #[glib::object_interface]
1062/// #[object_interface_dynamic]
1063/// unsafe impl ObjectInterface for MyInterface { ... }
1064/// ```
1065///
1066/// As a dynamic type, an object interface must be explicitly registered when
1067/// the system loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
1068/// Therefore, whereas an object interface can be registered only once as a
1069/// static type, it can be registered several times as a dynamic type.
1070///
1071/// An object interface registered as a dynamic type is never unregistered. The
1072/// system calls [`TypePluginExt::unuse`] to unload the implementation. If the
1073/// [`TypePlugin`] subclass is a [`TypeModule`], the object interface
1074/// registered as a dynamic type is marked as unloaded and must be registered
1075/// again when the module is reloaded.
1076///
1077/// The macro helper attribute `object_interface_dynamic` provides two
1078/// behaviors when registering an object interface as a dynamic type:
1079///
1080/// - lazy registration: by default an object interface is registered as a
1081///   dynamic type when the system loads the implementation (e.g. when the module
1082///   is loaded). Optionally setting `lazy_registration` to `true` postpones
1083///   registration on the first use (when `type_()` is called for the first time):
1084///
1085/// ```ignore
1086/// pub struct MyInterface {
1087///     parent: glib::gobject_ffi::GTypeInterface,
1088/// }
1089/// #[glib::object_interface]
1090/// #[object_interface_dynamic(lazy_registration = true)]
1091/// unsafe impl ObjectInterface for MyInterface { ... }
1092/// ```
1093///
1094/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
1095///   subclass: an object interface is usually registered as a dynamic type
1096///   within a [`TypeModule`] subclass:
1097///
1098/// ```ignore
1099/// pub struct MyModuleInterface {
1100///     parent: glib::gobject_ffi::GTypeInterface,
1101/// }
1102/// #[glib::object_interface]
1103/// #[object_interface_dynamic]
1104/// unsafe impl ObjectInterface for MyModuleInterface { ... }
1105/// ...
1106/// #[derive(Default)]
1107/// pub struct MyModule;
1108/// ...
1109/// impl TypeModuleImpl for MyModule {
1110///     fn load(&self) -> bool {
1111///         // registers object interfaces as dynamic types.
1112///         let my_module = self.obj();
1113///         let type_module: &glib::TypeModule = my_module.upcast_ref();
1114///         MyModuleInterface::on_implementation_load(type_module)
1115///     }
1116///     ...
1117/// }
1118/// ```
1119///
1120/// Optionally setting `plugin_type` allows to register an object interface as
1121/// a dynamic type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
1122///
1123/// ```ignore
1124/// pub struct MyPluginInterface {
1125///     parent: glib::gobject_ffi::GTypeInterface,
1126/// }
1127/// #[glib::object_interface]
1128/// #[object_interface_dynamic(plugin_type = MyPlugin)]
1129/// unsafe impl ObjectInterface for MyPluginInterface { ... }
1130/// ...
1131/// #[derive(Default)]
1132/// pub struct MyPlugin;
1133/// ...
1134/// impl TypePluginImpl for MyPlugin {
1135///     fn use_plugin(&self) {
1136///         // register object interfaces as dynamic types.
1137///         let my_plugin = self.obj();
1138///         MyPluginInterface::on_implementation_load(my_plugin.as_ref());
1139///     }
1140///     ...
1141/// }
1142/// ```
1143///
1144/// [`ObjectInterface`]: ../glib/subclass/interface/trait.ObjectInterface.html
1145/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
1146/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
1147/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.html#method.unuse///
1148#[proc_macro_attribute]
1149pub fn object_interface(_attr: TokenStream, item: TokenStream) -> TokenStream {
1150    let input = parse_macro_input!(item with object_impl_attributes::Input::parse_interface);
1151    object_impl_attributes::interface::impl_object_interface(input).into()
1152}
1153
1154/// Macro for deriving implementations of [`glib::clone::Downgrade`] and
1155/// [`glib::clone::Upgrade`] traits and a weak type.
1156///
1157/// # Examples
1158///
1159/// ## New Type Idiom
1160///
1161/// ```rust,ignore
1162/// #[derive(glib::Downgrade)]
1163/// pub struct FancyLabel(gtk::Label);
1164///
1165/// impl FancyLabel {
1166///     pub fn new(label: &str) -> Self {
1167///         Self(gtk::LabelBuilder::new().label(label).build())
1168///     }
1169///
1170///     pub fn flip(&self) {
1171///         self.0.set_angle(180.0 - self.0.angle());
1172///     }
1173/// }
1174///
1175/// let fancy_label = FancyLabel::new("Look at me!");
1176/// let button = gtk::ButtonBuilder::new().label("Click me!").build();
1177/// button.connect_clicked(
1178///     clone!(
1179///         #[weak]
1180///         fancy_label,
1181///         move || fancy_label.flip(),
1182///     ),
1183/// );
1184/// ```
1185///
1186/// ## Generic New Type
1187///
1188/// ```rust,ignore
1189/// #[derive(glib::Downgrade)]
1190/// pub struct TypedEntry<T>(gtk::Entry, std::marker::PhantomData<T>);
1191///
1192/// impl<T: ToString + FromStr> for TypedEntry<T> {
1193///     // ...
1194/// }
1195/// ```
1196///
1197/// ## Structures and Enums
1198///
1199/// ```rust,ignore
1200/// #[derive(Clone, glib::Downgrade)]
1201/// pub struct ControlButtons {
1202///     pub up: gtk::Button,
1203///     pub down: gtk::Button,
1204///     pub left: gtk::Button,
1205///     pub right: gtk::Button,
1206/// }
1207///
1208/// #[derive(Clone, glib::Downgrade)]
1209/// pub enum DirectionButton {
1210///     Left(gtk::Button),
1211///     Right(gtk::Button),
1212///     Up(gtk::Button),
1213///     Down(gtk::Button),
1214/// }
1215/// ```
1216///
1217/// [`glib::clone::Downgrade`]: ../glib/clone/trait.Downgrade.html
1218/// [`glib::clone::Upgrade`]: ../glib/clone/trait.Upgrade.html
1219#[proc_macro_derive(Downgrade)]
1220pub fn downgrade(input: TokenStream) -> TokenStream {
1221    let input = parse_macro_input!(input as DeriveInput);
1222    downgrade_derive::impl_downgrade(input)
1223}
1224
1225/// Derive macro for serializing/deserializing custom structs/enums as [`glib::Variant`]s.
1226///
1227/// # Example
1228///
1229/// ```
1230/// use glib::prelude::*;
1231///
1232/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1233/// struct Foo {
1234///     some_string: String,
1235///     some_int: i32,
1236/// }
1237///
1238/// let v = Foo { some_string: String::from("bar"), some_int: 1 };
1239/// let var = v.to_variant();
1240/// assert_eq!(var.get::<Foo>(), Some(v));
1241/// ```
1242///
1243/// When storing `Vec`s of fixed size types it is a good idea to wrap these in
1244/// `glib::FixedSizeVariantArray` as serialization/deserialization will be more efficient.
1245///
1246/// # Example
1247///
1248/// ```
1249/// use glib::prelude::*;
1250///
1251/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1252/// struct Foo {
1253///     some_vec: glib::FixedSizeVariantArray<Vec<u32>, u32>,
1254///     some_int: i32,
1255/// }
1256///
1257/// let v = Foo { some_vec: vec![1u32, 2u32].into(), some_int: 1 };
1258/// let var = v.to_variant();
1259/// assert_eq!(var.get::<Foo>(), Some(v));
1260/// ```
1261///
1262/// Enums are serialized as a tuple `(sv)` with the first value as a [kebab case] string for the
1263/// enum variant, or just `s` if this is a C-style enum. Some additional attributes are supported
1264/// for enums:
1265/// - `#[variant_enum(repr)]` to serialize the enum variant as an integer type instead of `s`.  The
1266///   `#[repr]` attribute must also be specified on the enum with a sized integer type, and the type
1267///   must implement `Copy`.
1268/// - `#[variant_enum(enum)]` uses [`EnumClass`] to serialize/deserialize as nicks. Meant for use
1269///   with [`glib::Enum`](Enum).
1270/// - `#[variant_enum(flags)]` uses [`FlagsClass`] to serialize/deserialize as nicks. Meant for use
1271///   with [`glib::flags`](macro@flags).
1272/// - `#[variant_enum(enum, repr)]` serializes as `i32`. Meant for use with [`glib::Enum`](Enum).
1273///   The type must also implement `Copy`.
1274/// - `#[variant_enum(flags, repr)]` serializes as `u32`. Meant for use with
1275///   [`glib::flags`](macro@flags).
1276///
1277/// # Example
1278///
1279/// ```
1280/// use glib::prelude::*;
1281///
1282/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1283/// enum Foo {
1284///     MyA,
1285///     MyB(i32),
1286///     MyC { some_int: u32, some_string: String }
1287/// }
1288///
1289/// let v = Foo::MyC { some_int: 1, some_string: String::from("bar") };
1290/// let var = v.to_variant();
1291/// assert_eq!(var.child_value(0).str(), Some("my-c"));
1292/// assert_eq!(var.get::<Foo>(), Some(v));
1293///
1294/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Variant)]
1295/// #[variant_enum(repr)]
1296/// #[repr(u8)]
1297/// enum Bar {
1298///     A,
1299///     B = 3,
1300///     C = 7
1301/// }
1302///
1303/// let v = Bar::B;
1304/// let var = v.to_variant();
1305/// assert_eq!(var.get::<u8>(), Some(3));
1306/// assert_eq!(var.get::<Bar>(), Some(v));
1307///
1308/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum, glib::Variant)]
1309/// #[variant_enum(enum)]
1310/// #[enum_type(name = "MyEnum")]
1311/// enum MyEnum {
1312///     Val,
1313///     #[enum_value(name = "My Val")]
1314///     ValWithCustomName,
1315///     #[enum_value(name = "My Other Val", nick = "other")]
1316///     ValWithCustomNameAndNick,
1317/// }
1318///
1319/// let v = MyEnum::ValWithCustomNameAndNick;
1320/// let var = v.to_variant();
1321/// assert_eq!(var.str(), Some("other"));
1322/// assert_eq!(var.get::<MyEnum>(), Some(v));
1323/// ```
1324///
1325/// [`glib::Variant`]: ../glib/variant/struct.Variant.html
1326/// [`EnumClass`]: ../glib/struct.EnumClass.html
1327/// [`FlagsClass`]: ../glib/struct.FlagsClass.html
1328/// [kebab case]: https://docs.rs/heck/0.4.0/heck/trait.ToKebabCase.html
1329#[proc_macro_derive(Variant, attributes(variant_enum))]
1330pub fn variant_derive(input: TokenStream) -> TokenStream {
1331    let input = parse_macro_input!(input as DeriveInput);
1332    variant_derive::impl_variant(input)
1333        .unwrap_or_else(syn::Error::into_compile_error)
1334        .into()
1335}
1336#[proc_macro]
1337pub fn cstr_bytes(item: TokenStream) -> TokenStream {
1338    syn::parse::Parser::parse2(
1339        |stream: syn::parse::ParseStream<'_>| {
1340            let literal = stream.parse::<syn::LitStr>()?;
1341            stream.parse::<syn::parse::Nothing>()?;
1342            let bytes = std::ffi::CString::new(literal.value())
1343                .map_err(|e| syn::Error::new_spanned(&literal, format!("{e}")))?
1344                .into_bytes_with_nul();
1345            let bytes = proc_macro2::Literal::byte_string(&bytes);
1346            Ok(quote::quote! { #bytes }.into())
1347        },
1348        item.into(),
1349    )
1350    .unwrap_or_else(|e| e.into_compile_error().into())
1351}
1352
1353/// This macro enables you to derive object properties in a quick way.
1354///
1355/// # Supported `#[property]` attributes
1356/// | Attribute | Description | Default | Example |
1357/// | --- | --- | --- | --- |
1358/// | `name = "literal"` | The name of the property | field ident where `_` (leading and trailing `_` are trimmed) is replaced into `-` | `#[property(name = "prop-name")]` |
1359/// | `type = expr` | The type of the property | inferred | `#[property(type = i32)]` |
1360/// | `get [= expr]` | Specify that the property is readable and use [`PropertyGet::get`] [or optionally set a custom internal getter] | | `#[property(get)]`, `#[property(get = get_prop)]`, or `[property(get = \|_\| 2)]` |
1361/// | `set [= expr]` | Specify that the property is writable and use [`PropertySet::set`] [or optionally set a custom internal setter] | | `#[property(set)]`, `#[property(set = set_prop)]`, or `[property(set = \|_, val\| {})]` |
1362/// | `override_class = expr` | The type of class of which to override the property from | | `#[property(override_class = SomeClass)]` |
1363/// | `override_interface = expr` | The type of interface of which to override the property from | | `#[property(override_interface = SomeInterface)]` |
1364/// | `nullable` | Whether to use `Option<T>` in the generated setter method |  | `#[property(nullable)]` |
1365/// | `member = ident` | Field of the nested type where property is retrieved and set | | `#[property(member = author)]` |
1366/// | `construct` | Specify that the property is construct property. Ensures that the property is always set during construction (if not explicitly then the default value is used). The use of a custom internal setter is supported. | | `#[property(get, construct)]` or `#[property(get, set = set_prop, construct)]` |
1367/// | `construct_only` | Specify that the property is construct only. This will not generate a public setter and only allow the property to be set during object construction. The use of a custom internal setter is supported. | | `#[property(get, construct_only)]` or `#[property(get, set = set_prop, construct_only)]` |
1368/// | `builder(<required-params>)[.ident]*` | Used to input required params or add optional Param Spec builder fields | | `#[property(builder(SomeEnum::default()))]`, `#[builder().default_value(1).minimum(0).maximum(5)]`, etc.  |
1369/// | `default` | Sets the `default_value` field of the Param Spec builder | | `#[property(default = 1)]` |
1370/// | `<optional-pspec-builder-fields> = expr` | Used to add optional Param Spec builder fields | | `#[property(minimum = 0)` , `#[property(minimum = 0, maximum = 1)]`, etc. |
1371/// | `<optional-pspec-builder-fields>` | Used to add optional Param Spec builder fields | | `#[property(explicit_notify)]` , `#[property(construct_only)]`, etc. |
1372///
1373/// ## Using Rust keywords as property names
1374/// You might hit a roadblock when declaring properties with this macro because you want to use a name that happens to be a Rust keyword. This may happen with names like `loop`, which is a pretty common name when creating things like animation handlers.
1375/// To use those names, you can make use of the raw identifier feature of Rust. Simply prefix the identifier name with `r#` in the struct declaration. Internally, those `r#`s are stripped so you can use its expected name in [`ObjectExt::property`] or within GtkBuilder template files.
1376///
1377/// # Generated methods
1378/// The following methods are generated on the wrapper type specified on `#[properties(wrapper_type = ...)]`:
1379/// * `$property()`, when the property is readable
1380/// * `set_$property()`, when the property is writable and not construct-only
1381/// * `connect_$property_notify()`
1382/// * `notify_$property()`
1383///
1384/// ## Extension trait
1385/// You can choose to move the method definitions to a trait by using `#[properties(wrapper_type = super::MyType, ext_trait = MyTypePropertiesExt)]`.
1386/// The trait name is optional, and defaults to `MyTypePropertiesExt`, where `MyType` is extracted from the wrapper type.
1387/// Note: The trait is defined in the same module where the `#[derive(Properties)]` call happens, and is implemented on the wrapper type.
1388///
1389/// Notice: You can't reimplement the generated methods on the wrapper type, unless you move them to a trait.
1390/// You can change the behavior of the generated getter/setter methods by using a custom internal getter/setter.
1391///
1392/// # Internal getters and setters
1393/// By default, they are generated for you. However, you can use a custom getter/setter
1394/// by assigning an expression to `get`/`set` `#[property]` attributes: `#[property(get = |_| 2, set)]` or `#[property(get, set = custom_setter_func)]`.
1395///
1396/// # Supported types
1397/// Every type implementing the trait [`Property`] is supported.
1398/// The type `Option<T>` is supported as a property only if `Option<T>` implements [`ToValueOptional`].
1399/// Optional types also require the `nullable` attribute: without it, the generated setter on the wrapper type
1400/// will take `T` instead of `Option<T>`, preventing the user from ever calling the setter with a `None` value.
1401///
1402/// ## Adding support for custom types
1403/// ### Types wrapping an existing <code>T: [ToValue] + [HasParamSpec]</code>
1404/// If you have declared a newtype as
1405/// ```rust
1406/// struct MyInt(i32);
1407/// ```
1408/// you can use it as a property by deriving [`ValueDelegate`].
1409///
1410/// ### Types with inner mutability
1411/// The trait [`Property`] must be implemented.
1412/// The traits [`PropertyGet`] and [`PropertySet`] should be implemented to enable the Properties macro
1413/// to generate a default internal getter/setter.
1414/// If possible, implementing [`PropertySetNested`] is preferred over `PropertySet`, because it
1415/// enables this macro to access the contained type and provide access to its fields,
1416/// using the `member = $structfield` syntax.
1417///
1418/// ### Types without [`HasParamSpec`][HasParamSpec]
1419/// If you have encountered a type <code>T: [ToValue]</code>, inside the gtk-rs crate, which doesn't implement [`HasParamSpec`][HasParamSpec],
1420/// then it's a bug and you should report it.
1421/// If you need to support a `ToValue` type with a [`ParamSpec`] not provided by gtk-rs, then you need to
1422/// implement `HasParamSpec` on that type.
1423///
1424/// # Example
1425/// ```
1426/// use std::cell::RefCell;
1427/// use glib::prelude::*;
1428/// use glib::subclass::prelude::*;
1429/// use glib_macros::Properties;
1430///
1431/// #[derive(Default, Clone)]
1432/// struct Author {
1433///     name: String,
1434///     nick: String,
1435/// }
1436///
1437/// pub mod imp {
1438///     use std::rc::Rc;
1439///
1440///     use super::*;
1441///
1442///     #[derive(Properties, Default)]
1443///     #[properties(wrapper_type = super::Foo)]
1444///     pub struct Foo {
1445///         #[property(get, set = Self::set_fizz)]
1446///         fizz: RefCell<String>,
1447///         #[property(name = "author-name", get, set, type = String, member = name)]
1448///         #[property(name = "author-nick", get, set, type = String, member = nick)]
1449///         author: RefCell<Author>,
1450///         #[property(get, set, explicit_notify, lax_validation)]
1451///         custom_flags: RefCell<String>,
1452///         #[property(get, set, minimum = 0, maximum = 3)]
1453///         numeric_builder: RefCell<u32>,
1454///         #[property(get, set, builder('c'))]
1455///         builder_with_required_param: RefCell<char>,
1456///         #[property(get, set, nullable)]
1457///         optional: RefCell<Option<String>>,
1458///         #[property(get, set)]
1459///         smart_pointer: Rc<RefCell<String>>,
1460///     }
1461///     
1462///     #[glib::derived_properties]
1463///     impl ObjectImpl for Foo {}
1464///
1465///     #[glib::object_subclass]
1466///     impl ObjectSubclass for Foo {
1467///         const NAME: &'static str = "MyFoo";
1468///         type Type = super::Foo;
1469///     }
1470///
1471///     impl Foo {
1472///         fn set_fizz(&self, value: String) {
1473///             *self.fizz.borrow_mut() = format!("custom set: {}", value);
1474///         }
1475///     }
1476/// }
1477///
1478/// glib::wrapper! {
1479///     pub struct Foo(ObjectSubclass<imp::Foo>);
1480/// }
1481///
1482/// fn main() {
1483///   let myfoo: Foo = glib::object::Object::new();
1484///
1485///   myfoo.set_fizz("test value");
1486///   assert_eq!(myfoo.fizz(), "custom set: test value".to_string());
1487/// }
1488/// ```
1489///
1490/// [`Property`]: ../glib/property/trait.Property.html
1491/// [`PropertyGet`]: ../glib/property/trait.PropertyGet.html
1492/// [`PropertyGet::get`]: ../glib/property/trait.PropertyGet.html#tymethod.get
1493/// [`PropertySet`]: ../glib/property/trait.PropertySet.html
1494/// [`PropertySet::set`]: ../glib/property/trait.PropertySet.html#tymethod.set
1495/// [`PropertySetNested`]: ../glib/property/trait.PropertySetNested.html
1496/// [`ObjectExt::property`]: ../glib/object/trait.ObjectExt.html#tymethod.property
1497/// [HasParamSpec]: ../glib/trait.HasParamSpec.html
1498/// [`ParamSpec`]: ../glib/struct.ParamSpec.html
1499/// [`ToValueOptional`]: ../glib/value/trait.ToValueOptional.html
1500/// [ToValue]: ../glib/value/trait.ToValue.html
1501#[allow(clippy::needless_doctest_main)]
1502#[proc_macro_derive(Properties, attributes(properties, property))]
1503pub fn derive_props(input: TokenStream) -> TokenStream {
1504    let input = parse_macro_input!(input as properties::PropsMacroInput);
1505    properties::impl_derive_props(input)
1506}
1507
1508/// When applied to `ObjectImpl`
1509/// ```ignore
1510/// #[glib::derived_properties]
1511/// impl ObjectImpl for CustomObject
1512/// ```
1513/// this macro generates
1514/// ```ignore
1515/// impl ObjectImpl for CustomObject {
1516///     fn properties() -> &'static [glib::ParamSpec] {
1517///         Self::derived_properties()
1518///     }
1519///     fn set_property(&self, id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
1520///         self.derived_set_property(id, value, pspec)
1521///     }
1522///     fn property(&self, id: usize, pspec: &glib::ParamSpec) -> glib::Value {
1523///         self.derived_property(id, pspec)
1524///     }
1525/// }
1526/// ```
1527#[proc_macro_attribute]
1528pub fn derived_properties(_attr: TokenStream, item: TokenStream) -> TokenStream {
1529    syn::parse::<syn::ItemImpl>(item)
1530        .map_err(|_| {
1531            syn::Error::new(
1532                Span::call_site(),
1533                derived_properties_attribute::WRONG_PLACE_MSG,
1534            )
1535        })
1536        .and_then(|input| derived_properties_attribute::impl_derived_properties(&input))
1537        .unwrap_or_else(syn::Error::into_compile_error)
1538        .into()
1539}
1540
1541/// # Example
1542/// ```
1543/// use glib::prelude::*;
1544/// use glib::ValueDelegate;
1545///
1546/// #[derive(ValueDelegate, Debug, PartialEq)]
1547/// struct MyInt(i32);
1548///
1549/// let myv = MyInt(2);
1550/// let convertedv = myv.to_value();
1551/// assert_eq!(convertedv.get::<MyInt>(), Ok(myv));
1552///
1553///
1554/// #[derive(ValueDelegate, Debug, PartialEq)]
1555/// #[value_delegate(from = u32)]
1556/// enum MyEnum {
1557///     Zero,
1558///     NotZero(u32)
1559/// }
1560///
1561/// impl From<u32> for MyEnum {
1562///     fn from(v: u32) -> Self {
1563///         match v {
1564///             0 => MyEnum::Zero,
1565///             x => MyEnum::NotZero(x)
1566///         }
1567///     }
1568/// }
1569/// impl<'a> From<&'a MyEnum> for u32 {
1570///     fn from(v: &'a MyEnum) -> Self {
1571///         match v {
1572///             MyEnum::Zero => 0,
1573///             MyEnum::NotZero(x) => *x
1574///         }
1575///     }
1576/// }
1577/// impl From<MyEnum> for u32 {
1578///     fn from(v: MyEnum) -> Self {
1579///         match v {
1580///             MyEnum::Zero => 0,
1581///             MyEnum::NotZero(x) => x
1582///         }
1583///     }
1584/// }
1585///
1586/// let myv = MyEnum::NotZero(34);
1587/// let convertedv = myv.to_value();
1588/// assert_eq!(convertedv.get::<MyEnum>(), Ok(myv));
1589///
1590///
1591/// // If you want your type to be usable inside an `Option`, you can derive `ToValueOptional`
1592/// // by adding `nullable` as follows
1593/// #[derive(ValueDelegate, Debug, PartialEq)]
1594/// #[value_delegate(nullable)]
1595/// struct MyString(String);
1596///
1597/// let myv = Some(MyString("Hello world".to_string()));
1598/// let convertedv = myv.to_value();
1599/// assert_eq!(convertedv.get::<Option<MyString>>(), Ok(myv));
1600/// let convertedv = None::<MyString>.to_value();
1601/// assert_eq!(convertedv.get::<Option<MyString>>(), Ok(None::<MyString>));
1602/// ```
1603#[proc_macro_derive(ValueDelegate, attributes(value_delegate))]
1604pub fn derive_value_delegate(input: TokenStream) -> TokenStream {
1605    let input = parse_macro_input!(input as value_delegate_derive::ValueDelegateInput);
1606    value_delegate_derive::impl_value_delegate(input).unwrap()
1607}
1608
1609/// An attribute macro for writing asynchronous test functions.
1610///
1611/// This macro is designed to wrap an asynchronous test function and ensure that
1612/// it runs within a `glib::MainContext`. It helps in writing async tests that
1613/// require the use of an event loop for the asynchronous execution.
1614///
1615/// # Example
1616///
1617/// ```
1618/// #[glib::async_test]
1619/// async fn my_async_test() {
1620///     // Test code that runs asynchronously
1621/// }
1622/// ```
1623#[proc_macro_attribute]
1624pub fn async_test(args: TokenStream, item: TokenStream) -> TokenStream {
1625    async_test::async_test(args, item)
1626}