1use std::fmt::{self, Display};
2
3use crate::{ident::Ident, Docs, Type};
4
5#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
8pub struct Params {
9 items: Vec<(Ident, Type)>,
10}
11
12impl<N> From<(N, Type)> for Params
13where
14 N: Into<Ident>,
15{
16 fn from(value: (N, Type)) -> Self {
17 Self {
18 items: vec![(value.0.into(), value.1)],
19 }
20 }
21}
22
23impl<N> FromIterator<(N, Type)> for Params
24where
25 N: Into<Ident>,
26{
27 fn from_iter<T: IntoIterator<Item = (N, Type)>>(iter: T) -> Self {
28 Self {
29 items: iter.into_iter().map(|(n, t)| (n.into(), t)).collect(),
30 }
31 }
32}
33
34impl Display for Params {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 let mut peekable = self.items.iter().peekable();
37 while let Some((name, type_)) = peekable.next() {
38 write!(f, "{}: {}", name, type_)?;
39 if peekable.peek().is_some() {
40 write!(f, ", ")?;
41 }
42 }
43 Ok(())
44 }
45}
46
47impl Params {
48 pub fn empty() -> Self {
49 Self::default()
50 }
51
52 pub fn push(&mut self, name: impl Into<Ident>, ty: Type) {
53 self.items.push((name.into(), ty));
54 }
55
56 pub fn item(&mut self, name: impl Into<Ident>, item: impl Into<Type>) {
57 self.items.push((name.into(), item.into()));
58 }
59
60 pub fn items(&self) -> &Vec<(Ident, Type)> {
61 &self.items
62 }
63
64 pub fn items_mut(&mut self) -> &mut Vec<(Ident, Type)> {
65 &mut self.items
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
70#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
71#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
72pub struct StandaloneFunc {
73 pub(crate) name: Ident,
74 pub(crate) params: Params,
75 pub(crate) result: Option<Type>,
76 pub(crate) docs: Option<Docs>,
77}
78
79impl StandaloneFunc {
80 pub fn new(name: impl Into<Ident>) -> Self {
81 Self {
82 name: name.into(),
83 params: Params::empty(),
84 result: None,
85 docs: None,
86 }
87 }
88
89 pub fn set_name(&self) -> &Ident {
90 &self.name
91 }
92
93 pub fn name(&self) -> &Ident {
94 &self.name
95 }
96
97 pub fn name_mut(&mut self) -> &mut Ident {
98 &mut self.name
99 }
100
101 pub fn set_params(&mut self, params: impl Into<Params>) {
102 self.params = params.into();
103 }
104
105 pub fn params(&self) -> &Params {
106 &self.params
107 }
108
109 pub fn params_mut(&mut self) -> &mut Params {
110 &mut self.params
111 }
112
113 pub fn result(&self) -> &Option<Type> {
114 &self.result
115 }
116
117 pub fn set_result(&mut self, result: Option<Type>) {
118 self.result = result;
119 }
120
121 pub fn result_mut(&mut self) -> &mut Option<Type> {
122 &mut self.result
123 }
124
125 pub fn set_docs(&mut self, docs: Option<impl Into<Docs>>) {
126 self.docs = docs.map(|d| d.into());
127 }
128
129 pub fn docs(&self) -> &Option<Docs> {
130 &self.docs
131 }
132}