rustc_attr_parsing/attributes/
util.rs1use std::num::IntErrorKind;
2
3use rustc_ast::LitKind;
4use rustc_ast::attr::AttributeExt;
5use rustc_feature::is_builtin_attr_name;
6use rustc_hir::RustcVersion;
7use rustc_hir::limit::Limit;
8use rustc_span::Symbol;
9
10use crate::context::{AcceptContext, Stage};
11use crate::parser::{ArgParser, NameValueParser};
12use crate::session_diagnostics::LimitInvalid;
13
14pub fn parse_version(s: Symbol) -> Option<RustcVersion> {
18 let mut components = s.as_str().split('-');
19 let d = components.next()?;
20 if components.next().is_some() {
21 return None;
22 }
23 let mut digits = d.splitn(3, '.');
24 let major = digits.next()?.parse().ok()?;
25 let minor = digits.next()?.parse().ok()?;
26 let patch = digits.next().unwrap_or("0").parse().ok()?;
27 Some(RustcVersion { major, minor, patch })
28}
29
30pub fn is_builtin_attr(attr: &impl AttributeExt) -> bool {
31 attr.is_doc_comment().is_some()
32 || attr.ident().is_some_and(|ident| is_builtin_attr_name(ident.name))
33}
34
35pub(crate) fn parse_single_integer<S: Stage>(
42 cx: &mut AcceptContext<'_, '_, S>,
43 args: &ArgParser,
44) -> Option<u128> {
45 let Some(list) = args.list() else {
46 cx.expected_list(cx.attr_span);
47 return None;
48 };
49 let Some(single) = list.single() else {
50 cx.expected_single_argument(list.span);
51 return None;
52 };
53 let Some(lit) = single.lit() else {
54 cx.expected_integer_literal(single.span());
55 return None;
56 };
57 let LitKind::Int(num, _ty) = lit.kind else {
58 cx.expected_integer_literal(single.span());
59 return None;
60 };
61 Some(num.0)
62}
63
64impl<S: Stage> AcceptContext<'_, '_, S> {
65 pub(crate) fn parse_limit_int(&self, nv: &NameValueParser) -> Option<Limit> {
66 let Some(limit) = nv.value_as_str() else {
67 self.expected_string_literal(nv.value_span, Some(nv.value_as_lit()));
68 return None;
69 };
70
71 let error_str = match limit.as_str().parse() {
72 Ok(i) => return Some(Limit::new(i)),
73 Err(e) => match e.kind() {
74 IntErrorKind::PosOverflow => "`limit` is too large",
75 IntErrorKind::Empty => "`limit` must be a non-negative integer",
76 IntErrorKind::InvalidDigit => "not a valid integer",
77 IntErrorKind::NegOverflow => {
78 panic!(
79 "`limit` should never negatively overflow since we're parsing into a usize and we'd get Empty instead"
80 )
81 }
82 IntErrorKind::Zero => {
83 panic!("zero is a valid `limit` so should have returned Ok() when parsing")
84 }
85 kind => panic!("unimplemented IntErrorKind variant: {:?}", kind),
86 },
87 };
88
89 self.emit_err(LimitInvalid { span: self.attr_span, value_span: nv.value_span, error_str });
90
91 None
92 }
93}