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() || attr.name().is_some_and(|name| is_builtin_attr_name(name))
32}
33
34pub(crate) fn parse_single_integer<S: Stage>(
41 cx: &mut AcceptContext<'_, '_, S>,
42 args: &ArgParser,
43) -> Option<u128> {
44 let Some(list) = args.list() else {
45 cx.expected_list(cx.attr_span, args);
46 return None;
47 };
48 let Some(single) = list.single() else {
49 cx.expected_single_argument(list.span);
50 return None;
51 };
52 let Some(lit) = single.lit() else {
53 cx.expected_integer_literal(single.span());
54 return None;
55 };
56 let LitKind::Int(num, _ty) = lit.kind else {
57 cx.expected_integer_literal(single.span());
58 return None;
59 };
60 Some(num.0)
61}
62
63impl<S: Stage> AcceptContext<'_, '_, S> {
64 pub(crate) fn parse_limit_int(&self, nv: &NameValueParser) -> Option<Limit> {
65 let Some(limit) = nv.value_as_str() else {
66 self.expected_string_literal(nv.value_span, Some(nv.value_as_lit()));
67 return None;
68 };
69
70 let error_str = match limit.as_str().parse() {
71 Ok(i) => return Some(Limit::new(i)),
72 Err(e) => match e.kind() {
73 IntErrorKind::PosOverflow => "`limit` is too large",
74 IntErrorKind::Empty => "`limit` must be a non-negative integer",
75 IntErrorKind::InvalidDigit => "not a valid integer",
76 IntErrorKind::NegOverflow => {
77 panic!(
78 "`limit` should never negatively overflow since we're parsing into a usize and we'd get Empty instead"
79 )
80 }
81 IntErrorKind::Zero => {
82 panic!("zero is a valid `limit` so should have returned Ok() when parsing")
83 }
84 kind => panic!("unimplemented IntErrorKind variant: {:?}", kind),
85 },
86 };
87
88 self.emit_err(LimitInvalid { span: self.attr_span, value_span: nv.value_span, error_str });
89
90 None
91 }
92}