-
-
Notifications
You must be signed in to change notification settings - Fork 14.2k
MGCA: Support struct expressions without intermediary anon consts #149114
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
base: main
Are you sure you want to change the base?
Conversation
|
|
0dbf003 to
a019ac7
Compare
This comment has been minimized.
This comment has been minimized.
a019ac7 to
b557322
Compare
This comment has been minimized.
This comment has been minimized.
b557322 to
734737a
Compare
|
@bors try @rust-timer queue |
This comment has been minimized.
This comment has been minimized.
MGCA: Support struct expressions without intermediary anon consts
This comment has been minimized.
This comment has been minimized.
| let (variant_idx, branches) = if def.is_enum() { | ||
| let (head, rest) = branches.split_first().unwrap(); | ||
| (VariantIdx::from_u32(head.unwrap_leaf().to_u32()), rest) | ||
| (VariantIdx::from_u32(head.to_value().valtree.unwrap_leaf().to_u32()), rest) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the addition of all the .to_value().valtree everywhere is kind of unfortunate
| // We need a branch for each "level" of the data structure. | ||
| let bytes = ty::ValTree::from_raw_bytes(tcx, byte_sym.as_byte_str()); | ||
| ty::ValTree::from_branches(tcx, [bytes]) | ||
| ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, bytes, *inner_ty)]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
same with all the extra calls to ty::Const::new_x
This comment has been minimized.
This comment has been minimized.
734737a to
6496c15
Compare
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
Finished benchmarking commit (eeb4682): comparison URL. Overall result: ❌✅ regressions and improvements - please read the text belowBenchmarking this pull request means it may be perf-sensitive – we'll automatically label it not fit for rolling up. You can override this, but we strongly advise not to, due to possible changes in compiler perf. Next Steps: If you can justify the regressions found in this try perf run, please do so in sufficient writing along with @bors rollup=never Instruction countOur most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.
Max RSS (memory usage)Results (primary 1.2%, secondary 1.0%)A less reliable metric. May be of interest, but not used to determine the overall result above.
CyclesResults (secondary -0.1%)A less reliable metric. May be of interest, but not used to determine the overall result above.
Binary sizeResults (secondary 0.0%)A less reliable metric. May be of interest, but not used to determine the overall result above.
Bootstrap: 474.035s -> 472.627s (-0.30%) |
6496c15 to
1a44434
Compare
|
@bors try @rust-timer queue |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
|
||
| if let DefKind::AnonConst = tcx.def_kind(def_id) | ||
| && let ty::AnonConstKind::MCG = tcx.anon_const_kind(def_id) | ||
| && let Err(e) = tcx.hir_const_arg_anon_check_invalid_param_uses(def_id) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
check_const_arg_invalid_param_uses?
| && let Err(e) = tcx.hir_const_arg_anon_check_invalid_param_uses(anon.def_id) | ||
| { | ||
| return ty::Const::new_error(tcx, e); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is this necessary?
| && let ty::AnonConstKind::MCG = tcx.anon_const_kind(def_id) | ||
| && let Err(e) = tcx.hir_const_arg_anon_check_invalid_param_uses(def_id) | ||
| { | ||
| e.raise_fatal(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
kinda meh:
three options
wrap with Result<TypeckResults, ErrorGuaranteed>
- meh, not used by other code
make a dummy TypeckResults
- fragile, we don't have good test coverage for how e.g. lints access the typeck results, likely to cause a bunch of rare ICE
change HirTyLowering to disable lowering anything to ty::Param/ConstKind
- similar to "forbid lower to infer"
- seems best, add fixme for this pls :3
| None | ||
| } | ||
|
|
||
| pub fn hir_const_arg_anon_check_invalid_param_uses( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pretty iffy, idk, add fixme that we should remove it medium-term
| expr.id, | ||
| &se.qself, | ||
| &se.path, | ||
| ParamMode::Explicit, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add FIXME that we should use Optional here and make sure the ItemCtxt still errors if u do it in a signature
|
|
||
| let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| { | ||
| let hir_id = self.lower_node_id(f.id); | ||
| self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add fixme to look into this, I expect this to be broken as it causes us to silently allow attrs
| self.lower_anon_const_to_const_arg_direct(anon_const) | ||
| } else { | ||
| self.lower_expr_to_const_arg_direct(&f.expr) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this naming sucks :3 we should rename the lower_ty and lower_ty_direct to lower_ty_and_intern and lower_ty.
Same with const stuff.
| ) -> V::Result { | ||
| let ConstArg { hir_id, kind } = const_arg; | ||
| try_visit!(visitor.visit_id(*hir_id)); | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why whitespace
| Node::Block(_) | ||
| | Node::Arm(_) | ||
| | Node::ExprField(_) | ||
| | Node::ConstArgExprField(_) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
try to move into an unreachable branch and then we get a test if it ICEs after merge
| // `MgcaDisambiguation::Direct` is set even when MGCA is disabled, so | ||
| // to avoid affecting stable we have to feature gate the not creating | ||
| // anon consts | ||
| if let MgcaDisambiguation::Direct = constant.mgca_disambiguation |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
make this a match now that mgca impacts both branches
| handle_const_block(self, constant, DefKind::InlineConst); | ||
| return; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
return handle_const_block(self, constant, DefKind::InlineConst);
|
|
||
| match rest { | ||
| StructRest::Base(expr) => self.visit_expr(expr), | ||
| _ => (), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
??? why no exhaustive
| _ => self.invocation_parent.parent_def, | ||
| }; | ||
|
|
||
| self.with_parent(parent_def, |this| visit::walk_expr(this, expr)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you rewrite this to only use with_parent if we actually create a new def_id and just walk_expr in the other branches?
|
|
||
| for init_expr in fields { | ||
| if let ExprKind::ConstBlock(ref constant) = init_expr.expr.kind { | ||
| handle_const_block(self, constant, DefKind::AnonConst); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
please add a comment that we only do this to give const blocks a different DefKind, the rest is just a walk
| /// the fields of the variant. | ||
| /// | ||
| /// ZST types are represented as an empty slice. | ||
| Branch(Box<[I::Const]>), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pls add FIXME to use a List
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
also add FIXME to struct that we shouldn't intern valtree anymore, we already intern Const and valtree is now always directly inside of Const
| } | ||
|
|
||
| pub trait ValTree<I: Interner<ValTree = Self>>: Copy + Debug + Hash + Eq { | ||
| // This isnt' `IntoKind` because then we can't return a reference |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add a FIXME that we don't need this once we properly intern instead of using Box<[_]>
|
|
||
| fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self { | ||
| let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self; | ||
| folder.cx().intern_valtree(inner.clone().fold_with(folder)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
before reintern, check for eq
| folder: &mut F, | ||
| ) -> Result<Self, F::Error> { | ||
| let inner: &ty::ValTreeKind<TyCtxt<'tcx>> = &*self; | ||
| let valtree = folder.cx().intern_valtree(inner.clone().try_fold_with(folder)?); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
also check for eq here
| self.valtree | ||
| .unwrap_branch() | ||
| .into_iter() | ||
| .map(|ct| ct.to_value().valtree.unwrap_leaf().to_u8()), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pls add a method to ty::Const to get the leaf and use that
| impl<'tcx> ty::ValTreeKind<TyCtxt<'tcx>> { | ||
| #[inline] | ||
| pub fn unwrap_leaf(&self) -> ScalarInt { | ||
| fn unwrap_leaf(&self) -> ScalarInt { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pls move as many as possible to rustc_type_ir instead of adding an extension trait
| } | ||
| } | ||
|
|
||
| fn lower_struct_expr_const_arg( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fn lower_const_arg_struct or lower_const_arg_expr_struct idk, sth that's consistent and not ass :>
| ) -> Const<'tcx> { | ||
| let tcx = self.tcx(); | ||
|
|
||
| let non_adt_or_variant_res = || { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add FIXME that most of this function should be reused with normal struct expr hir lowering
| .fields | ||
| .iter() | ||
| .map(|field_def| { | ||
| // FIXME(mgca): we aren't really handling privacy or stability at all but we should |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
and macro visibility
| #![expect(incomplete_features)] | ||
| #![crate_type = "lib"] | ||
|
|
||
| #[derive(Eq, PartialEq, std::marker::ConstParamTy)] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
comment
| @@ -0,0 +1,17 @@ | |||
| //@ check-pass | |||
| // This should error | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
change to FIXME
This comment has been minimized.
This comment has been minimized.
|
Finished benchmarking commit (b925bed): comparison URL. Overall result: ❌✅ regressions and improvements - please read the text belowBenchmarking this pull request means it may be perf-sensitive – we'll automatically label it not fit for rolling up. You can override this, but we strongly advise not to, due to possible changes in compiler perf. Next Steps: If you can justify the regressions found in this try perf run, please do so in sufficient writing along with @bors rollup=never Instruction countOur most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.
Max RSS (memory usage)Results (primary -1.5%, secondary 2.3%)A less reliable metric. May be of interest, but not used to determine the overall result above.
CyclesResults (secondary -0.0%)A less reliable metric. May be of interest, but not used to determine the overall result above.
Binary sizeThis benchmark run did not return any relevant results for this metric. Bootstrap: 478.546s -> 479.261s (0.15%) |
r? oli-obk
tracking issue: #132980
based on: #150025
High level goal
Under
feature(min_generic_const_args)this PR adds another kind of const argument. A struct/variant construction const arg kind. We represent the values of the fields as themselves being const arguments which allows for uses of generic parameters subject to the existing restrictions present inmin_generic_const_args:This PR does not support uses of const ctors, e.g.
None. And also does not support tuple constructors, e.g.Some(N). I believe that it would not be difficult to add support for such functionality after this PR lands so have left it out deliberately.We currently require that all generic parameters on the type being constructed be explicitly specified. I haven't really looked into why that is but it doesn't seem desirable to me as it should be legal to write
Some { ... }in a const argument inside of a body and have that desugar toSome::<_> { ... }. Regardless this can definitely be a follow-up PR and I assume this is some underlying consistency with the way that elided args are handled with type paths elsewhere.This PRs implementation of supporting struct expressions is somewhat incomplete. We don't handle
Foo { ..expr }at all and aren't handling privacy/stability. The printing ofConstArgKind::StructHIR nodes doesn't really exist either :')I've tried to keep the implementation here somewhat deliberately incomplete as I think a number of these issues are actually quite small and self contained after this PR lands and I'm hoping it could be a good set of issues to mentor newer contributors on 🤔 I just wanted the "bare minimum" required to actually demonstrate that the previous changes are "necessary".
ValTreenow recurse throughty::ConstIn order to actually represent struct/variant construction in
ty::Constwithout going through an anon const we would need to introduce some newConstKindvariant. Let's say some hypotheticalConstKind::ADT(Ty<'tcx>, List<Const<'tcx>>).This variant would represent things the same way that
ValTreedoes with the first element representing theVariantIdxof the enum (if its an enum), and then followed by a list of field values in definition order.This could work but there are a few reasons why it's suboptimal.
First it would mean we have a second kind of
Constthat can be normalized. Right now we only haveConstKind::Unevaluatedwhich possibly needs normalization. Similarly withTyKindwe only haveTyKind::Alias. If we introducedConstKind::ADTit would need to be normalized to aConstKind::Valueeventually. This feels to me like it has the potential to cause bugs in the long run where onlyConstKind::Unevaluatedis handled by some code paths.Secondly it would make type equality/inference be kind of... weird... It's desirable for
Some { 0: ?x } eq Some { 0: 1_u32 }to result in?x=1_u32. I can't see a way for this to work with thisConstKind::ADTdesign under the current architecture for how we represent types/consts and generally do equality operations.We would need to wholly special case these two variants in type equality and have a custom recursive walker separate from the existing architecture for doing type equality. It would also be somewhat unique in that it's a non-rigid
ty::Const(it can be normalized more later on in type inference) while also having somewhat "structural" equality behaviour.Lastly, it's worth noting that its not actually
ConstKind::ADTthat we want. It's desirable to extend this setup to also support tuples and arrays, or even references if we wind up supporting those in const generics. Therefore this isn't reallyConstKind::ADTbut a more generalConstKind::ShallowValueor something to that effect. It represents at least one "layer" of a types value :')Instead of doing this implementation choice we instead change
ValTree::Branch:The representation for so called "shallow values" is now the same as the representation for the entire full value. The desired inference/type equality behaviour just falls right out of this. We also don't wind up with these shallow values actually being non-rigid. And
ValTreealready supports references/tuples/arrays so we can handle those just fine.I think in the future it might be worth considering inlining
ValTreeintoty::ConstKind. E.g:This would imply that the usage of
ValTrees in patterns would now be usingty::Constbut they already kind of are anyway and I think that's probably okay in the long run. It also would mean that the set of things we could represent in const patterns is greater which may be desirable in the long run for supporting things such as const patterns of const generic parameters.Regardless, this PR doesn't actually inline
ValTreeintoty::ConstKind, it only changesBranchto recurse throughConst. This change could be split out of this PR if desired.I'm not sure if there'll be a perf impact from this change. It's somewhat plausible as now all const pattern values that have nesting will be interning a lot more
Tys. We shall see :>Forbidding generic parameters under mgca
Under mgca we now allow all const arguments to resolve paths to generic parameters. We then later actually validate that the const arg should be allowed to access generic parameters if it did wind up resolving to any.
This winds up just being a lot simpler to implement than trying to make name resolution "keep track" of whether we're inside of a non-anon-const const arg and then encounter a
const { ... }indicating we should now stop allowing resolving to generic parameters.It's also somewhat in line with what we'll need for a
feature(generic_const_args)where we'll want to decide whether an anon const should have any generic parameters based off syntactically whether any generic parameters were used. Though that design is entirely hypothetical at this point :)