Split out ast::ItemKind::Const into its own struct

This commit is contained in:
Oli Scherer 2023-03-29 09:20:45 +00:00
parent e3828777a6
commit ec74653652
14 changed files with 89 additions and 61 deletions

View file

@ -2897,6 +2897,13 @@ pub struct Static {
pub expr: Option<P<Expr>>,
}
#[derive(Clone, Encodable, Decodable, Debug)]
pub struct ConstItem {
pub defaultness: Defaultness,
pub ty: P<Ty>,
pub expr: Option<P<Expr>>,
}
#[derive(Clone, Encodable, Decodable, Debug)]
pub enum ItemKind {
/// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
@ -2914,7 +2921,7 @@ pub enum ItemKind {
/// A constant item (`const`).
///
/// E.g., `const FOO: i32 = 42;`.
Const(Defaultness, P<Ty>, Option<P<Expr>>),
Const(ConstItem),
/// A function declaration (`fn`).
///
/// E.g., `fn foo(bar: usize) -> usize { .. }`.
@ -3030,7 +3037,7 @@ pub fn generics(&self) -> Option<&Generics> {
pub enum AssocItemKind {
/// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
/// If `def` is parsed, then the constant is provided, and otherwise required.
Const(Defaultness, P<Ty>, Option<P<Expr>>),
Const(ConstItem),
/// An associated function.
Fn(Box<Fn>),
/// An associated type.
@ -3042,7 +3049,7 @@ pub enum AssocItemKind {
impl AssocItemKind {
pub fn defaultness(&self) -> Defaultness {
match *self {
Self::Const(defaultness, ..)
Self::Const(ConstItem { defaultness, .. })
| Self::Fn(box Fn { defaultness, .. })
| Self::Type(box TyAlias { defaultness, .. }) => defaultness,
Self::MacCall(..) => Defaultness::Final,
@ -3053,7 +3060,7 @@ pub fn defaultness(&self) -> Defaultness {
impl From<AssocItemKind> for ItemKind {
fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
match assoc_item_kind {
AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
AssocItemKind::Const(item) => ItemKind::Const(item),
AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
@ -3066,7 +3073,7 @@ impl TryFrom<ItemKind> for AssocItemKind {
fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
Ok(match item_kind {
ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
ItemKind::Const(item) => AssocItemKind::Const(item),
ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
ItemKind::MacCall(a) => AssocItemKind::MacCall(a),

View file

@ -1034,10 +1034,8 @@ pub fn noop_visit_item_kind<T: MutVisitor>(kind: &mut ItemKind, vis: &mut T) {
vis.visit_ty(ty);
visit_opt(expr, |expr| vis.visit_expr(expr));
}
ItemKind::Const(defaultness, ty, expr) => {
visit_defaultness(defaultness, vis);
vis.visit_ty(ty);
visit_opt(expr, |expr| vis.visit_expr(expr));
ItemKind::Const(item) => {
visit_const_item(item, vis);
}
ItemKind::Fn(box Fn { defaultness, generics, sig, body }) => {
visit_defaultness(defaultness, vis);
@ -1120,10 +1118,8 @@ pub fn noop_flat_map_assoc_item<T: MutVisitor>(
visitor.visit_vis(vis);
visit_attrs(attrs, visitor);
match kind {
AssocItemKind::Const(defaultness, ty, expr) => {
visit_defaultness(defaultness, visitor);
visitor.visit_ty(ty);
visit_opt(expr, |expr| visitor.visit_expr(expr));
AssocItemKind::Const(item) => {
visit_const_item(item, visitor);
}
AssocItemKind::Fn(box Fn { defaultness, generics, sig, body }) => {
visit_defaultness(defaultness, visitor);
@ -1153,6 +1149,15 @@ pub fn noop_flat_map_assoc_item<T: MutVisitor>(
smallvec![item]
}
fn visit_const_item<T: MutVisitor>(
ConstItem { defaultness, ty, expr }: &mut ConstItem,
visitor: &mut T,
) {
visit_defaultness(defaultness, visitor);
visitor.visit_ty(ty);
visit_opt(expr, |expr| visitor.visit_expr(expr));
}
pub fn noop_visit_fn_header<T: MutVisitor>(header: &mut FnHeader, vis: &mut T) {
let FnHeader { unsafety, asyncness, constness, ext: _ } = header;
visit_constness(constness, vis);

View file

@ -305,9 +305,9 @@ pub fn walk_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a Item) {
match &item.kind {
ItemKind::ExternCrate(_) => {}
ItemKind::Use(use_tree) => visitor.visit_use_tree(use_tree, item.id, false),
ItemKind::Static(Static { ty: typ, mutability: _, expr })
| ItemKind::Const(_, typ, expr) => {
visitor.visit_ty(typ);
ItemKind::Static(Static { ty, mutability: _, expr })
| ItemKind::Const(ConstItem { ty, expr, .. }) => {
visitor.visit_ty(ty);
walk_list!(visitor, visit_expr, expr);
}
ItemKind::Fn(box Fn { defaultness: _, generics, sig, body }) => {
@ -675,7 +675,7 @@ pub fn walk_assoc_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a AssocItem,
visitor.visit_ident(ident);
walk_list!(visitor, visit_attribute, attrs);
match kind {
AssocItemKind::Const(_, ty, expr) => {
AssocItemKind::Const(ConstItem { ty, expr, .. }) => {
visitor.visit_ty(ty);
walk_list!(visitor, visit_expr, expr);
}

View file

@ -233,8 +233,8 @@ fn lower_item_kind(
let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
hir::ItemKind::Static(ty, *m, body_id)
}
ItemKind::Const(_, t, e) => {
let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
ItemKind::Const(ast::ConstItem { ty, expr, .. }) => {
let (ty, body_id) = self.lower_const_item(ty, span, expr.as_deref());
hir::ItemKind::Const(ty, body_id)
}
ItemKind::Fn(box Fn {
@ -708,10 +708,10 @@ fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
let trait_item_def_id = hir_id.expect_owner();
let (generics, kind, has_default) = match &i.kind {
AssocItemKind::Const(_, ty, default) => {
AssocItemKind::Const(ConstItem { ty, expr, .. }) => {
let ty =
self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy));
let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
let body = expr.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
(hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
}
AssocItemKind::Fn(box Fn { sig, generics, body: None, .. }) => {
@ -809,7 +809,7 @@ fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
self.lower_attrs(hir_id, &i.attrs);
let (generics, kind) = match &i.kind {
AssocItemKind::Const(_, ty, expr) => {
AssocItemKind::Const(ConstItem { ty, expr, .. }) => {
let ty =
self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy));
(

View file

@ -983,8 +983,8 @@ fn visit_item(&mut self, item: &'a Item) {
self.err_handler().emit_err(errors::FieldlessUnion { span: item.span });
}
}
ItemKind::Const(def, .., None) => {
self.check_defaultness(item.span, *def);
ItemKind::Const(ConstItem { defaultness, expr: None, .. }) => {
self.check_defaultness(item.span, *defaultness);
self.session.emit_err(errors::ConstWithoutBody {
span: item.span,
replace_span: self.ending_semi_or_hi(item.span),
@ -1259,13 +1259,11 @@ fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
if ctxt == AssocCtxt::Impl {
match &item.kind {
AssocItemKind::Const(_, _, body) => {
if body.is_none() {
self.session.emit_err(errors::AssocConstWithoutBody {
span: item.span,
replace_span: self.ending_semi_or_hi(item.span),
});
}
AssocItemKind::Const(ConstItem { expr: None, .. }) => {
self.session.emit_err(errors::AssocConstWithoutBody {
span: item.span,
replace_span: self.ending_semi_or_hi(item.span),
});
}
AssocItemKind::Fn(box Fn { body, .. }) => {
if body.is_none() {

View file

@ -168,8 +168,15 @@ pub(crate) fn print_item(&mut self, item: &ast::Item) {
def,
);
}
ast::ItemKind::Const(def, ty, body) => {
self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, *def);
ast::ItemKind::Const(ast::ConstItem { defaultness, ty, expr }) => {
self.print_item_const(
item.ident,
None,
ty,
expr.as_deref(),
&item.vis,
*defaultness,
);
}
ast::ItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
self.print_fn_full(
@ -508,8 +515,8 @@ pub(crate) fn print_assoc_item(&mut self, item: &ast::AssocItem) {
ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
}
ast::AssocItemKind::Const(def, ty, body) => {
self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
ast::AssocItemKind::Const(ast::ConstItem { defaultness, ty, expr }) => {
self.print_item_const(ident, None, ty, expr.as_deref(), vis, *defaultness);
}
ast::AssocItemKind::Type(box ast::TyAlias {
defaultness,

View file

@ -264,11 +264,11 @@ pub fn expand_test_or_bench(
cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp),
],
// const $ident: test::TestDescAndFn =
ast::ItemKind::Const(
ast::Defaultness::Final,
cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))),
ast::ItemKind::Const(ast::ConstItem {
defaultness: ast::Defaultness::Final,
ty: cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))),
// test::TestDescAndFn {
Some(
expr: Some(
cx.expr_struct(
sp,
test_path("TestDescAndFn"),
@ -361,7 +361,7 @@ pub fn expand_test_or_bench(
],
), // }
),
),
}),
);
test_const = test_const.map(|mut tc| {
tc.vis.kind = ast::VisibilityKind::Public;

View file

@ -638,8 +638,13 @@ pub fn item_const(
ty: P<ast::Ty>,
expr: P<ast::Expr>,
) -> P<ast::Item> {
let def = ast::Defaultness::Final;
self.item(span, name, AttrVec::new(), ast::ItemKind::Const(def, ty, Some(expr)))
let defaultness = ast::Defaultness::Final;
self.item(
span,
name,
AttrVec::new(),
ast::ItemKind::Const(ast::ConstItem { defaultness, ty, expr: Some(expr) }),
)
}
// Builds `#[name]`.

View file

@ -805,7 +805,9 @@ fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
use ast::ItemKind::*;
if let Const(.., Some(expr)) | Static(ast::Static { expr: Some(expr), .. }) = &item.kind {
if let Const(ast::ConstItem { expr: Some(expr), .. })
| Static(ast::Static { expr: Some(expr), .. }) = &item.kind
{
self.check_unused_delims_expr(
cx,
expr,

View file

@ -237,7 +237,7 @@ fn parse_item_kind(
} else {
self.recover_const_mut(const_span);
let (ident, ty, expr) = self.parse_item_global(None)?;
(ident, ItemKind::Const(def_(), ty, expr))
(ident, ItemKind::Const(ConstItem { defaultness: def_(), ty, expr }))
}
} else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
// TRAIT ITEM
@ -863,9 +863,13 @@ fn parse_assoc_item(
let kind = match AssocItemKind::try_from(kind) {
Ok(kind) => kind,
Err(kind) => match kind {
ItemKind::Static(Static { ty: a, mutability: _, expr: b }) => {
ItemKind::Static(Static { ty, mutability: _, expr }) => {
self.sess.emit_err(errors::AssociatedStaticItemNotAllowed { span });
AssocItemKind::Const(Defaultness::Final, a, b)
AssocItemKind::Const(ConstItem {
defaultness: Defaultness::Final,
ty,
expr,
})
}
_ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
},
@ -1115,12 +1119,12 @@ pub fn parse_foreign_item(
let kind = match ForeignItemKind::try_from(kind) {
Ok(kind) => kind,
Err(kind) => match kind {
ItemKind::Const(_, a, b) => {
ItemKind::Const(ConstItem { ty, expr, .. }) => {
self.sess.emit_err(errors::ExternItemCannotBeConst {
ident_span: ident.span,
const_span: span.with_hi(ident.span.lo()),
});
ForeignItemKind::Static(a, Mutability::Not, b)
ForeignItemKind::Static(ty, Mutability::Not, expr)
}
_ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
},

View file

@ -2347,7 +2347,7 @@ fn resolve_item(&mut self, item: &'ast Item) {
}
ItemKind::Static(ast::Static { ref ty, ref expr, .. })
| ItemKind::Const(_, ref ty, ref expr) => {
| ItemKind::Const(ast::ConstItem { ref ty, ref expr, .. }) => {
self.with_static_rib(|this| {
this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
this.visit_ty(ty);
@ -2625,11 +2625,11 @@ fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
for item in trait_items {
self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
match &item.kind {
AssocItemKind::Const(_, ty, default) => {
AssocItemKind::Const(ast::ConstItem { ty, expr, .. }) => {
self.visit_ty(ty);
// Only impose the restrictions of `ConstRibKind` for an
// actual constant expression in a provided default.
if let Some(expr) = default {
if let Some(expr) = expr {
// We allow arbitrary const expressions inside of associated consts,
// even if they are potentially not const evaluatable.
//
@ -2800,7 +2800,7 @@ fn resolve_impl_item(
use crate::ResolutionError::*;
self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
match &item.kind {
AssocItemKind::Const(_, ty, default) => {
AssocItemKind::Const(ast::ConstItem { ty, expr, .. }) => {
debug!("resolve_implementation AssocItemKind::Const");
// If this is a trait impl, ensure the const
// exists in trait
@ -2815,7 +2815,7 @@ fn resolve_impl_item(
);
self.visit_ty(ty);
if let Some(expr) = default {
if let Some(expr) = expr {
// We allow arbitrary const expressions inside of associated consts,
// even if they are potentially not const evaluatable.
//

View file

@ -1,7 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source::snippet;
use rustc_ast::ast::{Item, ItemKind, Ty, TyKind, Static};
use rustc_ast::ast::{Item, ItemKind, Ty, TyKind, Static, ConstItem};
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_session::{declare_tool_lint, impl_lint_pass};
@ -100,7 +100,7 @@ fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
}
if !item.span.from_expansion() {
if let ItemKind::Const(_, ref var_type, _) = item.kind {
if let ItemKind::Const(ConstItem { ty: ref var_type, .. }) = item.kind {
Self::visit_type(var_type, cx, "constants have by default a `'static` lifetime");
// Don't check associated consts because `'static` cannot be elided on those (issue
// #2438)

View file

@ -287,7 +287,7 @@ pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
(ExternCrate(l), ExternCrate(r)) => l == r,
(Use(l), Use(r)) => eq_use_tree(l, r),
(Static(ast::Static{ ty: lt, mutability: lm, expr: le}), Static(ast::Static { ty: rt, mutability: rm, expr: re})) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
(Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
(Const(ast::ConstItem { defaultness: ld, ty: lt, expr: le}), Const(ast::ConstItem { defaultness: rd, ty: rt, expr: re} )) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
(
Fn(box ast::Fn {
defaultness: ld,
@ -451,7 +451,7 @@ pub fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool {
pub fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
use AssocItemKind::*;
match (l, r) {
(Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
(Const(ast::ConstItem { defaultness: ld, ty: lt, expr: le}), Const(ast::ConstItem { defaultness: rd, ty: rt, expr: re})) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
(
Fn(box ast::Fn {
defaultness: ld,

View file

@ -1808,7 +1808,7 @@ pub(crate) fn from_item(item: &'a ast::Item) -> Self {
ast::ItemKind::Static(ast::Static { ref ty, mutability, ref expr}) => {
(None, "static", ty, mutability, expr)
}
ast::ItemKind::Const(defaultness, ref ty, ref expr) => {
ast::ItemKind::Const(ast::ConstItem { defaultness, ref ty, ref expr}) => {
(Some(defaultness), "const", ty, ast::Mutability::Not, expr)
}
_ => unreachable!(),
@ -1827,8 +1827,8 @@ pub(crate) fn from_item(item: &'a ast::Item) -> Self {
pub(crate) fn from_trait_item(ti: &'a ast::AssocItem) -> Self {
let (defaultness, ty, expr_opt) = match ti.kind {
ast::AssocItemKind::Const(defaultness, ref ty, ref expr_opt) => {
(defaultness, ty, expr_opt)
ast::AssocItemKind::Const(ast::ConstItem {defaultness, ref ty, ref expr}) => {
(defaultness, ty, expr)
}
_ => unreachable!(),
};
@ -1846,7 +1846,7 @@ pub(crate) fn from_trait_item(ti: &'a ast::AssocItem) -> Self {
pub(crate) fn from_impl_item(ii: &'a ast::AssocItem) -> Self {
let (defaultness, ty, expr) = match ii.kind {
ast::AssocItemKind::Const(defaultness, ref ty, ref expr) => (defaultness, ty, expr),
ast::AssocItemKind::Const(ast::ConstItem { defaultness, ref ty, ref expr}) => (defaultness, ty, expr),
_ => unreachable!(),
};
StaticParts {