Skip to main content

risingwave_expr_macro/
gen.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//! Generate code for the functions.
16
17use itertools::Itertools;
18use proc_macro2::{Ident, Span};
19use quote::{format_ident, quote};
20
21use super::*;
22
23impl FunctionAttr {
24    /// Expands the wildcard in function arguments or return type.
25    pub fn expand(&self) -> Vec<Self> {
26        // handle variadic argument
27        if self
28            .args
29            .last()
30            .is_some_and(|arg| arg.starts_with("variadic"))
31        {
32            // expand:  foo(a, b, variadic anyarray)
33            // to:      foo(a, b, ...)
34            //        + foo_variadic(a, b, anyarray)
35            let mut attrs = Vec::new();
36            attrs.extend(
37                FunctionAttr {
38                    args: {
39                        let mut args = self.args.clone();
40                        *args.last_mut().unwrap() = "...".to_owned();
41                        args
42                    },
43                    ..self.clone()
44                }
45                .expand(),
46            );
47            attrs.extend(
48                FunctionAttr {
49                    name: format!("{}_variadic", self.name),
50                    args: {
51                        let mut args = self.args.clone();
52                        let last = args.last_mut().unwrap();
53                        *last = last.strip_prefix("variadic ").unwrap().into();
54                        args
55                    },
56                    ..self.clone()
57                }
58                .expand(),
59            );
60            return attrs;
61        }
62        let args = self.args.iter().map(|ty| types::expand_type_wildcard(ty));
63        let ret = types::expand_type_wildcard(&self.ret);
64        let mut attrs = Vec::new();
65        for (args, mut ret) in args.multi_cartesian_product().cartesian_product(ret) {
66            if ret == "auto" {
67                ret = types::min_compatible_type(&args);
68            }
69            let attr = FunctionAttr {
70                args: args.iter().map(|s| s.to_string()).collect(),
71                ret: ret.to_owned(),
72                ..self.clone()
73            };
74            attrs.push(attr);
75        }
76        attrs
77    }
78
79    /// Generate the type infer function: `fn(&[DataType]) -> Result<DataType>`
80    fn generate_type_infer_fn(&self) -> Result<TokenStream2> {
81        if let Some(func) = &self.type_infer {
82            if func == "unreachable" {
83                return Ok(
84                    quote! { |_| unreachable!("type inference for this function should be specially handled in frontend, and should not call sig.type_infer") },
85                );
86            }
87            // use the user defined type inference function
88            return Ok(func.parse().unwrap());
89        } else if self.ret == "any" {
90            // TODO: if there are multiple "any", they should be the same type
91            if let Some(i) = self.args.iter().position(|t| t == "any") {
92                // infer as the type of "any" argument
93                return Ok(quote! { |args| Ok(args[#i].clone()) });
94            }
95            if let Some(i) = self.args.iter().position(|t| t == "anyarray") {
96                // infer as the element type of "anyarray" argument
97                return Ok(quote! { |args| Ok(args[#i].as_list_elem().clone()) });
98            }
99        } else if self.ret == "anyarray" {
100            if let Some(i) = self.args.iter().position(|t| t == "anyarray") {
101                // infer as the type of "anyarray" argument
102                return Ok(quote! { |args| Ok(args[#i].clone()) });
103            }
104            if let Some(i) = self.args.iter().position(|t| t == "any") {
105                // infer as the array type of "any" argument
106                return Ok(quote! { |args| Ok(DataType::list(args[#i].clone())) });
107            }
108        } else if self.ret == "struct" {
109            if let Some(i) = self.args.iter().position(|t| t == "struct") {
110                // infer as the type of "struct" argument
111                return Ok(quote! { |args| Ok(args[#i].clone()) });
112            }
113        } else if self.ret == "anymap" {
114            if let Some(i) = self.args.iter().position(|t| t == "anymap") {
115                // infer as the type of "anymap" argument
116                return Ok(quote! { |args| Ok(args[#i].clone()) });
117            }
118        } else {
119            // the return type is fixed
120            let ty = data_type(&self.ret);
121            return Ok(quote! { |_| Ok(#ty) });
122        }
123        Err(Error::new(
124            Span::call_site(),
125            "type inference function cannot be automatically derived. You should provide: `type_infer = \"|args| Ok(...)\"`",
126        ))
127    }
128
129    /// Generate a descriptor (`FuncSign`) of the scalar or table function.
130    ///
131    /// The types of arguments and return value should not contain wildcard.
132    ///
133    /// # Arguments
134    /// `build_fn`: whether the user provided a function is a build function.
135    /// (from the `#[build_function]` macro)
136    pub fn generate_function_descriptor(
137        &self,
138        user_fn: &UserFunctionAttr,
139        build_fn: bool,
140    ) -> Result<TokenStream2> {
141        if self.is_table_function {
142            return self.generate_table_function_descriptor(user_fn, build_fn);
143        }
144        let name = self.name.clone();
145        let variadic = matches!(self.args.last(), Some(t) if t == "...");
146        let args = match variadic {
147            true => &self.args[..self.args.len() - 1],
148            false => &self.args[..],
149        }
150        .iter()
151        .map(|ty| sig_data_type(ty))
152        .collect_vec();
153        let ret = sig_data_type(&self.ret);
154
155        let is_async = self.async_ || user_fn.async_;
156        let pb_type = format_ident!("{}", utils::to_camel_case(&name));
157        let ctor_name = format_ident!("{}", self.ident_name());
158        let build_fn = if build_fn {
159            let name = format_ident!("{}", user_fn.name);
160            if self.async_ {
161                quote! {
162                    |return_type, children| {
163                        let expr = #name(return_type, children)?;
164                        risingwave_expr::ensure!(
165                            matches!(&expr, risingwave_expr::expr::BoxedExpression::Async(_)),
166                            "async expression builder `{}` returned a synchronous expression",
167                            stringify!(#name)
168                        );
169                        Ok(expr)
170                    }
171                }
172            } else {
173                quote! { #name }
174            }
175        } else if self.rewritten {
176            quote! { |_, _| Err(ExprError::UnsupportedFunction(#name.into())) }
177        } else {
178            // This is the core logic for `#[function]`
179            self.generate_build_scalar_function(user_fn, true)?
180        };
181        let type_infer_fn = self.generate_type_infer_fn()?;
182        let deprecated = self.deprecated;
183        let maybe_allow_deprecated = if deprecated {
184            quote! { #[allow(deprecated)] }
185        } else {
186            quote! {}
187        };
188
189        Ok(quote! {
190            #[risingwave_expr::codegen::linkme::distributed_slice(risingwave_expr::sig::FUNCTIONS)]
191            fn #ctor_name() -> risingwave_expr::sig::FuncSign {
192                use risingwave_common::types::{DataType, DataTypeName};
193                use risingwave_expr::sig::{FuncSign, SigDataType, FuncBuilder};
194
195                #maybe_allow_deprecated
196                FuncSign {
197                    name: risingwave_pb::expr::expr_node::Type::#pb_type.into(),
198                    inputs_type: vec![#(#args),*],
199                    variadic: #variadic,
200                    ret_type: #ret,
201                    build: FuncBuilder::Scalar(#build_fn),
202                    type_infer: #type_infer_fn,
203                    deprecated: #deprecated,
204                    is_async: #is_async,
205                }
206            }
207        })
208    }
209
210    /// Generate a build function for the scalar function.
211    ///
212    /// If `optimize_const` is true, the function will be optimized for constant arguments,
213    /// and fallback to the general version if any argument is not constant.
214    fn generate_build_scalar_function(
215        &self,
216        user_fn: &UserFunctionAttr,
217        optimize_const: bool,
218    ) -> Result<TokenStream2> {
219        let variadic = matches!(self.args.last(), Some(t) if t == "...");
220        let num_args = self.args.len() - if variadic { 1 } else { 0 };
221        let fn_name = format_ident!("{}", user_fn.name);
222        let struct_name = match optimize_const {
223            true => format_ident!("{}OptimizeConst", utils::to_camel_case(&self.ident_name())),
224            false => format_ident!("{}", utils::to_camel_case(&self.ident_name())),
225        };
226        let async_struct_name = format_ident!("Async{}", struct_name);
227
228        // we divide all arguments into two groups: prebuilt and non-prebuilt.
229        // prebuilt arguments are collected from the "prebuild" field.
230        // let's say we have a function with 3 arguments: [0, 1, 2]
231        // and the prebuild field contains "$1".
232        // then we have:
233        //     prebuilt_indices = [1]
234        //     non_prebuilt_indices = [0, 2]
235        //
236        // if the const argument optimization is enabled, prebuilt arguments are
237        // evaluated at build time, thus the children only contain non-prebuilt arguments:
238        //     children_indices = [0, 2]
239        // otherwise, the children contain all arguments:
240        //     children_indices = [0, 1, 2]
241
242        let prebuilt_indices = match &self.prebuild {
243            Some(s) => (0..num_args)
244                .filter(|i| s.contains(&format!("${i}")))
245                .collect_vec(),
246            None => vec![],
247        };
248        let non_prebuilt_indices = match &self.prebuild {
249            Some(s) => (0..num_args)
250                .filter(|i| !s.contains(&format!("${i}")))
251                .collect_vec(),
252            _ => (0..num_args).collect_vec(),
253        };
254        let children_indices = match optimize_const {
255            #[allow(clippy::redundant_clone)] // false-positive
256            true => non_prebuilt_indices.clone(),
257            false => (0..num_args).collect_vec(),
258        };
259
260        /// Return a list of identifiers with the given prefix and indices.
261        fn idents(prefix: &str, indices: &[usize]) -> Vec<Ident> {
262            indices
263                .iter()
264                .map(|i| format_ident!("{prefix}{i}"))
265                .collect()
266        }
267        let inputs = idents("i", &children_indices);
268        let prebuilt_inputs = idents("i", &prebuilt_indices);
269        let non_prebuilt_inputs = idents("i", &non_prebuilt_indices);
270        let array_refs = idents("array", &children_indices);
271        let arrays = idents("a", &children_indices);
272        let datums = idents("v", &children_indices);
273        let arg_arrays = children_indices
274            .iter()
275            .map(|i| format_ident!("{}", types::array_type(&self.args[*i])));
276        let arg_arrays = arg_arrays.collect_vec();
277        let arg_types = children_indices.iter().map(|i| {
278            types::ref_type(&self.args[*i])
279                .parse::<TokenStream2>()
280                .unwrap()
281        });
282        let arg_types = arg_types.collect_vec();
283        let annotation: TokenStream2 = match user_fn.core_return_type.as_str() {
284            // add type annotation for functions that return generic types
285            "T" | "T1" | "T2" | "T3" => format!(": Option<{}>", types::owned_type(&self.ret))
286                .parse()
287                .unwrap(),
288            _ => quote! {},
289        };
290        let ret_array_type = format_ident!("{}", types::array_type(&self.ret));
291        let builder_type = format_ident!("{}Builder", types::array_type(&self.ret));
292        let prebuilt_arg_type = match &self.prebuild {
293            Some(s) if optimize_const => s.split("::").next().unwrap().parse().unwrap(),
294            _ => quote! { () },
295        };
296        let prebuilt_arg_value = match &self.prebuild {
297            // example:
298            // prebuild = "RegexContext::new($1)"
299            // return = "RegexContext::new(i1)"
300            Some(s) => s
301                .replace('$', "i")
302                .parse()
303                .expect("invalid prebuild syntax"),
304            None => quote! { () },
305        };
306        let prebuild_const = if self.prebuild.is_some() && optimize_const {
307            let build_general = self.generate_build_scalar_function(user_fn, false)?;
308            quote! {{
309                let build_general = #build_general;
310                #(
311                    // try to evaluate constant for prebuilt arguments
312                    let #prebuilt_inputs = match children[#prebuilt_indices].eval_const() {
313                        Ok(s) => s,
314                        // prebuilt argument is not constant, fallback to general
315                        Err(_) => return build_general(return_type, children),
316                    };
317                    // get reference to the constant value
318                    let #prebuilt_inputs = match &#prebuilt_inputs {
319                        Some(s) => s.as_scalar_ref_impl().try_into()?,
320                        // the function should always return null if any const argument is null
321                        None => return Ok(risingwave_expr::expr::LiteralExpression::new(
322                            return_type,
323                            None,
324                        ).boxed()),
325                    };
326                )*
327                #prebuilt_arg_value
328            }}
329        } else {
330            quote! { () }
331        };
332
333        // ensure the number of children matches the number of arguments
334        let check_children = match variadic {
335            true => quote! { risingwave_expr::ensure!(children.len() >= #num_args); },
336            false => quote! { risingwave_expr::ensure!(children.len() == #num_args); },
337        };
338
339        // evaluate variadic arguments in sync `eval`
340        let eval_variadic_sync = variadic.then(|| {
341            quote! {
342                let mut columns = Vec::with_capacity(self.children.len() - #num_args);
343                for child in &self.children[#num_args..] {
344                    columns.push(child.eval(input)?);
345                }
346                let variadic_input = DataChunk::new(columns, input.visibility().clone());
347            }
348        });
349        // evaluate variadic arguments in async `eval`
350        let eval_variadic_async = variadic.then(|| {
351            quote! {
352                let mut columns = Vec::with_capacity(self.children.len() - #num_args);
353                for child in &self.children[#num_args..] {
354                    columns.push(child.eval(input).await?);
355                }
356                let variadic_input = DataChunk::new(columns, input.visibility().clone());
357            }
358        });
359        // evaluate variadic arguments in sync `eval_row`
360        let eval_row_variadic_sync = variadic.then(|| {
361            quote! {
362                let mut row = Vec::with_capacity(self.children.len() - #num_args);
363                for child in &self.children[#num_args..] {
364                    row.push(child.eval_row(input)?);
365                }
366                let variadic_row = OwnedRow::new(row);
367            }
368        });
369        // evaluate variadic arguments in async `eval_row`
370        let eval_row_variadic_async = variadic.then(|| {
371            quote! {
372                let mut row = Vec::with_capacity(self.children.len() - #num_args);
373                for child in &self.children[#num_args..] {
374                    row.push(child.eval_row(input).await?);
375                }
376                let variadic_row = OwnedRow::new(row);
377            }
378        });
379
380        let generic = (self.ret == "boolean" && user_fn.generic == 3).then(|| {
381            // XXX: for generic compare functions, we need to specify the compatible type
382            let compatible_type = types::ref_type(types::min_compatible_type(&self.args))
383                .parse::<TokenStream2>()
384                .unwrap();
385            quote! { ::<_, _, #compatible_type> }
386        });
387        let prebuilt_arg = match (&self.prebuild, optimize_const) {
388            // use the prebuilt argument
389            (Some(_), true) => quote! { &self.prebuilt_arg, },
390            // build the argument on site
391            (Some(_), false) => quote! { &#prebuilt_arg_value, },
392            // no prebuilt argument
393            (None, _) => quote! {},
394        };
395        let variadic_args = variadic.then(|| quote! { &variadic_row, });
396        let context = user_fn.context.then(|| quote! { &self.context, });
397        let writer = user_fn
398            .writer_type_kind
399            .is_some()
400            .then(|| quote! { &mut writer, });
401        let await_ = user_fn.async_.then(|| quote! { .await });
402
403        let record_error = {
404            // Uniform arguments into `DatumRef`.
405            #[allow(clippy::disallowed_methods)] // allow zip
406            let inputs_args = inputs
407                .iter()
408                .zip(user_fn.args_option.iter())
409                .map(|(input, opt)| {
410                    if *opt {
411                        quote! { #input.map(|s| ScalarRefImpl::from(s)) }
412                    } else {
413                        quote! { Some(ScalarRefImpl::from(#input)) }
414                    }
415                });
416            let inputs_args = quote! {
417                let args: &[DatumRef<'_>] = &[#(#inputs_args),*];
418                let args = args.iter().copied();
419            };
420            let var_args = variadic.then(|| {
421                quote! {
422                    let args = args.chain(variadic_row.iter());
423                }
424            });
425
426            quote! {
427                #inputs_args
428                #var_args
429                errors.push(ExprError::function(
430                    stringify!(#fn_name),
431                    args,
432                    e,
433                ));
434            }
435        };
436
437        // call the user defined function
438        // inputs: [ Option<impl ScalarRef> ]
439        let mut output = quote! { #fn_name #generic(
440            #(#non_prebuilt_inputs,)*
441            #variadic_args
442            #prebuilt_arg
443            #context
444            #writer
445        ) #await_ };
446        // handle error if the function returns `Result`
447        // wrap a `Some` if the function doesn't return `Option`
448        output = match user_fn.return_type_kind {
449            // XXX: we don't support void type yet. return null::int for now.
450            _ if self.ret == "void" => quote! { { #output; Option::<i32>::None } },
451            ReturnTypeKind::T => quote! { Some(#output) },
452            ReturnTypeKind::Option => output,
453            ReturnTypeKind::Result => quote! {
454                match #output {
455                    Ok(x) => Some(x),
456                    Err(e) => {
457                        #record_error
458                        None
459                    }
460                }
461            },
462            ReturnTypeKind::ResultOption => quote! {
463                match #output {
464                    Ok(x) => x,
465                    Err(e) => {
466                        #record_error
467                        None
468                    }
469                }
470            },
471        };
472        // if user function accepts non-option arguments, we assume the function
473        // returns null on null input, so we need to unwrap the inputs before calling.
474        if self.prebuild.is_some() {
475            output = quote! {
476                match (#(#inputs,)*) {
477                    (#(Some(#inputs),)*) => #output,
478                    _ => None,
479                }
480            };
481        } else {
482            #[allow(clippy::disallowed_methods)] // allow zip
483            let some_inputs = inputs
484                .iter()
485                .zip(user_fn.args_option.iter())
486                .map(|(input, opt)| {
487                    if *opt {
488                        quote! { #input }
489                    } else {
490                        quote! { Some(#input) }
491                    }
492                });
493            output = quote! {
494                match (#(#inputs,)*) {
495                    (#(#some_inputs,)*) => #output,
496                    _ => None,
497                }
498            };
499        };
500        // now the `output` is: Option<impl ScalarRef or Scalar>
501        let append_output = match user_fn.writer_type_kind {
502            Some(WriterTypeKind::FmtWrite)
503            | Some(WriterTypeKind::IoWrite)
504            | Some(WriterTypeKind::ListWrite) => quote! {{
505                let mut writer = builder.writer();
506                if #output.is_some() {
507                    writer.finish();
508                } else {
509                    writer.rollback();
510                    builder.append_null();
511                }
512            }},
513            Some(WriterTypeKind::JsonbbBuilder) => quote! {{
514                let mut writer_wrapper = builder.writer();
515                let mut writer = writer_wrapper.inner();
516                if #output.is_some() {
517                    writer_wrapper.finish();
518                } else {
519                    writer_wrapper.rollback();
520                    builder.append_null();
521                }
522            }},
523            None if user_fn.core_return_type == "impl AsRef < [u8] >" => quote! {
524                builder.append(#output.as_ref().map(|s| s.as_ref()));
525            },
526            None => quote! {
527                let output #annotation = #output;
528                builder.append(output.as_ref().map(|s| s.as_scalar_ref()));
529            },
530        };
531        // the output expression in `eval_row`
532        let row_output = match user_fn.writer_type_kind {
533            Some(WriterTypeKind::FmtWrite) => quote! {{
534                let mut writer = String::new();
535                #output.map(|_| writer.into())
536            }},
537            Some(WriterTypeKind::IoWrite) => quote! {{
538                let mut writer = Vec::new();
539                #output.map(|_| writer.into())
540            }},
541            Some(WriterTypeKind::JsonbbBuilder) => quote! {{
542                let mut writer = jsonbb::Builder::<Vec<u8>>::new();
543                #output.map(|_| JsonbVal::from(writer.finish()).into())
544            }},
545            Some(WriterTypeKind::ListWrite) => quote! {{
546                let mut writer = {
547                    let DataType::List(list_ty) = &self.context.return_type else {
548                        panic!("data type must be DataType::List");
549                    };
550                    list_ty.elem().create_array_builder(1)
551                };
552                #output.map(|_| ListValue::new(writer.finish()).into())
553            }},
554            None if user_fn.core_return_type == "impl AsRef < [u8] >" => quote! {
555                #output.map(|s| s.as_ref().into())
556            },
557            None => quote! {{
558                let output #annotation = #output;
559                output.map(|s| s.into())
560            }},
561        };
562        // the main body in `eval`
563        let eval = if let Some(batch_fn) = &self.batch_fn {
564            assert!(
565                !variadic,
566                "customized batch function is not supported for variadic functions"
567            );
568            // user defined batch function
569            let fn_name = format_ident!("{}", batch_fn);
570            quote! {
571                let c = #fn_name(#(#arrays),*);
572                Arc::new(c.into())
573            }
574        } else if (types::is_primitive(&self.ret) || self.ret == "boolean")
575            && user_fn.is_pure()
576            && !variadic
577            && self.prebuild.is_none()
578        {
579            // SIMD optimization for primitive types
580            match self.args.len() {
581                0 => quote! {
582                    let c = #ret_array_type::from_iter_bitmap(
583                        std::iter::repeat_with(|| #fn_name()).take(input.capacity()),
584                        Bitmap::ones(input.capacity()),
585                    );
586                    Arc::new(c.into())
587                },
588                1 => quote! {
589                    let c = #ret_array_type::from_iter_bitmap(
590                        a0.raw_iter().map(|a| #fn_name(a)),
591                        a0.null_bitmap().clone()
592                    );
593                    Arc::new(c.into())
594                },
595                2 => quote! {
596                    // allow using `zip` for performance
597                    #[allow(clippy::disallowed_methods)]
598                    let c = #ret_array_type::from_iter_bitmap(
599                        a0.raw_iter()
600                            .zip(a1.raw_iter())
601                            .map(|(a, b)| #fn_name #generic(a, b)),
602                        a0.null_bitmap() & a1.null_bitmap(),
603                    );
604                    Arc::new(c.into())
605                },
606                n => todo!("SIMD optimization for {n} arguments"),
607            }
608        } else {
609            // no optimization
610            let let_variadic = variadic.then(|| {
611                quote! {
612                    let variadic_row = variadic_input.row_at_unchecked_vis(i);
613                }
614            });
615            quote! {
616                let mut builder = #builder_type::with_type(input.capacity(), self.context.return_type.clone());
617
618                if input.is_vis_compacted() {
619                    for i in 0..input.capacity() {
620                        #(let #inputs = unsafe { #arrays.value_at_unchecked(i) };)*
621                        #let_variadic
622                        #append_output
623                    }
624                } else {
625                    for i in 0..input.capacity() {
626                        if unsafe { !input.visibility().is_set_unchecked(i) } {
627                            builder.append_null();
628                            continue;
629                        }
630                        #(let #inputs = unsafe { #arrays.value_at_unchecked(i) };)*
631                        #let_variadic
632                        #append_output
633                    }
634                }
635                Arc::new(builder.finish().into())
636            }
637        };
638
639        let sync_impl = if user_fn.async_ {
640            quote! {}
641        } else {
642            quote! {
643                #[derive(Debug)]
644                struct #struct_name {
645                    context: Context,
646                    children: Vec<Arc<dyn risingwave_expr::expr::SyncExpression>>,
647                    prebuilt_arg: #prebuilt_arg_type,
648                }
649                impl risingwave_expr::expr::ExpressionInfo for #struct_name {
650                    fn return_type(&self) -> DataType {
651                        self.context.return_type.clone()
652                    }
653                }
654                impl risingwave_expr::expr::SyncExpression for #struct_name {
655                    fn eval(&self, input: &DataChunk) -> Result<ArrayRef> {
656                        #(
657                            let #array_refs = self.children[#children_indices].eval(input)?;
658                            let #arrays: &#arg_arrays = #array_refs.as_ref().into();
659                        )*
660                        #eval_variadic_sync
661                        let mut errors = vec![];
662                        let array = { #eval };
663                        if errors.is_empty() {
664                            Ok(array)
665                        } else {
666                            Err(ExprError::Multiple(array, errors.into()))
667                        }
668                    }
669                    fn eval_row(&self, input: &OwnedRow) -> Result<Datum> {
670                        #(
671                            let #datums = self.children[#children_indices].eval_row(input)?;
672                            let #inputs: Option<#arg_types> = #datums.as_ref().map(|s| s.as_scalar_ref_impl().try_into().unwrap());
673                        )*
674                        #eval_row_variadic_sync
675                        let mut errors: Vec<ExprError> = vec![];
676                        let output = #row_output;
677                        if let Some(err) = errors.into_iter().next() {
678                            Err(err.into())
679                        } else {
680                            Ok(output)
681                        }
682                    }
683                }
684            }
685        };
686        let build_sync = if user_fn.async_ {
687            quote! {}
688        } else {
689            quote! {
690                use risingwave_expr::expr::try_into_sync_exprs;
691
692                let children = match try_into_sync_exprs(children) {
693                    Ok(children) => {
694                        return Ok(#struct_name {
695                            context,
696                            children,
697                            prebuilt_arg,
698                        }.boxed());
699                    }
700                    Err(children) => children,
701                };
702            }
703        };
704
705        Ok(quote! {
706            |return_type: DataType, children: Vec<risingwave_expr::expr::BoxedExpression>|
707                -> risingwave_expr::Result<risingwave_expr::expr::BoxedExpression>
708            {
709                use std::sync::Arc;
710                use risingwave_common::array::*;
711                use risingwave_common::types::*;
712                use risingwave_common::bitmap::Bitmap;
713                use risingwave_common::row::OwnedRow;
714                use risingwave_common::util::iter_util::ZipEqFast;
715
716                use risingwave_expr::expr::{Context, BoxedExpression, SyncExpressionBoxExt, AsyncExpressionBoxExt};
717                use risingwave_expr::{ExprError, Result};
718                use risingwave_expr::codegen::*;
719
720                #check_children
721                let prebuilt_arg = #prebuild_const;
722                let context = Context {
723                    return_type,
724                    arg_types: children.iter().map(|c| c.return_type()).collect(),
725                    variadic: #variadic,
726                };
727
728                #sync_impl
729
730                #[derive(Debug)]
731                struct #async_struct_name {
732                    context: Context,
733                    children: Vec<BoxedExpression>,
734                    prebuilt_arg: #prebuilt_arg_type,
735                }
736                impl risingwave_expr::expr::ExpressionInfo for #async_struct_name {
737                    fn return_type(&self) -> DataType {
738                        self.context.return_type.clone()
739                    }
740                }
741                impl risingwave_expr::expr::AsyncExpression for #async_struct_name {
742                    async fn eval(&self, input: &DataChunk) -> Result<ArrayRef> {
743                        #(
744                            let #array_refs = self.children[#children_indices].eval(input).await?;
745                            let #arrays: &#arg_arrays = #array_refs.as_ref().into();
746                        )*
747                        #eval_variadic_async
748                        let mut errors = vec![];
749                        let array = { #eval };
750                        if errors.is_empty() {
751                            Ok(array)
752                        } else {
753                            Err(ExprError::Multiple(array, errors.into()))
754                        }
755                    }
756                    async fn eval_row(&self, input: &OwnedRow) -> Result<Datum> {
757                        #(
758                            let #datums = self.children[#children_indices].eval_row(input).await?;
759                            let #inputs: Option<#arg_types> = #datums.as_ref().map(|s| s.as_scalar_ref_impl().try_into().unwrap());
760                        )*
761                        #eval_row_variadic_async
762                        let mut errors: Vec<ExprError> = vec![];
763                        let output = #row_output;
764                        if let Some(err) = errors.into_iter().next() {
765                            Err(err.into())
766                        } else {
767                            Ok(output)
768                        }
769                    }
770                }
771
772                #build_sync
773
774                Ok(#async_struct_name {
775                    context,
776                    children,
777                    prebuilt_arg,
778                }.boxed())
779            }
780        })
781    }
782
783    /// Generate a descriptor of the aggregate function.
784    ///
785    /// The types of arguments and return value should not contain wildcard.
786    /// `user_fn` could be either `fn` or `impl`.
787    /// If `build_fn` is true, `user_fn` must be a `fn` that builds the aggregate function.
788    pub fn generate_aggregate_descriptor(
789        &self,
790        user_fn: &AggregateFnOrImpl,
791        build_fn: bool,
792    ) -> Result<TokenStream2> {
793        let name = self.name.clone();
794
795        let mut args = Vec::with_capacity(self.args.len());
796        for ty in &self.args {
797            args.push(sig_data_type(ty));
798        }
799        let ret = sig_data_type(&self.ret);
800        let state_type = match &self.state {
801            Some(ty) if ty != "ref" => {
802                let ty = data_type(ty);
803                quote! { Some(#ty) }
804            }
805            _ => quote! { None },
806        };
807        let append_only = match build_fn {
808            false => !user_fn.has_retract(),
809            true => self.append_only,
810        };
811
812        let pb_kind = format_ident!("{}", utils::to_camel_case(&name));
813        let ctor_name = match append_only {
814            false => format_ident!("{}", self.ident_name()),
815            true => format_ident!("{}_append_only", self.ident_name()),
816        };
817        let build_fn = if build_fn {
818            let name = format_ident!("{}", user_fn.as_fn().name);
819            quote! { #name }
820        } else if self.rewritten {
821            quote! { |_| Err(ExprError::UnsupportedFunction(#name.into())) }
822        } else {
823            self.generate_agg_build_fn(user_fn)?
824        };
825        let build_retractable = match append_only {
826            true => quote! { None },
827            false => quote! { Some(#build_fn) },
828        };
829        let build_append_only = match append_only {
830            false => quote! { None },
831            true => quote! { Some(#build_fn) },
832        };
833        let retractable_state_type = match append_only {
834            true => quote! { None },
835            false => state_type.clone(),
836        };
837        let append_only_state_type = match append_only {
838            false => quote! { None },
839            true => state_type,
840        };
841        let type_infer_fn = self.generate_type_infer_fn()?;
842        let deprecated = self.deprecated;
843        let maybe_allow_deprecated = if deprecated {
844            quote! { #[allow(deprecated)] }
845        } else {
846            quote! {}
847        };
848
849        Ok(quote! {
850            #[risingwave_expr::codegen::linkme::distributed_slice(risingwave_expr::sig::FUNCTIONS)]
851            fn #ctor_name() -> risingwave_expr::sig::FuncSign {
852                use risingwave_common::types::{DataType, DataTypeName};
853                use risingwave_expr::sig::{FuncSign, SigDataType, FuncBuilder};
854
855                #maybe_allow_deprecated
856                FuncSign {
857                    name: risingwave_pb::expr::agg_call::PbKind::#pb_kind.into(),
858                    inputs_type: vec![#(#args),*],
859                    variadic: false,
860                    ret_type: #ret,
861                    build: FuncBuilder::Aggregate {
862                        retractable: #build_retractable,
863                        append_only: #build_append_only,
864                        retractable_state_type: #retractable_state_type,
865                        append_only_state_type: #append_only_state_type,
866                    },
867                    type_infer: #type_infer_fn,
868                    deprecated: #deprecated,
869                    is_async: false,
870                }
871            }
872        })
873    }
874
875    /// Generate build function for aggregate function.
876    fn generate_agg_build_fn(&self, user_fn: &AggregateFnOrImpl) -> Result<TokenStream2> {
877        // If the first argument of the aggregate function is of type `&mut T`,
878        // we assume it is a user defined state type.
879        let custom_state = user_fn.accumulate().first_mut_ref_arg.as_ref();
880        let state_type: TokenStream2 = match (custom_state, &self.state) {
881            (Some(s), _) => s.parse().unwrap(),
882            (_, Some(state)) if state == "ref" => types::ref_type(&self.ret).parse().unwrap(),
883            (_, Some(state)) if state != "ref" => types::owned_type(state).parse().unwrap(),
884            _ => types::owned_type(&self.ret).parse().unwrap(),
885        };
886        let let_arrays = self
887            .args
888            .iter()
889            .enumerate()
890            .map(|(i, arg)| {
891                let array = format_ident!("a{i}");
892                let array_type: TokenStream2 = types::array_type(arg).parse().unwrap();
893                quote! {
894                    let #array: &#array_type = input.column_at(#i).as_ref().into();
895                }
896            })
897            .collect_vec();
898        let let_values = (0..self.args.len())
899            .map(|i| {
900                let v = format_ident!("v{i}");
901                let a = format_ident!("a{i}");
902                quote! { let #v = unsafe { #a.value_at_unchecked(row_id) }; }
903            })
904            .collect_vec();
905        let downcast_state = if custom_state.is_some() {
906            quote! { let mut state: &mut #state_type = state0.downcast_mut(); }
907        } else if let Some(s) = &self.state
908            && s == "ref"
909        {
910            quote! { let mut state: Option<#state_type> = state0.as_datum_mut().as_ref().map(|x| x.as_scalar_ref_impl().try_into().unwrap()); }
911        } else {
912            quote! { let mut state: Option<#state_type> = state0.as_datum_mut().take().map(|s| s.try_into().unwrap()); }
913        };
914        let restore_state = if custom_state.is_some() {
915            quote! {}
916        } else if let Some(s) = &self.state
917            && s == "ref"
918        {
919            quote! { *state0.as_datum_mut() = state.map(|x| x.to_owned_scalar().into()); }
920        } else {
921            quote! { *state0.as_datum_mut() = state.map(|s| s.into()); }
922        };
923        let create_state = if custom_state.is_some() {
924            quote! {
925                fn create_state(&self) -> Result<AggregateState> {
926                    Ok(AggregateState::Any(Box::<#state_type>::default()))
927                }
928            }
929        } else if let Some(state) = &self.init_state {
930            let state: TokenStream2 = state.parse().unwrap();
931            quote! {
932                fn create_state(&self) -> Result<AggregateState> {
933                    Ok(AggregateState::Datum(Some(#state.into())))
934                }
935            }
936        } else {
937            // by default: `AggregateState::Datum(None)`
938            quote! {}
939        };
940        let args = (0..self.args.len()).map(|i| format_ident!("v{i}"));
941        let args = quote! { #(#args,)* };
942        let panic_on_retract = {
943            let msg = format!(
944                "attempt to retract on aggregate function {}, but it is append-only",
945                self.name
946            );
947            quote! { assert_eq!(op, Op::Insert, #msg); }
948        };
949        let mut next_state = match user_fn {
950            AggregateFnOrImpl::Fn(f) => {
951                let context = f.context.then(|| quote! { &self.context, });
952                let fn_name = format_ident!("{}", f.name);
953                match f.retract {
954                    true => {
955                        quote! { #fn_name(state, #args matches!(op, Op::Delete | Op::UpdateDelete) #context) }
956                    }
957                    false => quote! {{
958                        #panic_on_retract
959                        #fn_name(state, #args #context)
960                    }},
961                }
962            }
963            AggregateFnOrImpl::Impl(i) => {
964                let retract = match i.retract {
965                    Some(_) => quote! { self.function.retract(state, #args) },
966                    None => panic_on_retract,
967                };
968                quote! {
969                    if matches!(op, Op::Delete | Op::UpdateDelete) {
970                        #retract
971                    } else {
972                        self.function.accumulate(state, #args)
973                    }
974                }
975            }
976        };
977        next_state = match user_fn.accumulate().return_type_kind {
978            ReturnTypeKind::T => quote! { Some(#next_state) },
979            ReturnTypeKind::Option => next_state,
980            ReturnTypeKind::Result => quote! { Some(#next_state?) },
981            ReturnTypeKind::ResultOption => quote! { #next_state? },
982        };
983        if user_fn.accumulate().args_option.iter().all(|b| !b) {
984            match self.args.len() {
985                0 => {
986                    next_state = quote! {
987                        match state {
988                            Some(state) => #next_state,
989                            None => state,
990                        }
991                    };
992                }
993                1 => {
994                    let first_state = if self.init_state.is_some() {
995                        // for count, the state will never be None
996                        quote! { unreachable!() }
997                    } else if let Some(s) = &self.state
998                        && s == "ref"
999                    {
1000                        // for min/max/first/last, the state is the first value
1001                        quote! { Some(v0) }
1002                    } else if let AggregateFnOrImpl::Impl(impl_) = user_fn
1003                        && impl_.create_state.is_some()
1004                    {
1005                        // use user-defined create_state function
1006                        quote! {{
1007                            let state = self.function.create_state();
1008                            #next_state
1009                        }}
1010                    } else {
1011                        quote! {{
1012                            let state = #state_type::default();
1013                            #next_state
1014                        }}
1015                    };
1016                    next_state = quote! {
1017                        match (state, v0) {
1018                            (Some(state), Some(v0)) => #next_state,
1019                            (None, Some(v0)) => #first_state,
1020                            (state, None) => state,
1021                        }
1022                    };
1023                }
1024                _ => todo!("multiple arguments are not supported for non-option function"),
1025            }
1026        }
1027        let update_state = if custom_state.is_some() {
1028            quote! { _ = #next_state; }
1029        } else {
1030            quote! { state = #next_state; }
1031        };
1032        let get_result = if custom_state.is_some() {
1033            quote! { Ok(state.downcast_ref::<#state_type>().into()) }
1034        } else if let AggregateFnOrImpl::Impl(impl_) = user_fn
1035            && impl_.finalize.is_some()
1036        {
1037            quote! {
1038                let state = match state.as_datum() {
1039                    Some(s) => s.as_scalar_ref_impl().try_into().unwrap(),
1040                    None => return Ok(None),
1041                };
1042                Ok(Some(self.function.finalize(state).into()))
1043            }
1044        } else {
1045            quote! { Ok(state.as_datum().clone()) }
1046        };
1047        let function_field = match user_fn {
1048            AggregateFnOrImpl::Fn(_) => quote! {},
1049            AggregateFnOrImpl::Impl(i) => {
1050                let struct_name = format_ident!("{}", i.struct_name);
1051                let generic = self.generic.as_ref().map(|g| {
1052                    let g = format_ident!("{g}");
1053                    quote! { <#g> }
1054                });
1055                quote! { function: #struct_name #generic, }
1056            }
1057        };
1058        let function_new = match user_fn {
1059            AggregateFnOrImpl::Fn(_) => quote! {},
1060            AggregateFnOrImpl::Impl(i) => {
1061                let struct_name = format_ident!("{}", i.struct_name);
1062                let generic = self.generic.as_ref().map(|g| {
1063                    let g = format_ident!("{g}");
1064                    quote! { ::<#g> }
1065                });
1066                quote! { function: #struct_name #generic :: default(), }
1067            }
1068        };
1069
1070        Ok(quote! {
1071            |agg| {
1072                use std::collections::HashSet;
1073                use std::ops::Range;
1074                use risingwave_common::array::*;
1075                use risingwave_common::types::*;
1076                use risingwave_common::bail;
1077                use risingwave_common::bitmap::Bitmap;
1078                use risingwave_common_estimate_size::EstimateSize;
1079
1080                use risingwave_expr::expr::Context;
1081                use risingwave_expr::Result;
1082                use risingwave_expr::aggregate::AggregateState;
1083                use risingwave_expr::codegen::async_trait;
1084
1085                let context = Context {
1086                    return_type: agg.return_type.clone(),
1087                    arg_types: agg.args.arg_types().to_owned(),
1088                    variadic: false,
1089                };
1090
1091                struct Agg {
1092                    context: Context,
1093                    #function_field
1094                }
1095
1096                #[async_trait]
1097                impl risingwave_expr::aggregate::AggregateFunction for Agg {
1098                    fn return_type(&self) -> DataType {
1099                        self.context.return_type.clone()
1100                    }
1101
1102                    #create_state
1103
1104                    async fn update(&self, state0: &mut AggregateState, input: &StreamChunk) -> Result<()> {
1105                        #(#let_arrays)*
1106                        #downcast_state
1107                        for row_id in input.visibility().iter_ones() {
1108                            let op = unsafe { *input.ops().get_unchecked(row_id) };
1109                            #(#let_values)*
1110                            #update_state
1111                        }
1112                        #restore_state
1113                        Ok(())
1114                    }
1115
1116                    async fn update_range(&self, state0: &mut AggregateState, input: &StreamChunk, range: Range<usize>) -> Result<()> {
1117                        assert!(range.end <= input.capacity());
1118                        #(#let_arrays)*
1119                        #downcast_state
1120                        if input.is_vis_compacted() {
1121                            for row_id in range {
1122                                let op = unsafe { *input.ops().get_unchecked(row_id) };
1123                                #(#let_values)*
1124                                #update_state
1125                            }
1126                        } else {
1127                            for row_id in input.visibility().iter_ones() {
1128                                if row_id < range.start {
1129                                    continue;
1130                                } else if row_id >= range.end {
1131                                    break;
1132                                }
1133                                let op = unsafe { *input.ops().get_unchecked(row_id) };
1134                                #(#let_values)*
1135                                #update_state
1136                            }
1137                        }
1138                        #restore_state
1139                        Ok(())
1140                    }
1141
1142                    async fn get_result(&self, state: &AggregateState) -> Result<Datum> {
1143                        #get_result
1144                    }
1145                }
1146
1147                Ok(Box::new(Agg {
1148                    context,
1149                    #function_new
1150                }))
1151            }
1152        })
1153    }
1154
1155    /// Generate a descriptor of the table function.
1156    ///
1157    /// The types of arguments and return value should not contain wildcard.
1158    fn generate_table_function_descriptor(
1159        &self,
1160        user_fn: &UserFunctionAttr,
1161        build_fn: bool,
1162    ) -> Result<TokenStream2> {
1163        let name = self.name.clone();
1164        let mut args = Vec::with_capacity(self.args.len());
1165        for ty in &self.args {
1166            args.push(sig_data_type(ty));
1167        }
1168        let ret = sig_data_type(&self.ret);
1169
1170        let pb_type = format_ident!("{}", utils::to_camel_case(&name));
1171        let ctor_name = format_ident!("{}", self.ident_name());
1172        let build_fn = if build_fn {
1173            let name = format_ident!("{}", user_fn.name);
1174            quote! { #name }
1175        } else if self.rewritten {
1176            quote! { |_, _| Err(ExprError::UnsupportedFunction(#name.into())) }
1177        } else {
1178            self.generate_build_table_function(user_fn)?
1179        };
1180        let type_infer_fn = self.generate_type_infer_fn()?;
1181        let deprecated = self.deprecated;
1182        let maybe_allow_deprecated = if deprecated {
1183            quote! { #[allow(deprecated)] }
1184        } else {
1185            quote! {}
1186        };
1187
1188        Ok(quote! {
1189            #[risingwave_expr::codegen::linkme::distributed_slice(risingwave_expr::sig::FUNCTIONS)]
1190            fn #ctor_name() -> risingwave_expr::sig::FuncSign {
1191                use risingwave_common::types::{DataType, DataTypeName};
1192                use risingwave_expr::sig::{FuncSign, SigDataType, FuncBuilder};
1193
1194                #maybe_allow_deprecated
1195                FuncSign {
1196                    name: risingwave_pb::expr::table_function::Type::#pb_type.into(),
1197                    inputs_type: vec![#(#args),*],
1198                    variadic: false,
1199                    ret_type: #ret,
1200                    build: FuncBuilder::Table(#build_fn),
1201                    type_infer: #type_infer_fn,
1202                    deprecated: #deprecated,
1203                    is_async: false,
1204                }
1205            }
1206        })
1207    }
1208
1209    fn generate_build_table_function(&self, user_fn: &UserFunctionAttr) -> Result<TokenStream2> {
1210        let num_args = self.args.len();
1211        let return_types = output_types(&self.ret);
1212        let fn_name = format_ident!("{}", user_fn.name);
1213        let struct_name = format_ident!("{}", utils::to_camel_case(&self.ident_name()));
1214        let arg_ids = (0..num_args)
1215            .filter(|i| match &self.prebuild {
1216                Some(s) => !s.contains(&format!("${i}")),
1217                None => true,
1218            })
1219            .collect_vec();
1220        let const_ids = (0..num_args).filter(|i| match &self.prebuild {
1221            Some(s) => s.contains(&format!("${i}")),
1222            None => false,
1223        });
1224        let inputs: Vec<_> = arg_ids.iter().map(|i| format_ident!("i{i}")).collect();
1225        let all_child: Vec<_> = (0..num_args).map(|i| format_ident!("child{i}")).collect();
1226        let const_child: Vec<_> = const_ids.map(|i| format_ident!("child{i}")).collect();
1227        let child: Vec<_> = arg_ids.iter().map(|i| format_ident!("child{i}")).collect();
1228        let array_refs: Vec<_> = arg_ids.iter().map(|i| format_ident!("array{i}")).collect();
1229        let arrays: Vec<_> = arg_ids.iter().map(|i| format_ident!("a{i}")).collect();
1230        let arg_arrays = arg_ids
1231            .iter()
1232            .map(|i| format_ident!("{}", types::array_type(&self.args[*i])));
1233        let outputs = (0..return_types.len())
1234            .map(|i| format_ident!("o{i}"))
1235            .collect_vec();
1236        let builders = (0..return_types.len())
1237            .map(|i| format_ident!("builder{i}"))
1238            .collect_vec();
1239        let builder_types = return_types
1240            .iter()
1241            .map(|ty| format_ident!("{}Builder", types::array_type(ty)))
1242            .collect_vec();
1243        let return_types = if return_types.len() == 1 {
1244            vec![quote! { self.context.return_type.clone() }]
1245        } else {
1246            (0..return_types.len())
1247                .map(|i| quote! { self.context.return_type.as_struct().types().nth(#i).unwrap().clone() })
1248                .collect()
1249        };
1250        #[allow(clippy::disallowed_methods)]
1251        let optioned_outputs = user_fn
1252            .core_return_type
1253            .split(',')
1254            .map(|t| t.contains("Option"))
1255            // example: "(Option<&str>, i32)" => [true, false]
1256            .zip(&outputs)
1257            .map(|(optional, o)| match optional {
1258                false => quote! { Some(#o.as_scalar_ref()) },
1259                true => quote! { #o.map(|o| o.as_scalar_ref()) },
1260            })
1261            .collect_vec();
1262        let build_value_array = if return_types.len() == 1 {
1263            quote! { let [value_array] = value_arrays; }
1264        } else {
1265            quote! {
1266                let value_array = StructArray::new(
1267                    self.context.return_type.as_struct().clone(),
1268                    value_arrays.to_vec(),
1269                    Bitmap::ones(len),
1270                ).into_ref();
1271            }
1272        };
1273        let context = user_fn.context.then(|| quote! { &self.context, });
1274        let prebuilt_arg = match &self.prebuild {
1275            Some(_) => quote! { &self.prebuilt_arg, },
1276            None => quote! {},
1277        };
1278        let prebuilt_arg_type = match &self.prebuild {
1279            Some(s) => s.split("::").next().unwrap().parse().unwrap(),
1280            None => quote! { () },
1281        };
1282        let prebuilt_arg_value = match &self.prebuild {
1283            Some(s) => s
1284                .replace('$', "child")
1285                .parse()
1286                .expect("invalid prebuild syntax"),
1287            None => quote! { () },
1288        };
1289        let iter = quote! { #fn_name(#(#inputs,)* #prebuilt_arg #context) };
1290        let mut iter = match user_fn.return_type_kind {
1291            ReturnTypeKind::T => quote! { #iter },
1292            ReturnTypeKind::Option => quote! { match #iter {
1293                Some(it) => it,
1294                None => continue,
1295            } },
1296            ReturnTypeKind::Result => quote! { match #iter {
1297                Ok(it) => it,
1298                Err(e) => {
1299                    index_builder.append(Some(i as i32));
1300                    #(#builders.append_null();)*
1301                    error_builder.append_display(Some(e.as_report()));
1302                    continue;
1303                }
1304            } },
1305            ReturnTypeKind::ResultOption => quote! { match #iter {
1306                Ok(Some(it)) => it,
1307                Ok(None) => continue,
1308                Err(e) => {
1309                    index_builder.append(Some(i as i32));
1310                    #(#builders.append_null();)*
1311                    error_builder.append_display(Some(e.as_report()));
1312                    continue;
1313                }
1314            } },
1315        };
1316        // if user function accepts non-option arguments, we assume the function
1317        // returns empty on null input, so we need to unwrap the inputs before calling.
1318        #[allow(clippy::disallowed_methods)] // allow zip
1319        let some_inputs = inputs
1320            .iter()
1321            .zip(user_fn.args_option.iter())
1322            .map(|(input, opt)| {
1323                if *opt {
1324                    quote! { #input }
1325                } else {
1326                    quote! { Some(#input) }
1327                }
1328            });
1329        iter = quote! {
1330            match (#(#inputs,)*) {
1331                (#(#some_inputs,)*) => #iter,
1332                _ => continue,
1333            }
1334        };
1335        let iterator_item_type = user_fn.iterator_item_kind.clone().ok_or_else(|| {
1336            Error::new(
1337                user_fn.return_type_span,
1338                "expect `impl Iterator` in return type",
1339            )
1340        })?;
1341        let append_output = match iterator_item_type {
1342            ReturnTypeKind::T => quote! {
1343                let (#(#outputs),*) = output;
1344                #(#builders.append(#optioned_outputs);)* error_builder.append_null();
1345            },
1346            ReturnTypeKind::Option => quote! { match output {
1347                Some((#(#outputs),*)) => { #(#builders.append(#optioned_outputs);)* error_builder.append_null(); }
1348                None => { #(#builders.append_null();)* error_builder.append_null(); }
1349            } },
1350            ReturnTypeKind::Result => quote! { match output {
1351                Ok((#(#outputs),*)) => { #(#builders.append(#optioned_outputs);)* error_builder.append_null(); }
1352                Err(e) => { #(#builders.append_null();)* error_builder.append_display(Some(e.as_report())); }
1353            } },
1354            ReturnTypeKind::ResultOption => quote! { match output {
1355                Ok(Some((#(#outputs),*))) => { #(#builders.append(#optioned_outputs);)* error_builder.append_null(); }
1356                Ok(None) => { #(#builders.append_null();)* error_builder.append_null(); }
1357                Err(e) => { #(#builders.append_null();)* error_builder.append_display(Some(e.as_report())); }
1358            } },
1359        };
1360
1361        Ok(quote! {
1362            |return_type, chunk_size, children| {
1363                use risingwave_common::array::*;
1364                use risingwave_common::types::*;
1365                use risingwave_common::bitmap::Bitmap;
1366                use risingwave_common::util::iter_util::ZipEqFast;
1367                use risingwave_expr::expr::{BoxedExpression, Context};
1368                use risingwave_expr::{Result, ExprError};
1369                use risingwave_expr::codegen::*;
1370
1371                risingwave_expr::ensure!(children.len() == #num_args);
1372
1373                let context = Context {
1374                    return_type: return_type.clone(),
1375                    arg_types: children.iter().map(|c| c.return_type()).collect(),
1376                    variadic: false,
1377                };
1378
1379                let mut iter = children.into_iter();
1380                #(let #all_child = iter.next().unwrap();)*
1381                #(
1382                    let #const_child = #const_child.eval_const()?;
1383                    let #const_child = match &#const_child {
1384                        Some(s) => s.as_scalar_ref_impl().try_into()?,
1385                        // the function should always return empty if any const argument is null
1386                        None => return Ok(risingwave_expr::table_function::empty(return_type)),
1387                    };
1388                )*
1389
1390                #[derive(Debug)]
1391                struct #struct_name {
1392                    context: Context,
1393                    chunk_size: usize,
1394                    #(#child: BoxedExpression,)*
1395                    prebuilt_arg: #prebuilt_arg_type,
1396                }
1397                #[async_trait]
1398                impl risingwave_expr::table_function::TableFunction for #struct_name {
1399                    fn return_type(&self) -> DataType {
1400                        self.context.return_type.clone()
1401                    }
1402                    async fn eval<'a>(&'a self, input: &'a DataChunk) -> BoxStream<'a, Result<DataChunk>> {
1403                        self.eval_inner(input)
1404                    }
1405                }
1406                impl #struct_name {
1407                    #[try_stream(boxed, ok = DataChunk, error = ExprError)]
1408                    async fn eval_inner<'a>(&'a self, input: &'a DataChunk) {
1409                        #(
1410                        let #array_refs = self.#child.eval(input).await?;
1411                        let #arrays: &#arg_arrays = #array_refs.as_ref().into();
1412                        )*
1413
1414                        let mut index_builder = I32ArrayBuilder::new(self.chunk_size);
1415                        #(let mut #builders = #builder_types::with_type(self.chunk_size, #return_types);)*
1416                        let mut error_builder = Utf8ArrayBuilder::new(self.chunk_size);
1417
1418                        for i in 0..input.capacity() {
1419                            if unsafe { !input.visibility().is_set_unchecked(i) } {
1420                                continue;
1421                            }
1422                            #(let #inputs = unsafe { #arrays.value_at_unchecked(i) };)*
1423                            for output in #iter {
1424                                index_builder.append(Some(i as i32));
1425                                #append_output
1426
1427                                if index_builder.len() == self.chunk_size {
1428                                    let len = index_builder.len();
1429                                    let index_array = std::mem::replace(&mut index_builder, I32ArrayBuilder::new(self.chunk_size)).finish().into_ref();
1430                                    let value_arrays = [#(std::mem::replace(&mut #builders, #builder_types::with_type(self.chunk_size, #return_types)).finish().into_ref()),*];
1431                                    #build_value_array
1432                                    let error_array = std::mem::replace(&mut error_builder, Utf8ArrayBuilder::new(self.chunk_size)).finish().into_ref();
1433                                    if error_array.null_bitmap().any() {
1434                                        yield DataChunk::new(vec![index_array, value_array, error_array], self.chunk_size);
1435                                    } else {
1436                                        yield DataChunk::new(vec![index_array, value_array], self.chunk_size);
1437                                    }
1438                                }
1439                            }
1440                        }
1441
1442                        if index_builder.len() > 0 {
1443                            let len = index_builder.len();
1444                            let index_array = index_builder.finish().into_ref();
1445                            let value_arrays = [#(#builders.finish().into_ref()),*];
1446                            #build_value_array
1447                            let error_array = error_builder.finish().into_ref();
1448                            if error_array.null_bitmap().any() {
1449                                yield DataChunk::new(vec![index_array, value_array, error_array], len);
1450                            } else {
1451                                yield DataChunk::new(vec![index_array, value_array], len);
1452                            }
1453                        }
1454                    }
1455                }
1456
1457                Ok(Box::new(#struct_name {
1458                    context,
1459                    chunk_size,
1460                    #(#child,)*
1461                    prebuilt_arg: #prebuilt_arg_value,
1462                }))
1463            }
1464        })
1465    }
1466}
1467
1468fn sig_data_type(ty: &str) -> TokenStream2 {
1469    match ty {
1470        "any" => quote! { SigDataType::Any },
1471        "anyarray" => quote! { SigDataType::AnyArray },
1472        "anymap" => quote! { SigDataType::AnyMap },
1473        "vector" => quote! { SigDataType::Vector },
1474        "struct" => quote! { SigDataType::AnyStruct },
1475        _ if ty.starts_with("struct") && ty.contains("any") => quote! { SigDataType::AnyStruct },
1476        _ => {
1477            let datatype = data_type(ty);
1478            quote! { SigDataType::Exact(#datatype) }
1479        }
1480    }
1481}
1482
1483fn data_type(ty: &str) -> TokenStream2 {
1484    if let Some(ty) = ty.strip_suffix("[]") {
1485        let inner_type = data_type(ty);
1486        return quote! { DataType::list(#inner_type) };
1487    }
1488    if ty.starts_with("struct<") {
1489        return quote! { DataType::Struct(#ty.parse().expect("invalid struct type")) };
1490    }
1491    let variant = format_ident!("{}", types::data_type(ty));
1492    // TODO: enable the check
1493    // assert!(
1494    //     !matches!(ty, "any" | "anyarray" | "anymap" | "struct"),
1495    //     "{ty}, {variant}"
1496    // );
1497
1498    quote! { DataType::#variant }
1499}
1500
1501/// Extract multiple output types.
1502///
1503/// ```ignore
1504/// output_types("int4") -> ["int4"]
1505/// output_types("struct<key varchar, value jsonb>") -> ["varchar", "jsonb"]
1506/// ```
1507fn output_types(ty: &str) -> Vec<&str> {
1508    if let Some(s) = ty.strip_prefix("struct<")
1509        && let Some(args) = s.strip_suffix('>')
1510    {
1511        args.split(',')
1512            .map(|s| s.split_whitespace().nth(1).unwrap())
1513            .collect()
1514    } else {
1515        vec![ty]
1516    }
1517}