1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
//! Strict grammar for `#[rig_tool(...)]` arguments.
//!
//! Every argument either matches the grammar or produces a spanned error;
//! nothing is silently ignored, and duplicates are rejected. Name validation
//! against the actual parameter list happens in `expand`, where the function
//! signature is available.
use syn::{
Expr, ExprLit, Ident, Lit, Meta, Token,
parse::{Parse, ParseStream},
punctuated::Punctuated,
};
pub(crate) struct MacroArgs {
pub(crate) name: Option<String>,
pub(crate) description: Option<String>,
/// `params(name = "description")` entries in declaration order. Idents are
/// kept (not strings) so validation errors can point at the exact key.
pub(crate) param_descriptions: Vec<(Ident, String)>,
/// `required(...)` names; `None` means "derive from the parameter types".
pub(crate) required: Option<Vec<Ident>>,
}
impl MacroArgs {
pub(crate) fn description_for(&self, param: &str) -> Option<&str> {
self.param_descriptions
.iter()
.find(|(ident, _)| ident == param)
.map(|(_, description)| description.as_str())
}
}
fn parse_string_literal(expr: &Expr, field_name: &str) -> syn::Result<String> {
match expr {
Expr::Lit(ExprLit {
lit: Lit::Str(lit_str),
..
}) => Ok(lit_str.value()),
_ => Err(syn::Error::new_spanned(
expr,
format!("`{field_name}` must be a string literal"),
)),
}
}
fn validate_explicit_tool_name(name: &str, expr: &Expr) -> syn::Result<()> {
if !(1..=64).contains(&name.chars().count()) {
return Err(syn::Error::new_spanned(
expr,
"`name` must be between 1 and 64 characters long",
));
}
let mut chars = name.chars();
if !chars
.next()
.is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
{
return Err(syn::Error::new_spanned(
expr,
"`name` must start with an ASCII letter or underscore",
));
}
if chars.any(|ch| !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-') {
return Err(syn::Error::new_spanned(
expr,
"`name` may only contain ASCII letters, digits, underscores, or hyphens",
));
}
Ok(())
}
fn reject_duplicate<T>(
slot: &Option<T>,
spanned: impl quote::ToTokens,
what: &str,
) -> syn::Result<()> {
if slot.is_some() {
return Err(syn::Error::new_spanned(
spanned,
format!("duplicate `{what}` argument"),
));
}
Ok(())
}
impl Parse for MacroArgs {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut name = None;
let mut description = None;
let mut param_descriptions: Option<Vec<(Ident, String)>> = None;
let mut required = None;
if input.is_empty() {
return Ok(MacroArgs {
name,
description,
param_descriptions: Vec::new(),
required,
});
}
let meta_list: Punctuated<Meta, Token![,]> = Punctuated::parse_terminated(input)?;
for meta in meta_list {
match meta {
Meta::NameValue(nv) => {
let ident = nv.path.get_ident().ok_or_else(|| {
syn::Error::new_spanned(
&nv.path,
"unsupported top-level #[rig_tool] argument",
)
})?;
match ident.to_string().as_str() {
"name" => {
reject_duplicate(&name, &nv.path, "name")?;
let parsed_name = parse_string_literal(&nv.value, "name")?;
validate_explicit_tool_name(&parsed_name, &nv.value)?;
name = Some(parsed_name);
}
"description" => {
reject_duplicate(&description, &nv.path, "description")?;
description = Some(parse_string_literal(&nv.value, "description")?);
}
_ => {
return Err(syn::Error::new_spanned(
&nv.path,
format!("unsupported top-level #[rig_tool] argument `{ident}`"),
));
}
}
}
Meta::List(list) => {
let ident = list.path.get_ident().ok_or_else(|| {
syn::Error::new_spanned(
&list.path,
"unsupported top-level #[rig_tool] argument",
)
})?;
match ident.to_string().as_str() {
"params" => {
reject_duplicate(¶m_descriptions, &list.path, "params(...)")?;
let nested: Punctuated<Meta, Token![,]> =
list.parse_args_with(Punctuated::parse_terminated)?;
let mut descriptions = Vec::new();
for meta in nested {
let Meta::NameValue(nv) = meta else {
return Err(syn::Error::new_spanned(
meta,
"`params(...)` entries must have the form `name = \"description\"`",
));
};
let Some(param_ident) = nv.path.get_ident().cloned() else {
return Err(syn::Error::new_spanned(
&nv.path,
"parameter descriptions must use identifier keys",
));
};
let value =
parse_string_literal(&nv.value, ¶m_ident.to_string())?;
if descriptions
.iter()
.any(|(existing, _): &(Ident, String)| *existing == param_ident)
{
return Err(syn::Error::new_spanned(
¶m_ident,
format!(
"duplicate `params(...)` entry for `{param_ident}`"
),
));
}
descriptions.push((param_ident, value));
}
param_descriptions = Some(descriptions);
}
"required" => {
reject_duplicate(&required, &list.path, "required(...)")?;
let required_variables: Punctuated<Ident, Token![,]> =
list.parse_args_with(Punctuated::parse_terminated)?;
let mut names: Vec<Ident> = Vec::new();
for ident in required_variables {
if names.contains(&ident) {
return Err(syn::Error::new_spanned(
&ident,
format!("duplicate `required(...)` entry for `{ident}`"),
));
}
names.push(ident);
}
required = Some(names);
}
_ => {
return Err(syn::Error::new_spanned(
&list.path,
format!("unsupported top-level #[rig_tool] argument `{ident}`"),
));
}
}
}
Meta::Path(path) => {
let message = if let Some(ident) = path.get_ident() {
format!("unsupported top-level #[rig_tool] argument `{ident}`")
} else {
"unsupported top-level #[rig_tool] argument".to_string()
};
return Err(syn::Error::new_spanned(path, message));
}
}
}
Ok(MacroArgs {
name,
description,
param_descriptions: param_descriptions.unwrap_or_default(),
required,
})
}
}