Skip to main content

risingwave_expr_macro/
parse.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Parse the tokens of the macro.
16
17use proc_macro_error::abort;
18use quote::ToTokens;
19use syn::parse::{Parse, ParseStream};
20use syn::spanned::Spanned;
21use syn::{LitStr, Token, parse_quote};
22
23use super::*;
24
25impl Parse for FunctionAttr {
26    /// Parse the attribute of the function macro.
27    fn parse(input: ParseStream<'_>) -> Result<Self> {
28        let mut parsed = Self::default();
29
30        let sig = input.parse::<LitStr>()?;
31        let sig_str = sig.value();
32        let (name_args, ret) = match sig_str.split_once("->") {
33            Some((name_args, ret)) => (name_args, ret),
34            None => (sig_str.as_str(), "void"),
35        };
36        let (name, args) = name_args
37            .split_once('(')
38            .ok_or_else(|| Error::new_spanned(&sig, "expected '('"))?;
39        let args = args.trim_start().trim_end_matches([')', ' ']);
40        let (is_table_function, ret) = match ret.trim_start().strip_prefix("setof") {
41            Some(s) => (true, s),
42            None => (false, ret),
43        };
44        parsed.name = name.trim().to_owned();
45        parsed.args = if args.is_empty() {
46            vec![]
47        } else {
48            args.split(',').map(|s| s.trim().to_owned()).collect()
49        };
50        parsed.ret = ret.trim().to_owned();
51        parsed.is_table_function = is_table_function;
52
53        if input.parse::<Token![,]>().is_err() {
54            return Ok(parsed);
55        }
56
57        let metas = input.parse_terminated(
58            |input| {
59                if input.peek(Token![async]) {
60                    let token: Token![async] = input.parse()?;
61                    Ok(syn::Meta::Path(syn::Ident::new("async", token.span).into()))
62                } else {
63                    syn::Meta::parse(input)
64                }
65            },
66            Token![,],
67        )?;
68        for meta in metas {
69            let get_value = || {
70                let kv = meta.require_name_value()?;
71                let syn::Expr::Lit(lit) = &kv.value else {
72                    return Err(Error::new(kv.value.span(), "expected literal"));
73                };
74                let syn::Lit::Str(lit) = &lit.lit else {
75                    return Err(Error::new(kv.value.span(), "expected string literal"));
76                };
77                Ok(lit.value())
78            };
79            if meta.path().is_ident("batch_fn") {
80                parsed.batch_fn = Some(get_value()?);
81            } else if meta.path().is_ident("state") {
82                parsed.state = Some(get_value()?);
83            } else if meta.path().is_ident("init_state") {
84                parsed.init_state = Some(get_value()?);
85            } else if meta.path().is_ident("prebuild") {
86                parsed.prebuild = Some(get_value()?);
87            } else if meta.path().is_ident("type_infer") {
88                parsed.type_infer = Some(get_value()?);
89            } else if meta.path().is_ident("generic") {
90                parsed.generic = Some(get_value()?);
91            } else if meta.path().is_ident("async") {
92                parsed.async_ = true;
93            } else if meta.path().is_ident("volatile") {
94                parsed.volatile = true;
95            } else if meta.path().is_ident("deprecated") || meta.path().is_ident("internal") {
96                parsed.deprecated = true;
97            } else if meta.path().is_ident("rewritten") {
98                parsed.rewritten = true;
99            } else if meta.path().is_ident("append_only") {
100                parsed.append_only = true;
101            } else {
102                return Err(Error::new(
103                    meta.span(),
104                    format!("invalid property: {:?}", meta.path()),
105                ));
106            }
107        }
108        Ok(parsed)
109    }
110}
111
112impl Parse for UserFunctionAttr {
113    fn parse(input: ParseStream<'_>) -> Result<Self> {
114        let itemfn: syn::ItemFn = input.parse()?;
115        Ok(UserFunctionAttr::from(&itemfn.sig))
116    }
117}
118
119impl From<&syn::Signature> for UserFunctionAttr {
120    fn from(sig: &syn::Signature) -> Self {
121        let (return_type_kind, iterator_item_kind, core_return_type) = match &sig.output {
122            syn::ReturnType::Default => (ReturnTypeKind::T, None, "()".into()),
123            syn::ReturnType::Type(_, ty) => {
124                let (kind, inner) = check_type(ty);
125                match strip_iterator(inner) {
126                    Some(ty) => {
127                        let (inner_kind, inner) = check_type(ty);
128                        (kind, Some(inner_kind), inner.to_token_stream().to_string())
129                    }
130                    None => (kind, None, inner.to_token_stream().to_string()),
131                }
132            }
133        };
134        UserFunctionAttr {
135            name: sig.ident.to_string(),
136            async_: sig.asyncness.is_some(),
137            writer_type_kind: sig.inputs.last().and_then(arg_writer_type),
138            context: sig.inputs.iter().any(arg_is_context),
139            retract: last_arg_is_retract(sig),
140            args_option: sig.inputs.iter().map(arg_is_option).collect(),
141            first_mut_ref_arg: first_mut_ref_arg(sig),
142            return_type_kind,
143            iterator_item_kind,
144            core_return_type,
145            generic: sig.generics.params.len(),
146            return_type_span: sig.output.span(),
147        }
148    }
149}
150
151impl Parse for AggregateImpl {
152    fn parse(input: ParseStream<'_>) -> Result<Self> {
153        let itemimpl: syn::ItemImpl = input.parse()?;
154        let parse_function = |name: &str| {
155            itemimpl.items.iter().find_map(|item| match item {
156                syn::ImplItem::Fn(syn::ImplItemFn { sig, .. }) if sig.ident == name => {
157                    Some(UserFunctionAttr::from(sig))
158                }
159                _ => None,
160            })
161        };
162        let self_path = itemimpl.self_ty.to_token_stream().to_string();
163        let struct_name = match self_path.split_once('<') {
164            Some((path, _)) => path.trim().into(), // remove generic parameters
165            None => self_path,
166        };
167        Ok(AggregateImpl {
168            struct_name,
169            accumulate: parse_function("accumulate").expect("expect accumulate function"),
170            retract: parse_function("retract"),
171            merge: parse_function("merge"),
172            finalize: parse_function("finalize"),
173            create_state: parse_function("create_state"),
174            encode_state: parse_function("encode_state"),
175            decode_state: parse_function("decode_state"),
176        })
177    }
178}
179
180impl Parse for AggregateFnOrImpl {
181    fn parse(input: ParseStream<'_>) -> Result<Self> {
182        // consume attributes
183        let _ = input.call(syn::Attribute::parse_outer)?;
184        if input.peek(Token![impl]) {
185            Ok(AggregateFnOrImpl::Impl(input.parse()?))
186        } else {
187            Ok(AggregateFnOrImpl::Fn(input.parse()?))
188        }
189    }
190}
191
192/// Check if the argument is a writer and return its type.
193fn arg_writer_type(arg: &syn::FnArg) -> Option<WriterTypeKind> {
194    let syn::FnArg::Typed(arg) = arg else {
195        return None;
196    };
197    let syn::Type::Reference(syn::TypeReference { elem, .. }) = arg.ty.as_ref() else {
198        return None;
199    };
200    let elem = elem.as_ref();
201    if elem == &parse_quote!(impl std::fmt::Write) {
202        Some(WriterTypeKind::FmtWrite)
203    } else if elem == &parse_quote!(impl std::io::Write) {
204        Some(WriterTypeKind::IoWrite)
205    } else if elem == &parse_quote!(impl Write) {
206        abort! { elem, "use of ambiguous `Write` trait.";
207            note = "`function!` macro can only recognize fully-qualified type.";
208            help = "Please use `std::fmt::Write` or `std::io::Write` instead."
209        };
210    } else if elem == &parse_quote!(jsonbb::Builder) {
211        Some(WriterTypeKind::JsonbbBuilder)
212    } else if elem == &parse_quote!(Builder) {
213        abort! { elem, "use of ambiguous `Builder` type.";
214            note = "`function!` macro can only recognize fully-qualified type.";
215            help = "Please use `jsonbb::Builder` instead."
216        };
217    } else if elem == &parse_quote!(impl risingwave_common::array::ListWrite) {
218        Some(WriterTypeKind::ListWrite)
219    } else {
220        None
221    }
222}
223
224/// Check if the argument is `&Context`.
225fn arg_is_context(arg: &syn::FnArg) -> bool {
226    let syn::FnArg::Typed(arg) = arg else {
227        return false;
228    };
229    let syn::Type::Reference(syn::TypeReference { elem, .. }) = arg.ty.as_ref() else {
230        return false;
231    };
232    let syn::Type::Path(path) = elem.as_ref() else {
233        return false;
234    };
235    let Some(seg) = path.path.segments.last() else {
236        return false;
237    };
238    seg.ident == "Context"
239}
240
241/// Check if the last argument is `retract: bool`.
242fn last_arg_is_retract(sig: &syn::Signature) -> bool {
243    let Some(syn::FnArg::Typed(arg)) = sig.inputs.last() else {
244        return false;
245    };
246    let syn::Pat::Ident(pat) = &*arg.pat else {
247        return false;
248    };
249    pat.ident.to_string().contains("retract")
250}
251
252/// Check if the argument is `Option`.
253fn arg_is_option(arg: &syn::FnArg) -> bool {
254    let syn::FnArg::Typed(arg) = arg else {
255        return false;
256    };
257    let syn::Type::Path(path) = arg.ty.as_ref() else {
258        return false;
259    };
260    let Some(seg) = path.path.segments.last() else {
261        return false;
262    };
263    seg.ident == "Option"
264}
265
266/// Returns `T` if the first argument (except `self`) is `&mut T`.
267fn first_mut_ref_arg(sig: &syn::Signature) -> Option<String> {
268    let arg = match sig.inputs.first()? {
269        syn::FnArg::Typed(arg) => arg,
270        syn::FnArg::Receiver(_) => match sig.inputs.iter().nth(1)? {
271            syn::FnArg::Typed(arg) => arg,
272            _ => return None,
273        },
274    };
275    let syn::Type::Reference(syn::TypeReference {
276        elem,
277        mutability: Some(_),
278        ..
279    }) = arg.ty.as_ref()
280    else {
281        return None;
282    };
283    Some(elem.to_token_stream().to_string())
284}
285
286/// Check the return type.
287fn check_type(ty: &syn::Type) -> (ReturnTypeKind, &syn::Type) {
288    if let Some(inner) = strip_outer_type(ty, "Result") {
289        if let Some(inner) = strip_outer_type(inner, "Option") {
290            (ReturnTypeKind::ResultOption, inner)
291        } else {
292            (ReturnTypeKind::Result, inner)
293        }
294    } else if let Some(inner) = strip_outer_type(ty, "Option") {
295        (ReturnTypeKind::Option, inner)
296    } else if let Some(inner) = strip_outer_type(ty, "DatumRef") {
297        (ReturnTypeKind::Option, inner)
298    } else {
299        (ReturnTypeKind::T, ty)
300    }
301}
302
303/// Check if the type is `type_<T>` and return `T`.
304fn strip_outer_type<'a>(ty: &'a syn::Type, type_: &str) -> Option<&'a syn::Type> {
305    let syn::Type::Path(path) = ty else {
306        return None;
307    };
308    let seg = path.path.segments.last()?;
309    if seg.ident != type_ {
310        return None;
311    }
312    let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
313        return None;
314    };
315    let Some(syn::GenericArgument::Type(ty)) = args.args.first() else {
316        return None;
317    };
318    Some(ty)
319}
320
321/// Check if the type is `impl Iterator<Item = T>` and return `T`.
322fn strip_iterator(ty: &syn::Type) -> Option<&syn::Type> {
323    let syn::Type::ImplTrait(impl_trait) = ty else {
324        return None;
325    };
326    let syn::TypeParamBound::Trait(trait_bound) = impl_trait.bounds.first()? else {
327        return None;
328    };
329    let segment = trait_bound.path.segments.last().unwrap();
330    if segment.ident != "Iterator" {
331        return None;
332    }
333    let syn::PathArguments::AngleBracketed(angle_bracketed) = &segment.arguments else {
334        return None;
335    };
336    for arg in &angle_bracketed.args {
337        if let syn::GenericArgument::AssocType(b) = arg
338            && b.ident == "Item"
339        {
340            return Some(&b.ty);
341        }
342    }
343    None
344}