Skip to content

Commit 4f745ac

Browse files
committed
Add checked legacy text signature overrides
Keep optional-group and CSV display signatures separate from argument binding. Validate explicit overrides against binding metadata in a const context and preserve legacy call behavior. Assisted-by: OpenAI Codex: model version not exposed
1 parent dd8c343 commit 4f745ac

14 files changed

Lines changed: 814 additions & 37 deletions

File tree

‎crates/derive-impl/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ mod pymodule;
2020
mod pypayload;
2121
mod pystructseq;
2222
mod pytraverse;
23+
mod text_signature;
2324

2425
use error::Diagnostic;
2526
use metadata::PunctuatedNestedMeta;

‎crates/derive-impl/src/pyclass.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1413,6 +1413,7 @@ where
14131413
),
14141414
args.context.self_ty_subst.as_ref(),
14151415
None,
1416+
item_meta.text_signature()?.as_ref(),
14161417
);
14171418
let doc_body_pending =
14181419
doc_body_pending_expr(args.context.self_ty_subst.as_ref(), &py_name, rust_doc);
@@ -1823,7 +1824,7 @@ impl ToTokens for GetSetNursery {
18231824
struct MethodItemMeta(ItemMetaInner);
18241825

18251826
impl ItemMeta for MethodItemMeta {
1826-
const ALLOWED_NAMES: &'static [&'static str] = &["name", "raw", "coexist"];
1827+
const ALLOWED_NAMES: &'static [&'static str] = &["name", "raw", "coexist", "text_signature"];
18271828

18281829
fn from_inner(inner: ItemMetaInner) -> Self {
18291830
Self(inner)

‎crates/derive-impl/src/pymodule.rs‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,7 @@ impl ModuleItem for FunctionItem {
678678

679679
let py_name = item_meta.simple_name()?;
680680
let mut flags_signatures = vec![item_meta.signature_from_flags()?];
681+
let mut text_signatures = vec![item_meta.text_signature()?];
681682
let mut py_names = vec![py_name];
682683
for attr_index in self.py_attrs.iter().rev() {
683684
let mut loop_unit = || {
@@ -692,19 +693,31 @@ impl ModuleItem for FunctionItem {
692693
));
693694
}
694695
flags_signatures.push(item_meta.signature_from_flags()?);
696+
text_signatures.push(item_meta.text_signature()?);
695697
py_names.push(py_name);
696698
Ok(())
697699
};
698700
let r = loop_unit();
699701
args.context.errors.ok_or_push(r);
700702
}
701703

704+
if flags_signatures
705+
.iter()
706+
.zip(&text_signatures)
707+
.any(|(flags, text)| *flags && text.is_some())
708+
{
709+
return Err(self.new_syn_error(
710+
ident.span(),
711+
"text_signature and signature_from_flags are mutually exclusive",
712+
));
713+
}
702714
let module = args.doc_module();
703715
let rust_doc = args.attrs.doc().filter(|doc| !doc.is_empty());
704716
let docs = py_names
705717
.iter()
706718
.zip(flags_signatures)
707-
.map(|(py_name, from_flags)| {
719+
.zip(text_signatures)
720+
.map(|((py_name, from_flags), text_signature)| {
708721
let db_doc = if rust_doc.is_some() {
709722
None
710723
} else {
@@ -716,7 +729,15 @@ impl ModuleItem for FunctionItem {
716729
if from_flags {
717730
flags_signature_doc_tokens(func.sig(), py_name, doc)
718731
} else {
719-
internal_doc_tokens(func.sig(), py_name, None, doc, None, Some("$module"))
732+
internal_doc_tokens(
733+
func.sig(),
734+
py_name,
735+
None,
736+
doc,
737+
None,
738+
Some("$module"),
739+
text_signature.as_ref(),
740+
)
720741
}
721742
})
722743
.collect();
Lines changed: 249 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
1+
//! Explicit legacy text signatures. This deliberately accepts a small grammar:
2+
//! positional parameters, a `/`, literal defaults, `**kwargs`, and trailing
3+
//! nested optional positional groups. It is not a Python expression parser.
4+
use proc_macro2::{Span, TokenStream};
5+
use quote::quote;
6+
use syn::{Error, Result};
7+
8+
pub(crate) struct TextSignature {
9+
pub(crate) text: String,
10+
params: Vec<Parameter>,
11+
}
12+
13+
struct Parameter {
14+
name: String,
15+
positional: bool,
16+
optional: bool,
17+
keywords: bool,
18+
}
19+
20+
fn identifier(name: &str) -> bool {
21+
let name = name.strip_prefix('$').unwrap_or(name);
22+
if matches!(
23+
name,
24+
"False"
25+
| "None"
26+
| "True"
27+
| "and"
28+
| "as"
29+
| "assert"
30+
| "async"
31+
| "await"
32+
| "break"
33+
| "class"
34+
| "continue"
35+
| "def"
36+
| "del"
37+
| "elif"
38+
| "else"
39+
| "except"
40+
| "finally"
41+
| "for"
42+
| "from"
43+
| "global"
44+
| "if"
45+
| "import"
46+
| "in"
47+
| "is"
48+
| "lambda"
49+
| "nonlocal"
50+
| "not"
51+
| "or"
52+
| "pass"
53+
| "raise"
54+
| "return"
55+
| "try"
56+
| "while"
57+
| "with"
58+
| "yield"
59+
) {
60+
return false;
61+
}
62+
let mut bytes = name.bytes();
63+
matches!(bytes.next(), Some(b'a'..=b'z' | b'A'..=b'Z' | b'_'))
64+
&& bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
65+
}
66+
67+
impl TextSignature {
68+
pub(crate) fn parse(text: String, span: Span) -> Result<Self> {
69+
let invalid = || Error::new(span, "invalid or unsupported text_signature override");
70+
let body = text
71+
.strip_prefix('(')
72+
.and_then(|s| s.strip_suffix(')'))
73+
.ok_or_else(invalid)?;
74+
let mut params = Vec::new();
75+
if body.contains("[,") {
76+
let mut parts = body.split("[,").collect::<Vec<_>>();
77+
let optional_count = parts.len() - 1;
78+
let ending = format!("{}, /", "]".repeat(optional_count));
79+
let last = parts
80+
.pop()
81+
.unwrap()
82+
.strip_suffix(&ending)
83+
.ok_or_else(invalid)?;
84+
let required = parts.remove(0);
85+
for name in required.split(',').map(str::trim) {
86+
params.push(Parameter {
87+
name: name.into(),
88+
positional: true,
89+
optional: false,
90+
keywords: false,
91+
});
92+
}
93+
for name in parts.into_iter().chain([last]).map(str::trim) {
94+
params.push(Parameter {
95+
name: name.into(),
96+
positional: true,
97+
optional: true,
98+
keywords: false,
99+
});
100+
}
101+
} else {
102+
let mut slash = false;
103+
let mut optional = false;
104+
let mut keywords = false;
105+
for part in body.split(',').map(str::trim) {
106+
if keywords {
107+
return Err(invalid());
108+
}
109+
if part == "/" {
110+
if slash || params.is_empty() {
111+
return Err(invalid());
112+
}
113+
slash = true;
114+
for param in &mut params {
115+
param.positional = true;
116+
}
117+
continue;
118+
}
119+
let (name, default) = match part.split_once('=') {
120+
Some((name, default)) => {
121+
let default = default.trim();
122+
let quoted = (default.starts_with('\'') && default.ends_with('\''))
123+
|| (default.starts_with('"') && default.ends_with('"'));
124+
let literal = if quoted && default.len() >= 2 {
125+
!default[1..default.len() - 1].contains(['\'', '"', '\\', '\n', '\r'])
126+
} else {
127+
matches!(default, "None" | "True" | "False")
128+
|| default
129+
.parse::<i128>()
130+
.is_ok_and(|value| value.to_string() == default)
131+
};
132+
if !literal {
133+
return Err(invalid());
134+
}
135+
(name.trim(), true)
136+
}
137+
None => (part, false),
138+
};
139+
let name = if let Some(name) = name.strip_prefix("**") {
140+
if default {
141+
return Err(invalid());
142+
}
143+
keywords = true;
144+
name
145+
} else {
146+
name
147+
};
148+
if optional && !default && !keywords {
149+
return Err(invalid());
150+
}
151+
optional |= default;
152+
params.push(Parameter {
153+
name: name.into(),
154+
positional: false,
155+
optional: default,
156+
keywords,
157+
});
158+
}
159+
}
160+
for (index, param) in params.iter().enumerate() {
161+
if !identifier(&param.name)
162+
|| params[..index].iter().any(|other| other.name == param.name)
163+
|| (param.name.starts_with('$')
164+
&& (index != 0
165+
|| !param.positional
166+
|| param.optional
167+
|| !matches!(param.name.as_str(), "$self" | "$type" | "$module")))
168+
{
169+
return Err(invalid());
170+
}
171+
}
172+
Ok(Self { text, params })
173+
}
174+
175+
pub(crate) fn params_tokens(&self) -> Vec<TokenStream> {
176+
self.params.iter().map(|param| {
177+
let name = &param.name;
178+
let kind = if param.keywords { quote!(VarKeyword) } else if param.positional { quote!(PositionalOnly) } else { quote!(PositionalOrKeyword) };
179+
let default = if param.optional { quote!(Some(::rustpython_vm::function::DefaultRepr::Unrepresentable)) } else { quote!(None) };
180+
quote! { ::rustpython_vm::function::Param { name: #name, kind: ::rustpython_vm::function::ParamKind::#kind, default: #default } }
181+
}).collect()
182+
}
183+
}
184+
185+
#[cfg(test)]
186+
mod tests {
187+
use super::*;
188+
189+
#[test]
190+
fn supported_overrides() {
191+
for name in ["sub", "prefix", "suffix"] {
192+
let sig = TextSignature::parse(
193+
format!("($self, {name}[, start[, end]], /)"),
194+
Span::call_site(),
195+
)
196+
.unwrap();
197+
assert_eq!(sig.params.len(), 4);
198+
assert!(sig.params[2..].iter().all(|p| p.positional && p.optional));
199+
assert!(!sig.params[1].optional);
200+
}
201+
for name in ["iterable", "fileobj", "name"] {
202+
let sig = TextSignature::parse(
203+
format!("($module, {name}, /, dialect='excel', **fmtparams)"),
204+
Span::call_site(),
205+
)
206+
.unwrap();
207+
assert_eq!(sig.params.len(), 4);
208+
assert!(sig.params[1].positional);
209+
assert!(!sig.params[2].positional);
210+
assert!(sig.params[2].optional);
211+
assert!(sig.params[3].keywords);
212+
}
213+
}
214+
215+
#[test]
216+
fn malformed_overrides() {
217+
for text in [
218+
"()",
219+
"(class, /)",
220+
"(value=01, /)",
221+
"($self, sub[, ], /)",
222+
"($self, sub[, start[, ]], /)",
223+
"($self, sub[, start[, end], /)",
224+
"($self, $self, /)",
225+
"($module, name, /, **name)",
226+
"($module, name, /, **kwargs, **kwargs)",
227+
"($self, sub[, start[, end]]], /)",
228+
"($self, sub[, start], end, /)",
229+
"($self, sub[, start=0], /)",
230+
"($self, sub[, start], /, **kwargs)",
231+
"($self, sub[, start, end], /)",
232+
"($module, name, /, dialect=call(), **fmtparams)",
233+
"($module, name, /, dialect='excel', **fmtparams, extra)",
234+
"($module, name, /, /)",
235+
"($module, name, /, name=None)",
236+
"($module, name)",
237+
"(name, $self, /)",
238+
"($unknown, name, /)",
239+
"($module, name, /, dialect='excel', required)",
240+
"($module, name, /, **kwargs=None)",
241+
"($module, name, /, dialect='excel'junk')",
242+
] {
243+
assert!(
244+
TextSignature::parse(text.into(), Span::call_site()).is_err(),
245+
"{text}"
246+
);
247+
}
248+
}
249+
}

0 commit comments

Comments
 (0)