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