Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lower all trivial const paths as ConstArgKind::Path #135186

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 0 additions & 25 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,6 @@ impl Path {
pub fn is_global(&self) -> bool {
!self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
}

/// If this path is a single identifier with no arguments, does not ensure
/// that the path resolves to a const param, the caller should check this.
pub fn is_potential_trivial_const_arg(&self) -> bool {
self.segments.len() == 1 && self.segments[0].args.is_none()
}
}

/// A segment of a path: an identifier, an optional lifetime, and a set of types.
Expand Down Expand Up @@ -1175,25 +1169,6 @@ pub struct Expr {
}

impl Expr {
/// Could this expr be either `N`, or `{ N }`, where `N` is a const parameter.
///
/// If this is not the case, name resolution does not resolve `N` when using
/// `min_const_generics` as more complex expressions are not supported.
///
/// Does not ensure that the path resolves to a const param, the caller should check this.
/// This also does not consider macros, so it's only correct after macro-expansion.
pub fn is_potential_trivial_const_arg(&self) -> bool {
let this = self.maybe_unwrap_block();

if let ExprKind::Path(None, path) = &this.kind
&& path.is_potential_trivial_const_arg()
{
true
} else {
false
}
}

/// Returns an expression with (when possible) *one* outter brace removed
pub fn maybe_unwrap_block(&self) -> &Expr {
if let ExprKind::Block(block, None) = &self.kind
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_ast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub mod util {
pub mod case;
pub mod classify;
pub mod comments;
mod const_args;
pub mod literal;
pub mod parser;
pub mod unicode;
Expand Down
71 changes: 71 additions & 0 deletions compiler/rustc_ast/src/util/const_args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use std::ops::ControlFlow;

use crate::ptr::P;
use crate::visit::{Visitor, walk_anon_const};
use crate::{DUMMY_NODE_ID, Expr, ExprKind, Path, QSelf};

impl Expr {
// FIXME: update docs
/// Could this expr be either `N`, or `{ N }`, where `N` is a const parameter.
///
/// If this is not the case, name resolution does not resolve `N` when using
/// `min_const_generics` as more complex expressions are not supported.
///
/// Does not ensure that the path resolves to a const param, the caller should check this.
/// This also does not consider macros, so it's only correct after macro-expansion.
pub fn is_potential_trivial_const_arg(&self, allow_mgca_arg: bool) -> bool {
let this = self.maybe_unwrap_block();
if allow_mgca_arg {
MGCATrivialConstArgVisitor::new().visit_expr(this).is_continue()
} else {
if let ExprKind::Path(None, path) = &this.kind
&& path.is_potential_trivial_const_arg(&None, allow_mgca_arg)
{
true
} else {
false
}
}
}
}

impl Path {
// FIXME: add docs
#[tracing::instrument(level = "debug", ret)]
pub fn is_potential_trivial_const_arg(
&self,
qself: &Option<P<QSelf>>,
allow_mgca_arg: bool,
) -> bool {
if allow_mgca_arg {
let mut visitor = MGCATrivialConstArgVisitor::new();
visitor.visit_qself(qself).is_continue()
&& visitor.visit_path(self, DUMMY_NODE_ID).is_continue()
} else {
qself.is_none()
&& self.segments.len() == 1
&& self.segments.iter().all(|seg| seg.args.is_none())
}
}
}

pub(crate) struct MGCATrivialConstArgVisitor {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a visitor is not really necessary for MGCA 🤔 The only real requirement is the at-most-one-layer-of-braces thing so really this is just a check for if the expr is a ExprKind::Path or a braced ExprKind::Path.

for Path::is_potential_trivial_const_arg i think we should just always be returning true if allow_mgca_arg is set since we should support every path 🤔 (atleast at the ast/hir level). for Expr::is_potential_trivial_const_arg when allow_mgca_arg is set its just a check for ExprKind::Path


impl MGCATrivialConstArgVisitor {
pub(crate) fn new() -> Self {
Self {}
}
}

impl<'ast> Visitor<'ast> for MGCATrivialConstArgVisitor {
type Result = ControlFlow<()>;

fn visit_anon_const(&mut self, c: &'ast crate::AnonConst) -> Self::Result {
let expr = c.value.maybe_unwrap_block();
match &expr.kind {
ExprKind::Path(_, _) => {}
_ => return ControlFlow::Break(()),
}
walk_anon_const(self, c)
}
}
18 changes: 9 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1101,7 +1101,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
.and_then(|partial_res| partial_res.full_res())
{
if !res.matches_ns(Namespace::TypeNS)
&& path.is_potential_trivial_const_arg()
// FIXME: should this only allow single-segment paths?
BoxyUwU marked this conversation as resolved.
Show resolved Hide resolved
&& path.is_potential_trivial_const_arg(&None, self.tcx.features().min_generic_const_args())
{
debug!(
"lower_generic_arg: Lowering type argument as const argument: {:?}",
Expand Down Expand Up @@ -2061,8 +2062,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
) -> &'hir hir::ConstArg<'hir> {
let tcx = self.tcx;

// FIXME(min_generic_const_args): we only allow one-segment const paths for now
let ct_kind = if path.is_potential_trivial_const_arg()
let ct_kind = if path
.is_potential_trivial_const_arg(&None, tcx.features().min_generic_const_args())
&& (tcx.features().min_generic_const_args()
|| matches!(res, Res::Def(DefKind::ConstParam, _)))
{
Expand All @@ -2072,7 +2073,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
path,
ParamMode::Optional,
AllowReturnTypeNotation::No,
// FIXME(min_generic_const_args): update for `fn foo() -> Bar<FOO<impl Trait>>` support
// FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
ImplTraitContext::Disallowed(ImplTraitPosition::Path),
None,
);
Expand Down Expand Up @@ -2136,19 +2137,18 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
};
let maybe_res =
self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
// FIXME(min_generic_const_args): we only allow one-segment const paths for now
if let ExprKind::Path(None, path) = &expr.kind
&& path.is_potential_trivial_const_arg()
if let ExprKind::Path(qself, path) = &expr.kind
&& path.is_potential_trivial_const_arg(qself, tcx.features().min_generic_const_args())
&& (tcx.features().min_generic_const_args()
|| matches!(maybe_res, Some(Res::Def(DefKind::ConstParam, _))))
{
let qpath = self.lower_qpath(
expr.id,
&None,
qself,
path,
ParamMode::Optional,
AllowReturnTypeNotation::No,
// FIXME(min_generic_const_args): update for `fn foo() -> Bar<FOO<impl Trait>>` support
// FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
ImplTraitContext::Disallowed(ImplTraitPosition::Path),
None,
);
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_builtin_macros/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ fn make_format_args(
&& let [stmt] = block.stmts.as_slice()
&& let StmtKind::Expr(expr) = &stmt.kind
&& let ExprKind::Path(None, path) = &expr.kind
&& path.is_potential_trivial_const_arg()
&& path.segments.len() == 1
&& path.segments[0].args.is_none()
{
err.multipart_suggestion(
"quote your inlined format argument to use as string literal",
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,13 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
EncodeCrossCrate::Yes, experimental!(patchable_function_entry)
),

// Probably temporary component of min_generic_const_args.
// `#[type_const] const ASSOC: usize;`
gated!(
type_const, Normal, template!(Word), ErrorFollowing,
EncodeCrossCrate::Yes, min_generic_const_args, experimental!(type_const),
),

// ==========================================================================
// Internal attributes: Stability, deprecation, and unsafe:
// ==========================================================================
Expand Down
63 changes: 52 additions & 11 deletions compiler/rustc_hir_analysis/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ use tracing::{debug, instrument};

use crate::check::intrinsic::intrinsic_operation_unsafety;
use crate::errors;
use crate::hir_ty_lowering::errors::assoc_kind_str;
use crate::hir_ty_lowering::{FeedConstTy, HirTyLowerer, RegionInferReason};

pub(crate) mod dump;
Expand Down Expand Up @@ -468,14 +469,56 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> {
item_segment: &hir::PathSegment<'tcx>,
poly_trait_ref: ty::PolyTraitRef<'tcx>,
) -> Ty<'tcx> {
match self.lower_assoc_shared(
span,
item_def_id,
item_segment,
poly_trait_ref,
ty::AssocKind::Type,
) {
Ok((def_id, args)) => Ty::new_projection_from_args(self.tcx(), def_id, args),
Err(witness) => Ty::new_error(self.tcx(), witness),
}
}

fn lower_assoc_const(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this would probably also be good to unify with lower_assoc_ty somehow, at the very least it would be good to not duplicate almost 100 lines of diagnostics logic :3

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. These two could now be on the dyn HirTyLowerer impl instead, with just the new lower_assoc_shared left as a trait method. I didn't do that though in case future impl-specific behavior was needed. Thoughts?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a comment as a proper review comment, I think we can just delete both. If we ever need this/that level of flexibility it can be re-added but for now it seems unnecessary

&self,
span: Span,
item_def_id: DefId,
item_segment: &hir::PathSegment<'tcx>,
poly_trait_ref: ty::PolyTraitRef<'tcx>,
) -> Const<'tcx> {
match self.lower_assoc_shared(
span,
item_def_id,
item_segment,
poly_trait_ref,
ty::AssocKind::Const,
) {
Ok((def_id, args)) => {
let uv = ty::UnevaluatedConst::new(def_id, args);
Const::new_unevaluated(self.tcx(), uv)
}
Err(witness) => Const::new_error(self.tcx(), witness),
}
}

fn lower_assoc_shared(
&self,
span: Span,
item_def_id: DefId,
item_segment: &rustc_hir::PathSegment<'tcx>,
poly_trait_ref: ty::PolyTraitRef<'tcx>,
kind: ty::AssocKind,
) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> {
if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
let item_args = self.lowerer().lower_generic_args_of_assoc_item(
span,
item_def_id,
item_segment,
trait_ref.args,
);
Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
Ok((item_def_id, item_args))
} else {
// There are no late-bound regions; we can just ignore the binder.
let (mut mpart_sugg, mut inferred_sugg) = (None, None);
Expand Down Expand Up @@ -536,16 +579,14 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> {
}
_ => {}
}
Ty::new_error(
self.tcx(),
self.tcx().dcx().emit_err(errors::AssociatedItemTraitUninferredGenericParams {
span,
inferred_sugg,
bound,
mpart_sugg,
what: "type",
}),
)

Err(self.tcx().dcx().emit_err(errors::AssociatedItemTraitUninferredGenericParams {
span,
inferred_sugg,
bound,
mpart_sugg,
what: assoc_kind_str(kind),
}))
}
}

Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,11 +471,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {

// Good error for `where Trait::method(..): Send`.
let Some(self_ty) = opt_self_ty else {
return self.error_missing_qpath_self_ty(
let guar = self.error_missing_qpath_self_ty(
trait_def_id,
hir_ty.span,
item_segment,
ty::AssocKind::Type,
);
return Ty::new_error(tcx, guar);
};
let self_ty = self.lower_ty(self_ty);

Expand Down
Loading
Loading