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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use std::rc::Rc;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attribute<'a> {
pub is_inner: bool,
pub content: Rc<AttributeMetaItem<'a>>,
}
impl<'a> Attribute<'a> {
/// Checks if the attribute contents contain `#[doc(hidden)]`.
///
/// Also returns `true` if the "hidden" argument is combined with other arguments.
pub(crate) fn is_doc_hidden(raw: &'a str) -> bool {
// We cannot just look for `#[doc(hidden)]` as a string,
// since it might be combined with other arguments to `#[doc]`.
//
// However, we'd like to bail early without parsing the full attribute if possible,
// since parsing is expensive and involves many allocations.
// We can rely on the fact that rustdoc does some formatting and normalization
// of the attributes presented in rustdoc JSON, for example removing unnecessary spaces.
let raw = raw.trim_start();
if !raw.starts_with("#[doc(") {
return false;
}
let attribute = Attribute::new(raw);
// We look for:
// - the base of the attribute is `doc`, and
// - one of its arguments has the base `hidden`.
//
// This gracefully handles complex cases like `#[doc(hidden, alias = "TheAlias")]`.
attribute.content.base == "doc"
&& attribute
.content
.arguments
.iter()
.flatten()
.any(|arg| arg.base == "hidden")
}
pub fn raw_attribute(&self) -> String {
format!(
"#{}[{}]",
if self.is_inner { "!" } else { "" },
self.content.raw_item
)
}
pub fn new(raw: &'a str) -> Self {
let raw_trimmed = raw.trim();
let raw_without_closing = raw_trimmed.strip_suffix(']').unwrap_or_else(|| {
panic!(
"\
String `{raw_trimmed}` cannot be parsed as an attribute \
because it is not closed with a square bracket."
)
});
if let Some(raw_content) = raw_without_closing.strip_prefix("#[") {
Attribute {
is_inner: false,
content: Rc::new(AttributeMetaItem::new(raw_content)),
}
} else if let Some(raw_content) = raw_without_closing.strip_prefix("#![") {
Attribute {
is_inner: true,
content: Rc::new(AttributeMetaItem::new(raw_content)),
}
} else {
panic!(
"\
String `{raw_trimmed}` cannot be parsed as an attribute \
because it starts with neither `#[` nor `#![`."
)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttributeMetaItem<'a> {
pub raw_item: &'a str,
pub base: &'a str,
pub assigned_item: Option<&'a str>,
pub arguments: Option<Vec<Rc<AttributeMetaItem<'a>>>>,
}
impl<'a> AttributeMetaItem<'a> {
fn is_left_bracket(c: char) -> bool {
c == '(' || c == '[' || c == '{'
}
fn is_right_bracket(c: char) -> bool {
c == ')' || c == ']' || c == '}'
}
fn matching_right_bracket(c: char) -> char {
match c {
'(' => ')',
'[' => ']',
'{' => '}',
_ => unreachable!("Tried to find matching right bracket for {c}."),
}
}
/// Tries to parse `raw` as a comma-separated sequence of `AttributeMetaItem`'s
/// wrapped in parentheses, square brackets or curly brackets.
fn slice_arguments(raw: &'a str) -> Option<Vec<Rc<AttributeMetaItem<'a>>>> {
let raw_trimmed = raw.trim();
let first_char = raw_trimmed.chars().next()?;
let raw_meta_seq = raw_trimmed
.strip_prefix(Self::is_left_bracket)?
.strip_suffix(|c| c == Self::matching_right_bracket(first_char))?
.trim();
let mut index_after_last_comma = 0;
let mut previous_is_escape = false;
let mut inside_string_literal = false;
let mut brackets = Vec::new(); // currently opened brackets
let mut arguments: Vec<Rc<AttributeMetaItem>> = Vec::new(); // meta items constructed so far
for (j, c) in raw_meta_seq.char_indices() {
if c == '"' && !previous_is_escape {
inside_string_literal = !inside_string_literal;
}
if !inside_string_literal {
if Self::is_left_bracket(c) {
brackets.push(c);
} else if Self::is_right_bracket(c) {
// If the brackets don't match in any way, give up on parsing
// individual arguments since we don't understand the format.
if let Some(top_left) = brackets.pop() {
if Self::matching_right_bracket(top_left) != c {
return None;
}
} else {
return None;
}
} else if c == ',' {
// We only do a recursive call when the comma is on the outermost level.
if brackets.is_empty() {
arguments.push(Rc::new(AttributeMetaItem::new(
&raw_meta_seq[index_after_last_comma..j],
)));
index_after_last_comma = j + 1;
}
}
}
previous_is_escape = c == '\\';
}
// If the last comma was not a trailing one, there is still one meta item left.
if index_after_last_comma < raw_meta_seq.len() {
arguments.push(Rc::new(AttributeMetaItem::new(
&raw_meta_seq[index_after_last_comma..],
)));
}
Some(arguments)
}
pub fn new(raw: &'a str) -> Self {
let raw_trimmed = raw.trim();
if let Some(path_end) =
raw_trimmed.find(|c: char| c.is_whitespace() || c == '=' || Self::is_left_bracket(c))
{
let simple_path = &raw_trimmed[0..path_end];
let attr_input = &raw_trimmed[path_end..];
if !simple_path.is_empty() {
if let Some(assigned) = attr_input.trim().strip_prefix('=') {
return AttributeMetaItem {
raw_item: raw_trimmed,
base: simple_path,
assigned_item: Some(assigned.trim_start()),
arguments: None,
};
} else if let Some(arguments) = Self::slice_arguments(attr_input) {
return AttributeMetaItem {
raw_item: raw_trimmed,
base: simple_path,
assigned_item: None,
arguments: Some(arguments),
};
}
}
}
AttributeMetaItem {
raw_item: raw_trimmed,
base: raw_trimmed,
assigned_item: None,
arguments: None,
}
}
}
#[cfg(test)]
mod tests {
use std::rc::Rc;
use super::{Attribute, AttributeMetaItem};
#[test]
fn is_doc_hidden() {
let doc_hidden = Attribute::is_doc_hidden("#[doc(hidden, alias = \"TheAlias\")]");
assert!(doc_hidden);
}
#[test]
fn attribute_simple_inner() {
let attribute = Attribute::new("#![no_std]");
assert_eq!(
attribute,
Attribute {
is_inner: true,
content: Rc::new(AttributeMetaItem {
raw_item: "no_std",
base: "no_std",
assigned_item: None,
arguments: None
})
}
);
assert_eq!(attribute.raw_attribute(), "#![no_std]");
}
#[test]
fn attribute_complex_outer() {
let attribute =
Attribute::new("#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]");
assert_eq!(
attribute,
Attribute {
is_inner: false,
content: Rc::new(AttributeMetaItem {
raw_item: "cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))",
base: "cfg_attr",
assigned_item: None,
arguments: Some(vec![
Rc::new(AttributeMetaItem {
raw_item: "feature = \"serde\"",
base: "feature",
assigned_item: Some("\"serde\""),
arguments: None
}),
Rc::new(AttributeMetaItem {
raw_item: "derive(Serialize, Deserialize)",
base: "derive",
assigned_item: None,
arguments: Some(vec![
Rc::new(AttributeMetaItem {
raw_item: "Serialize",
base: "Serialize",
assigned_item: None,
arguments: None
}),
Rc::new(AttributeMetaItem {
raw_item: "Deserialize",
base: "Deserialize",
assigned_item: None,
arguments: None
})
])
})
])
})
}
);
}
#[test]
fn attribute_unformatted() {
let attribute = Attribute::new("\t#[ derive ( Eq\t, PartialEq, ) ] ");
assert_eq!(
attribute,
Attribute {
is_inner: false,
content: Rc::new(AttributeMetaItem {
raw_item: "derive ( Eq\t, PartialEq, )",
base: "derive",
assigned_item: None,
arguments: Some(vec![
Rc::new(AttributeMetaItem {
raw_item: "Eq",
base: "Eq",
assigned_item: None,
arguments: None
}),
Rc::new(AttributeMetaItem {
raw_item: "PartialEq",
base: "PartialEq",
assigned_item: None,
arguments: None
})
])
})
}
);
assert_eq!(
attribute.raw_attribute(),
"#[derive ( Eq\t, PartialEq, )]"
);
}
#[test]
fn attribute_utf8() {
let attribute = Attribute::new("#[crate::gę42(bęc = \"🦀\", cśś = \"⭐\")]");
assert_eq!(
attribute,
Attribute {
is_inner: false,
content: Rc::new(AttributeMetaItem {
raw_item: "crate::gę42(bęc = \"🦀\", cśś = \"⭐\")",
base: "crate::gę42",
assigned_item: None,
arguments: Some(vec![
Rc::new(AttributeMetaItem {
raw_item: "bęc = \"🦀\"",
base: "bęc",
assigned_item: Some("\"🦀\""),
arguments: None
}),
Rc::new(AttributeMetaItem {
raw_item: "cśś = \"⭐\"",
base: "cśś",
assigned_item: Some("\"⭐\""),
arguments: None
})
])
})
}
)
}
#[test]
fn attribute_raw_identifier() {
let attribute = Attribute::new("#[r#derive(Debug)]");
assert_eq!(
attribute,
Attribute {
is_inner: false,
content: Rc::new(AttributeMetaItem {
raw_item: "r#derive(Debug)",
base: "r#derive",
assigned_item: None,
arguments: Some(vec![Rc::new(AttributeMetaItem {
raw_item: "Debug",
base: "Debug",
assigned_item: None,
arguments: None
})])
})
}
)
}
#[test]
fn attribute_meta_item_custom_brackets() {
for raw_attribute in ["macro{arg1,arg2}", "macro[arg1,arg2]"] {
let meta_item = AttributeMetaItem::new(raw_attribute);
assert_eq!(
meta_item,
AttributeMetaItem {
raw_item: raw_attribute,
base: "macro",
assigned_item: None,
arguments: Some(vec![
Rc::new(AttributeMetaItem {
raw_item: "arg1",
base: "arg1",
assigned_item: None,
arguments: None
}),
Rc::new(AttributeMetaItem {
raw_item: "arg2",
base: "arg2",
assigned_item: None,
arguments: None
})
])
}
);
}
}
#[test]
fn attribute_meta_item_unrecognized_form() {
let meta_item = AttributeMetaItem::new("foo|bar|");
assert_eq!(
meta_item,
AttributeMetaItem {
raw_item: "foo|bar|",
base: "foo|bar|",
assigned_item: None,
arguments: None
}
);
}
#[test]
fn attribute_meta_item_string_literals() {
let literals = [
" ",
"comma ,",
"comma , escaped quote \\\" right parenthesis ) ",
"right parenthesis ) comma , left parenthesis (",
"right square ) comma , left square (",
"right curly } comma , left curly {",
"Mężny bądź, chroń pułk twój i sześć flag.",
];
for literal in literals {
let raw_attribute = format!("foo(bar = \"{literal}\", baz = \"{literal}\")");
let meta_item = AttributeMetaItem::new(&raw_attribute);
assert_eq!(
meta_item,
AttributeMetaItem {
raw_item: &raw_attribute,
base: "foo",
assigned_item: None,
arguments: Some(vec![
Rc::new(AttributeMetaItem {
raw_item: format!("bar = \"{literal}\"").as_str(),
base: "bar",
assigned_item: Some(format!("\"{literal}\"").as_str()),
arguments: None
}),
Rc::new(AttributeMetaItem {
raw_item: format!("baz = \"{literal}\"").as_str(),
base: "baz",
assigned_item: Some(format!("\"{literal}\"").as_str()),
arguments: None
})
])
}
)
}
}
}