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

make format! accept const vars as format-strings #69133

Closed
matthiaskrgr opened this issue Feb 13, 2020 · 6 comments
Closed

make format! accept const vars as format-strings #69133

matthiaskrgr opened this issue Feb 13, 2020 · 6 comments

Comments

@matthiaskrgr
Copy link
Member

I wonder if we could make rustc accept code like this:

    const y: &str = "hello {}";
    let x = format!(y, "world");

Currently this errors with:

error: format argument must be a string literal
 --> src/main.rs:3:21
  |
3 |     let x = format!(y, "world");
  |                     ^
  |
help: you might be missing a string literal to format with
  |
3 |     let x = format!("{} {}", y, "world");
  |                     ^^^^^^^^

rustc 1.43.0-nightly (58b834344 2020-02-05)

@sfackler
Copy link
Member

Macros run before name resolution, so there's no way for format! to find the contents of the string y.

@Centril
Copy link
Contributor

Centril commented Feb 13, 2020

Closing with @sfackler's explanation.

@vgsantoniazzi
Copy link

If you want to interpolate like that, you can use stringify!

https://doc.rust-lang.org/std/macro.stringify.html

@EricHe56
Copy link

maybe a inline function can help on it.

@dtolnay
Copy link
Member

dtolnay commented Mar 26, 2023

I wonder whether this can be reconsidered now after #106745, as processing the format string no longer occurs during macro expansion, so it could do name resolution.

@m-ou-se?

@m-ou-se
Copy link
Member

m-ou-se commented Mar 27, 2023

Processing the string still happens during macro expansion actually. (The format string syntax is directly parsed, implicit arguments are directly resolved to their indexes, etc. etc.) It's just that instead of expanding to a fmt::Arguments::new(…) expression directly, it will expand to a special FormatArgs AST node first, which will be expanded to the call expression when lowering the AST to HIR.

(And if we want to be able to resolve names/constants, I think we'd need to postpone the parsing not only until the AST lowering, but even later in the HIR.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants