]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/config_proc_macro/src/attrs.rs
Port pgo.sh to Python
[rust.git] / src / tools / rustfmt / config_proc_macro / src / attrs.rs
1 //! This module provides utilities for handling attributes on variants
2 //! of `config_type` enum. Currently there are two types of attributes
3 //! that could appear on the variants of `config_type` enum: `doc_hint`
4 //! and `value`. Both comes in the form of name-value pair whose value
5 //! is string literal.
6
7 /// Returns the value of the first `doc_hint` attribute in the given slice or
8 /// `None` if `doc_hint` attribute is not available.
9 pub fn find_doc_hint(attrs: &[syn::Attribute]) -> Option<String> {
10     attrs.iter().filter_map(doc_hint).next()
11 }
12
13 /// Returns `true` if the given attribute is a `doc_hint` attribute.
14 pub fn is_doc_hint(attr: &syn::Attribute) -> bool {
15     is_attr_name_value(attr, "doc_hint")
16 }
17
18 /// Returns a string literal value if the given attribute is `doc_hint`
19 /// attribute or `None` otherwise.
20 pub fn doc_hint(attr: &syn::Attribute) -> Option<String> {
21     get_name_value_str_lit(attr, "doc_hint")
22 }
23
24 /// Returns the value of the first `value` attribute in the given slice or
25 /// `None` if `value` attribute is not available.
26 pub fn find_config_value(attrs: &[syn::Attribute]) -> Option<String> {
27     attrs.iter().filter_map(config_value).next()
28 }
29
30 /// Returns a string literal value if the given attribute is `value`
31 /// attribute or `None` otherwise.
32 pub fn config_value(attr: &syn::Attribute) -> Option<String> {
33     get_name_value_str_lit(attr, "value")
34 }
35
36 /// Returns `true` if the given attribute is a `value` attribute.
37 pub fn is_config_value(attr: &syn::Attribute) -> bool {
38     is_attr_name_value(attr, "value")
39 }
40
41 fn is_attr_name_value(attr: &syn::Attribute, name: &str) -> bool {
42     attr.parse_meta().ok().map_or(false, |meta| match meta {
43         syn::Meta::NameValue(syn::MetaNameValue { ref path, .. }) if path.is_ident(name) => true,
44         _ => false,
45     })
46 }
47
48 fn get_name_value_str_lit(attr: &syn::Attribute, name: &str) -> Option<String> {
49     attr.parse_meta().ok().and_then(|meta| match meta {
50         syn::Meta::NameValue(syn::MetaNameValue {
51             ref path,
52             lit: syn::Lit::Str(ref lit_str),
53             ..
54         }) if path.is_ident(name) => Some(lit_str.value()),
55         _ => None,
56     })
57 }