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

More powerful const panic #90488

Closed
wants to merge 8 commits into from
Closed

Conversation

nbdd0121
Copy link
Contributor

@nbdd0121 nbdd0121 commented Nov 1, 2021

Add a const_panic_extra feature gate that enables const panic to panic with any format arguments.

It should make the example given in the rust-lang/rfcs#2345 possible:

const fn parse_bool(s: &str) -> bool {
    match s {
        "true" => true,
        "false" => false,
        other => panic!("`{}` is not a valid bool", other),
    }
}
parse_bool("true");
parse_bool("false");
parse_bool("foo");

The mechanism implemented in this PR essentially extracts arguments from const-eval Arguments and delegate the formatting to formatting machinary that's compiled with rustc. Currently only these types are formatted:

  • Non-reference primitives
  • Reference to types under the blanket impl (e.g. impl<T: Display> for &Display)
  • String (the only const String is empty string)
  • Arguments
  • dyn Trait if Trait is one of the formatting traits.

Other types will be formatted to <failed to format {ty}>.

I think it's possible to require that only types that can be correctly formatted are accepted by having an additional marker type, but that'll require const trait impl and specialization like this:

trait ConstDebug: Debug {}
impl<T: Debug> ConstDebug for T {}
impl const ConstDebug for &str {}

IMO it's okay to accept types that couldn't be formatted, given that const panic messages are considered diagnostics. It'll also make constification of assert_eq! easier (which uses &dyn Debug internally) since we current have no way to represent &dyn ~const ConstDebug.

I implement the feature in this way:

  • This is reasonable simple;
  • We won't see the whole formatting machinary be accepted by const-eval in near feature (previously suggested idea like using unleash miri doesn't work because the machinary's MIR isn't all available);
  • People are removing info from panic messages to make it const, which is not desirable;
  • There is a real need to make things like Result::unwrap const;

I plan to file/work on a few follow up PRs if this one is accepted:

  • Constification of Result::unwrap
  • Const panic fmt of additional types from std
  • Const panic fmt of ADTs if the Debug implementation is derived

This is a bulky PR, but I've separated it to individually meaningful commits so I'd suggest to review by commits. Some changes are made to ArgumentV1::new to allow the const_panic_extra being used without const_fn_fn_ptr_basics and const_mut_refs. Given this is hot code I'd suggest a perf run.

r? @oli-obk
@rustbot label: T-compiler A-const-eval

@rustbot rustbot added A-const-eval Area: constant evaluation (mir interpretation) T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Nov 1, 2021
@rust-highfive
Copy link
Collaborator

Some changes occured to the CTFE / Miri engine

cc @rust-lang/miri

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Nov 1, 2021
@camelid
Copy link
Member

camelid commented Nov 1, 2021

@bors try @rust-timer queue

@rust-timer
Copy link
Collaborator

Awaiting bors try build completion.

@rustbot label: +S-waiting-on-perf

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Nov 1, 2021
@bors
Copy link
Contributor

bors commented Nov 1, 2021

⌛ Trying commit c3ea64c with merge 513ad0280218aa8bfcb61c04b8d0384fceb042ea...

@rust-log-analyzer

This comment has been minimized.

@camelid
Copy link
Member

camelid commented Nov 1, 2021

(FYI, you may want to wait to fix tests until after the bors try run finishes; IIRC, sometimes pushing will cancel a try.)

@bors
Copy link
Contributor

bors commented Nov 2, 2021

☀️ Try build successful - checks-actions
Build commit: 513ad0280218aa8bfcb61c04b8d0384fceb042ea (513ad0280218aa8bfcb61c04b8d0384fceb042ea)

@rust-timer
Copy link
Collaborator

Queued 513ad0280218aa8bfcb61c04b8d0384fceb042ea with parent db062de, future comparison URL.

@rust-timer
Copy link
Collaborator

Finished benchmarking commit (513ad0280218aa8bfcb61c04b8d0384fceb042ea): comparison url.

Summary: This change led to large relevant mixed results 🤷 in compiler performance.

  • Large improvement in instruction counts (up to -1.9% on full builds of cranelift-codegen)
  • Large regression in instruction counts (up to 3.3% on full builds of tokio-webpush-simple)

If you disagree with this performance assessment, please file an issue in rust-lang/rustc-perf.

Benchmarking this pull request likely means that it is perf-sensitive, so we're automatically marking it as not fit for rolling up. While you can manually mark this PR as fit for rollup, we strongly recommend not doing so since this PR led to changes in compiler perf.

Next Steps: If you can justify the regressions found in this try perf run, please indicate this with @rustbot label: +perf-regression-triaged along with sufficient written justification. If you cannot justify the regressions please fix the regressions and do another perf run. If the next run shows neutral or positive results, the label will be automatically removed.

@bors rollup=never
@rustbot label: +S-waiting-on-review -S-waiting-on-perf +perf-regression

@rustbot rustbot added perf-regression Performance regression. and removed S-waiting-on-perf Status: Waiting on a perf run to be completed. labels Nov 2, 2021
arg_new!(new_pointer, Pointer);
arg_new!(new_binary, Binary);
arg_new!(new_lower_exp, LowerExp);
arg_new!(new_upper_exp, UpperExp);
Copy link
Member

Choose a reason for hiding this comment

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

Can these be inlined into the format_args!() expansion?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

These are generic functions so I think yes.

Copy link
Member

Choose a reason for hiding this comment

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

I actually meant can we inline their definition into the format_args!() expansion and omit those function definitions themself.

@nbdd0121 nbdd0121 force-pushed the const_panic branch 2 times, most recently from fc830ab to c3ea64c Compare November 9, 2021 21:30
@nbdd0121
Copy link
Contributor Author

nbdd0121 commented Nov 9, 2021

(Pushed to the wrong branch)

@rust-log-analyzer

This comment has been minimized.

@JohnCSimon JohnCSimon added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jan 30, 2022
bors added a commit to rust-lang-ci/rust that referenced this pull request Jan 31, 2022
Create `core::fmt::ArgumentV1` with generics instead of fn pointer

Split from (and prerequisite of) rust-lang#90488, as this seems to have perf implication.

`@rustbot` label: +T-libs
flip1995 pushed a commit to flip1995/rust that referenced this pull request Feb 10, 2022
Create `core::fmt::ArgumentV1` with generics instead of fn pointer

Split from (and prerequisite of) rust-lang#90488, as this seems to have perf implication.

`@rustbot` label: +T-libs
@Dylan-DPC Dylan-DPC added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Feb 19, 2022
@Dylan-DPC
Copy link
Member

@nbdd0121 this has conflicts to be resolved, once done we can get this reviewed quickly after that

@oli-obk
Copy link
Contributor

oli-obk commented Feb 19, 2022

Summary of the zulip thread:

There are three ways to continue:

  • do nothing, keep status quo. Not bad, not great either
  • do this PR, allowing all types that implement Display, but bail out by printing some form of <can't print>. This means we can just print all types conveniently, but it also means we need to keep this complex logic around forever and possibly extend it with more and more special handling. It may also be surprising, similar to how it would be suprising if {:?} would accept types that don't implement Debug, but just print some default message
  • restrict this PR to types that we know can have some CTFE logic to print them in the future, so that we can revert the PR some day without a breaking change and instead.

Ralf and I consider option 2 to be problematic and would prefer to go with option 3. We can always go for option 2 later, but if we start with it we can't revert to option 3.

That said, we need a feature gate for this anyway, so we could just merge it modulo some additional tests making sure the feature gate works and split out option 3 under a separate gate later.

@JohnCSimon JohnCSimon added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Mar 20, 2022
@JohnCSimon JohnCSimon added the I-needs-decision Issue: In need of a decision. label Apr 23, 2022
@c410-f3r
Copy link
Contributor

In order to make #96496 work in constant environments (or even a future stabilization), this PR or functionality is a must have.

@nbdd0121
Copy link
Contributor Author

This PR has been stagnated due to lack of strong motivating use case -- I am glad that it now has one!

@oli-obk
Copy link
Contributor

oli-obk commented May 12, 2022

Can you elaborate on what functionality of this PR is needed? Afaict option 3 is sufficient for #96496

@nbdd0121
Copy link
Contributor Author

If we have a, b of type T: Debug but not a restricted const printable type, then assert!(a == b) currently works in const context, but not with #96496.

@RalfJung
Copy link
Member

That sounds like a bug in the implementation of #96496.

Inside a const fn, it can only debug-print things if they are const Debug, of course.

@nbdd0121
Copy link
Contributor Author

nbdd0121 commented May 12, 2022

That sounds like a bug in the implementation of #96496.

Inside a const fn, it can only debug-print things if they are const Debug, of course.

That'll make a const fn and a non-const fn behave differently even if the const fn is not called in const context.

@oli-obk
Copy link
Contributor

oli-obk commented May 12, 2022

That'll make a const fn and a non-const fn behave differently even if the non-const fn is not called in const context.

you cannot call non-const fn from const fn at all. Did you flip non-const and const in the second part of your sentence?

@c410-f3r
Copy link
Contributor

c410-f3r commented May 12, 2022

Can you elaborate on what functionality of this PR is needed? Afaict option 3 is sufficient for #96496

const _: () = {
    let a = 1;
    assert!(a != 1);
};

Currently works but such thing won't be possible in #96496 without constant panic! formatting. I am not familiar enough with the internals of CTFE to conclude which option could satisfy this use-case.

@oli-obk
Copy link
Contributor

oli-obk commented May 12, 2022

As long as #96496 only requires integers and booleans to be formattable, then it will work out of the box. If it requires arbitrary types to be formattable (e.g. Mutex or something else that does things that are impossible in const eval), then it will not be possible in const eval

@c410-f3r
Copy link
Contributor

c410-f3r commented May 12, 2022

As long as #96496 only requires integers and booleans to be formattable, then it will work out of the box. If it requires arbitrary types to be formattable (e.g. Mutex or something else that does things that are impossible in const eval), then it will not be possible in const eval

Yes, types are arbitrary but all must implement Copy and Debug to be eligible for displaying. Will these bounds satisfy the required restrictions of const printing?

@oli-obk
Copy link
Contributor

oli-obk commented May 12, 2022

Yes, types are arbitrary but all must implement Copy and Debug to be eligible for displaying. Will these bounds satisfy the required restrictions of const printing?

ah perfect. If you are going via trait bounds instead of just syntax, then it will reject all types that do not implement const Debug, but only within const contexts. Even if your current impl does not manage this yet, we can always address that later. I feared it was a syntactical thing, where assert!(non_debug_type == foo) would fail to compile in the future.

@c410-f3r
Copy link
Contributor

Yes, types are arbitrary but all must implement Copy and Debug to be eligible for displaying. Will these bounds satisfy the required restrictions of const printing?

ah perfect. If you are going via trait bounds instead of just syntax, then it will reject all types that do not implement const Debug, but only within const contexts. Even if your current impl does not manage this yet, we can always address that later. I feared it was a syntactical thing, where assert!(non_debug_type == foo) would fail to compile in the future.

Thanks! Looking forward to see

const _: () = {
    let a = 1i32;
    panic!("Something {}", a);
};

Work someday

@oli-obk
Copy link
Contributor

oli-obk commented May 12, 2022

That'll make a const fn and a non-const fn behave differently even if the const fn is not called in const context.

This is what will happen for all other traits, too, not just Debug/Display.

On the PR itself:

I would like to move this PR along. But neither Ralf nor I will approve the current version. I know you feel strongly for allowing arbitrary types to be printed in const eval, even if they are unprintable (e.g. pointers). While I personally don't ever want this, and think you should not propose it, I think the right way to get this approved in your version would be an RFC/lang-team-MCP. Your proposed scheme just diverges too far from what we have right now, it can't just be a simple feature and stabilization.

Please consider restricting your implementation to builtin types that are guaranteed to get const evaluable Debug and Display impls

@oli-obk oli-obk removed the I-needs-decision Issue: In need of a decision. label May 20, 2022
@Dylan-DPC
Copy link
Member

Closing this based on comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-const-eval Area: constant evaluation (mir interpretation) perf-regression Performance regression. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.