Skip to main content

qtbridge_gen/
function_with_attributes.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4use syn::braced;
5
6pub enum BlockOrSemi {
7    Block(syn::Block),
8    Semi,
9}
10
11pub struct FunctionWithAttributes {
12    pub attrs: Vec<syn::Attribute>, // Attributes other than qsignal
13    pub vis: syn::Visibility,
14    pub sig: syn::Signature,
15    pub block: BlockOrSemi,
16}
17
18impl syn::parse::Parse for FunctionWithAttributes {
19    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
20
21        // Inspired by
22        // impl Parse for ForeignItemFn
23        //   and
24        // impl Parse for ImplItemFn
25
26        let mut attrs = input.call(syn::Attribute::parse_outer)?;
27        let vis: syn::Visibility = input.parse()?;
28        let _defaultness: Option<syn::Token![default]> = input.parse()?;
29        let sig: syn::Signature = input.parse()?;
30        if input.peek(syn::Token![;]) {
31            let _semi: syn::Token![;] = input.parse()?;
32            Ok(Self {
33                attrs,
34                vis,
35                sig,
36                block: BlockOrSemi::Semi,
37            })
38        }
39        else if input.peek(syn::token::Brace) {
40            let content;
41            let brace_token = braced!(content in input);
42            attrs.extend(content.call(syn::Attribute::parse_inner)?);
43            let block = syn::Block {
44                brace_token,
45                stmts: content.call(syn::Block::parse_within)?,
46            };
47            Ok(Self{
48                attrs,
49                vis,
50                sig,
51                block: BlockOrSemi::Block(block),
52            })
53        } else {
54            Err(input.error("Unexpected function syntax"))
55        }
56    }
57}