1use syn::{
16 Expr, Lit, Result as SynResult, Token, Type,
17 parse::{Parse, ParseStream},
18};
19
20use quote::ToTokens;
21
22#[cfg(rapx_has_attr_ir)]
23use rustc_attr_ir::Attribute;
24#[cfg(not(rapx_has_attr_ir))]
25use rustc_hir::Attribute;
26use rustc_hir::def_id::DefId;
27use rustc_middle::ty::TyCtxt;
28use rustc_span::Symbol;
29
30use super::Property;
31
32#[derive(Debug, Clone)]
36pub(crate) struct AttrProperty {
37 pub tag: String,
39 pub args: Vec<Expr>,
41 pub kind: Option<String>,
43}
44
45impl Parse for AttrProperty {
46 fn parse(input: ParseStream<'_>) -> SynResult<Self> {
52 let mut property = parse_property_head(input)?;
53
54 if input.peek(Token![,]) {
55 let fork = input.fork();
56 let _: Token![,] = fork.parse()?;
57 if fork.peek(syn::Ident) && fork.peek2(Token![=]) {
58 let _: Token![,] = input.parse()?;
59 let ident: syn::Ident = input.parse()?;
60 let _: Token![=] = input.parse()?;
61 let value: Expr = input.parse()?;
62
63 if ident == "kind" {
64 if let Expr::Lit(ref expr_lit) = value
65 && let Lit::Str(ref kind) = expr_lit.lit
66 {
67 property.kind = Some(kind.value());
68 } else {
69 return Err(syn::Error::new_spanned(
70 value,
71 "RAPx requires attribute kind must be a string literal",
72 ));
73 }
74 } else {
75 return Err(syn::Error::new(
76 ident.span(),
77 "unsupported named RAPx requires attribute argument",
78 ));
79 }
80 }
81 }
82
83 Ok(property)
84 }
85}
86
87pub(crate) fn parse_outer_attr(input: ParseStream<'_>) -> SynResult<syn::Attribute> {
88 input
89 .call(syn::Attribute::parse_outer)?
90 .into_iter()
91 .next()
92 .ok_or_else(|| input.error("expected an outer attribute"))
93}
94
95pub(crate) fn parse_rapx_attr(
100 attr_str: &str,
101 expected_name: &str,
102) -> SynResult<Option<AttrProperty>> {
103 let attr_str = strip_lifetime_ticks(attr_str);
104 let attr = syn::parse::Parser::parse_str(parse_outer_attr, &attr_str)?;
105 if !is_expected_syn_rapx_attr(&attr, expected_name) {
106 return Ok(None);
107 }
108
109 let syn::Meta::List(meta_list) = &attr.meta else {
110 return Ok(None);
111 };
112
113 let property = meta_list.parse_args::<AttrProperty>()?;
114 Ok(Some(property))
115}
116
117fn is_expected_syn_rapx_attr(attr: &syn::Attribute, expected_name: &str) -> bool {
119 let mut segments = attr.path().segments.iter();
120 matches!(
121 (segments.next(), segments.next(), segments.next()),
122 (Some(first), Some(second), None)
123 if first.ident == "rapx" && second.ident == expected_name
124 )
125}
126
127fn parse_property_head(input: ParseStream<'_>) -> SynResult<AttrProperty> {
134 let path: syn::Path = input.parse()?;
135 let tag = path
136 .segments
137 .last()
138 .map(|seg| seg.ident.to_string())
139 .ok_or_else(|| syn::Error::new_spanned(&path, "missing property name"))?;
140
141 let content;
142 syn::parenthesized!(content in input);
143
144 let mut args: Vec<Expr> = Vec::new();
145 while !content.is_empty() {
146 args.push(parse_property_arg(&content)?);
147 if content.is_empty() {
148 break;
149 }
150 content.parse::<Token![,]>()?;
151 }
152
153 Ok(AttrProperty {
154 tag,
155 args,
156 kind: None,
157 })
158}
159
160fn parse_property_arg(input: ParseStream<'_>) -> SynResult<Expr> {
170 if input.peek(syn::token::Paren) {
178 return input.parse::<Expr>();
179 }
180
181 let fork = input.fork();
182 if fork.parse::<Type>().is_ok() && (fork.is_empty() || fork.peek(Token![,])) {
183 let ty: Type = input.parse()?;
184 return Ok(type_to_arg_expr(ty));
185 }
186 input.parse::<Expr>()
187}
188
189fn type_to_arg_expr(ty: Type) -> Expr {
193 if let Type::Path(type_path) = &ty
194 && type_path.qself.is_none()
195 && type_path
196 .path
197 .segments
198 .iter()
199 .all(|s| matches!(s.arguments, syn::PathArguments::None))
200 {
201 return Expr::Path(syn::ExprPath {
202 attrs: Vec::new(),
203 qself: None,
204 path: type_path.path.clone(),
205 });
206 }
207 Expr::Verbatim(ty.to_token_stream())
208}
209
210fn strip_lifetime_ticks(s: &str) -> String {
217 let chars: Vec<char> = s.chars().collect();
218 let mut out = String::with_capacity(s.len());
219 let mut i = 0;
220 while i < chars.len() {
221 match chars[i] {
222 '"' => {
223 out.push('"');
224 i += 1;
225 while i < chars.len() {
226 let c = chars[i];
227 out.push(c);
228 i += 1;
229 if c == '\\' && i < chars.len() {
230 out.push(chars[i]);
231 i += 1;
232 } else if c == '"' {
233 break;
234 }
235 }
236 }
237 '\'' => {
238 let rest: String = chars[i + 1..].iter().collect();
242 if rest.starts_with("static")
243 && chars.get(i + 1 + "static".len()).is_none_or(|&c| !c.is_ascii_alphanumeric() && c != '_')
244 {
245 out.push_str(super::STATIC_LIFETIME_IDENT);
246 i += 1 + "static".len();
247 continue;
248 }
249 let len = match chars.get(i + 1) {
250 Some('\\') if chars.get(i + 3) == Some(&'\'') => 4,
251 Some(_) if chars.get(i + 2) == Some(&'\'') => 3,
252 _ => 0,
253 };
254 if len > 0 {
255 out.extend(&chars[i..i + len]);
256 i += len;
257 } else {
258 i += 1;
259 }
260 }
261 c => {
262 out.push(c);
263 i += 1;
264 }
265 }
266 }
267 out
268}
269
270pub(crate) fn is_rapx_named_attr(tcx: TyCtxt<'_>, attr: &Attribute, name: &str) -> bool {
271 let name = Symbol::intern(name);
272 crate::compat::attribute_path_matches(tcx, attr, &[Symbol::intern("rapx"), name])
273 || crate::compat::attribute_path_matches(tcx, attr, &[name])
274}
275
276pub(crate) fn collect_properties_from_named_attrs<'tcx>(
277 tcx: TyCtxt<'tcx>,
278 attrs: impl IntoIterator<Item = &'tcx Attribute>,
279 property_def_id: DefId,
280 parse_error_label: &str,
281 attr_name: &str,
282) -> Vec<Property<'tcx>> {
283 let mut results = Vec::new();
284
285 for attr in attrs {
286 if !is_rapx_named_attr(tcx, attr, attr_name) {
287 continue;
288 }
289
290 let attr_str = crate::compat::attribute_to_string(tcx, attr);
291 let parsed = match parse_rapx_attr(attr_str.as_str(), attr_name) {
292 Ok(parsed) => parsed,
293 Err(err) => {
294 rap_error!(
295 "Failed to parse RAPx {} attr '{}': {}",
296 parse_error_label,
297 attr_str,
298 err
299 );
300 continue;
301 }
302 };
303
304 let Some(property) = parsed else { continue };
305 results.extend(
306 Property::parse_list(tcx, property_def_id, property.tag.as_str(), &property.args)
307 .into_iter()
308 .map(move |mut p| {
309 p.apply_kind(property.kind.as_deref());
310 p
311 }),
312 );
313 }
314
315 results
316}