Skip to main content

qtbridge_gen/qt_gen_impl/qt_meta_gen/
qclass_info.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4use proc_macro2::{TokenStream};
5use quote::{quote};
6use syn::{parse::Parse, spanned::Spanned};
7
8use crate::utils::parse_utils::parse_name_value;
9
10pub struct QClassInfo{
11    pub name: syn::LitStr,
12    pub value: syn::LitStr,
13}
14
15impl QClassInfo {
16    pub fn new(item: &syn::ImplItemMacro) -> syn::Result<Option<Self>> {
17        if !item.mac.path.is_ident("qclass_info") {
18            return Ok(None); // Not a 'qclass_info!' macro
19        }
20
21        if let Some(first_attr) = item.attrs.first() {
22            return Err(syn::Error::new(first_attr.span(), "Attributes for qclass_info! macro are not supported"));
23        }
24
25        let class_info = item.mac.parse_body::<QClassInfo>()?;
26        Ok(Some(class_info))
27    }
28
29    pub fn get_meta_registration_code(&self) -> syn::Result<TokenStream> {
30
31        let QClassInfo {
32            name,
33            value,
34            ..
35        } = self;
36
37        Ok(quote!{
38                meta_obj.as_mut().add_class_info(#name, #value);
39        })
40
41    }
42
43}
44
45mod qclass_info_keywords {
46    syn::custom_keyword!(Name);
47    syn::custom_keyword!(Value);
48}
49
50impl syn::parse::Parse for QClassInfo {
51    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
52        let mut name = None;
53        let mut value = None;
54
55        while !input.is_empty() {
56            if input.peek(syn::Token![,]) {
57                input.parse::<syn::Token![,]>()?;
58                if input.is_empty() { break; }
59            }
60
61            let token_begin = input.fork();
62            if input.peek(qclass_info_keywords::Name) {
63                read_attribute(input, &mut name, "Name")?;
64            }
65            else if input.peek(qclass_info_keywords::Value) {
66                read_attribute(input, &mut value, "Value")?;
67            }
68            else {
69                return Err(token_begin.error("Unsupported qclass_info attribute"));
70            }
71        }
72        let name = name.ok_or_else(|| syn::Error::new(input.span(), "Missing Name attribute"))?;
73        let value = value.ok_or_else(|| syn::Error::new(input.span(), "Missing Value attribute"))?;
74
75        Ok(QClassInfo { name, value })
76    }
77
78}
79
80fn read_attribute<T: Parse>(input: syn::parse::ParseStream, dst: &mut Option<T>, name: &'static str) -> syn::Result<()> {
81    if dst.is_some() {
82        return Err(syn::Error::new(input.span(), format!("'{name}' attribute is already defined for the property")));
83    }
84
85    *dst = Some(parse_name_value::<syn::Ident, T>(input)?.1);
86
87    Ok(())
88}