hamelin_lib/tree/builder/
functions.rs1use std::sync::Arc;
4
5use ordermap::OrderMap;
6
7use crate::tree::ast::{
8 expression::{Expression, FunctionCall},
9 identifier::{ParsedSimpleIdentifier, SimpleIdentifier},
10 node::Span,
11};
12
13use super::{ExpressionBuilder, IntoExpressionBuilder};
14
15#[derive(Debug)]
17pub struct FunctionCallBuilder {
18 name: SimpleIdentifier,
19 positional_args: Vec<Box<dyn ExpressionBuilder>>,
20 named_args: OrderMap<String, Box<dyn ExpressionBuilder>>,
21}
22
23impl FunctionCallBuilder {
24 pub fn new(name: impl Into<String>) -> Self {
26 let name_str = name.into();
28 Self {
29 name: SimpleIdentifier::new(&name_str),
30 positional_args: Vec::new(),
31 named_args: OrderMap::new(),
32 }
33 }
34
35 pub fn arg(mut self, arg: impl IntoExpressionBuilder) -> Self {
37 self.positional_args.push(arg.into_expression_builder());
38 self
39 }
40
41 pub fn args(mut self, args: impl IntoIterator<Item = impl IntoExpressionBuilder>) -> Self {
43 for arg in args {
44 self.positional_args.push(arg.into_expression_builder());
45 }
46 self
47 }
48
49 pub fn named_arg(mut self, name: impl Into<String>, arg: impl IntoExpressionBuilder) -> Self {
51 self.named_args
52 .insert(name.into(), arg.into_expression_builder());
53 self
54 }
55}
56
57impl ExpressionBuilder for FunctionCallBuilder {
58 fn build(&self) -> Expression {
59 let positional_args = self
60 .positional_args
61 .iter()
62 .map(|arg| Arc::new(arg.build()))
63 .collect();
64
65 let named_args = self
66 .named_args
67 .iter()
68 .map(|(name, arg)| {
69 let ident = ParsedSimpleIdentifier::Valid(SimpleIdentifier::new(name));
71 (ident, Arc::new(arg.build()))
72 })
73 .collect();
74
75 Expression {
76 span: Span::NONE,
77 kind: FunctionCall {
78 name: ParsedSimpleIdentifier::Valid(self.name.clone()),
79 positional_args,
80 named_args,
81 }
82 .into(),
83 }
84 }
85}
86
87impl IntoExpressionBuilder for FunctionCallBuilder {
88 fn into_expression_builder(self) -> Box<dyn ExpressionBuilder> {
89 Box::new(self)
90 }
91}
92
93pub fn call(name: impl Into<String>) -> FunctionCallBuilder {
97 FunctionCallBuilder::new(name)
98}