Port `dead_code` lints to be translatable.
This adds an additional comma to lists with three or more items, to be consistent with list formatters like `icu4x`.
r? `@davidtwco`
Rewrite implementation of `#[alloc_error_handler]`
The new implementation doesn't use weak lang items and instead changes `#[alloc_error_handler]` to an attribute macro just like `#[global_allocator]`.
The attribute will generate the `__rg_oom` function which is called by the compiler-generated `__rust_alloc_error_handler`. If no `__rg_oom` function is defined in any crate then the compiler shim will call `__rdl_oom` in the alloc crate which will simply panic.
This also fixes link errors with `-C link-dead-code` with `default_alloc_error_handler`: `__rg_oom` was previously defined in the alloc crate and would attempt to reference the `oom` lang item, even if it didn't exist. This worked as long as `__rg_oom` was excluded from linking since it was not called.
This is a prerequisite for the stabilization of `default_alloc_error_handler` (#102318).
The new implementation doesn't use weak lang items and instead changes
`#[alloc_error_handler]` to an attribute macro just like
`#[global_allocator]`.
The attribute will generate the `__rg_oom` function which is called by
the compiler-generated `__rust_alloc_error_handler`. If no `__rg_oom`
function is defined in any crate then the compiler shim will call
`__rdl_oom` in the alloc crate which will simply panic.
This also fixes link errors with `-C link-dead-code` with
`default_alloc_error_handler`: `__rg_oom` was previously defined in the
alloc crate and would attempt to reference the `oom` lang item, even if
it didn't exist. This worked as long as `__rg_oom` was excluded from
linking since it was not called.
This is a prerequisite for the stabilization of
`default_alloc_error_handler` (#102318).
Note scope of TAIT more accurately
This maybe explains why the person was confused in #101897, since we say "same module" but really should've said "same impl".
r? ``@oli-obk``
translation: doc comments with derives, subdiagnostic-less enum variants, more derive use
- Adds support for `doc` attributes in the diagnostic derives so that documentation comments don't result in the derive failing.
- Adds support for enum variants in the subdiagnostic derive to not actually correspond to an addition to a diagnostic.
- Made use of the derive in more places in the `rustc_ast_lowering`, `rustc_ast_passes`, `rustc_lint`, `rustc_session`, `rustc_infer` - taking advantage of recent additions like eager subdiagnostics, multispan suggestions, etc.
cc #100717
Move `IntoDiagnostic` conformance for `TargetDataLayoutErrors` into `rustc_errors`
Addressed this suggestion https://github.com/rust-lang/rust/pull/101558#issuecomment-1243830009.
This way we comply with the Coherence rule given that `IntoDiagnostic` trait is defined in `rustc_errors`, and almost all other crates depend on it.
If we fail to locate a native library that we are linking with, it could
be the case the user entered a complete file name like `foo.lib` or
`libfoo.a` when we expect them to simply provide `foo`.
In this situation, we now detect that case and suggest the user only
provide the library name itself.
Enforce alphabetical sorting with tidy
We have many places where things are supposed to be sorted alphabetically. For the smaller and more recent size assertions, this is mostly upheld, but in other more... alive places it's very messy.
This introduces a new tidy directive to check that a section of code is sorted alphabetically and fixes all places where sorting has gone wrong.
translation: eager translation
Part of #100717. See [Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20lists!/near/295010720) for additional context.
- **Store diagnostic arguments in a `HashMap`**: Eager translation will enable subdiagnostics to be translated multiple times with different arguments - this requires the ability to replace the value of one argument with a new value, which is better suited to a `HashMap` than the previous storage, a `Vec`.
- **Add `AddToDiagnostic::add_to_diagnostic_with`**: `AddToDiagnostic::add_to_diagnostic_with` is similar to the previous `AddToDiagnostic::add_to_diagnostic` but takes a function that can be used by the caller to modify diagnostic messages originating from the subdiagnostic (such as performing translation eagerly). `add_to_diagnostic` now just calls `add_to_diagnostic_with` with an empty closure.
- **Add `DiagnosticMessage::Eager`**: Add variant of `DiagnosticMessage` for eagerly translated messages
(messages in the target language which don't need translated by the emitter during emission). Also adds `eager_subdiagnostic` function which is intended to be invoked by the diagnostic derive for subdiagnostic fields which are marked as needing eager translation.
- **Support `#[subdiagnostic(eager)]`**: Add support for `eager` argument to the `subdiagnostic` attribute which generates a call to `eager_subdiagnostic`.
- **Finish migrating `rustc_query_system`**: Using eager translation, migrate the remaining repeated cycle stack diagnostic.
- **Split formatting initialization and use in diagnostic derives**: Diagnostic derives have previously had to take special care when ordering the generated code so that fields were not used after a move.
This is unlikely for most fields because a field is either annotated with a subdiagnostic attribute and is thus likely a `Span` and copiable, or is a argument, in which case it is only used once by `set_arg`
anyway.
However, format strings for code in suggestions can result in fields being used after being moved if not ordered carefully. As a result, the derive currently puts `set_arg` calls last (just before emission), such as:
let diag = { /* create diagnostic */ };
diag.span_suggestion_with_style(
span,
fluent::crate::slug,
format!("{}", __binding_0),
Applicability::Unknown,
SuggestionStyle::ShowAlways
);
/* + other subdiagnostic additions */
diag.set_arg("foo", __binding_0);
/* + other `set_arg` calls */
diag.emit();
For eager translation, this doesn't work, as the message being translated eagerly can assume that all arguments are available - so arguments _must_ be set first.
Format strings for suggestion code are now separated into two parts - an initialization line that performs the formatting into a variable, and a usage in the subdiagnostic addition.
By separating these parts, the initialization can happen before arguments are set, preserving the desired order so that code compiles, while still enabling arguments to be set before subdiagnostics are added.
let diag = { /* create diagnostic */ };
let __code_0 = format!("{}", __binding_0);
/* + other formatting */
diag.set_arg("foo", __binding_0);
/* + other `set_arg` calls */
diag.span_suggestion_with_style(
span,
fluent::crate::slug,
__code_0,
Applicability::Unknown,
SuggestionStyle::ShowAlways
);
/* + other subdiagnostic additions */
diag.emit();
- **Remove field ordering logic in diagnostic derive:** Following the approach taken in earlier commits to separate formatting initialization from use in the subdiagnostic derive, simplify the diagnostic derive by removing the field-ordering logic that previously solved this problem.
r? ```@compiler-errors```
Migrate rustc_passes diagnostics
Picks up abandoned work from https://github.com/rust-lang/rust/pull/100870
I would like to do this collaboratively, as there is a lot of work! Here's the process:
- Comment below that you are willing to help and I will add you as a collaborator to my `rust` fork (that gives you write access)
- Indicate which file/task you would like to work on (so we don't duplicate work) from the list below
- Do the work, push up a commit, comment that you're done with that file/task
- Repeat until done 😄
### Files to Migrate (in `compiler/rustc_passes/src/`)
- [x] check_attr.rs ``@CleanCut``
- [x] check_const.rs ``@CleanCut``
- [x] dead.rs ``@CleanCut``
- [x] debugger_visualizer.rs ``@CleanCut``
- [x] diagnostic_items.rs ``@CleanCut``
- [x] entry.rs ``@CleanCut``
- [x] lang_items.rs ``@CleanCut``
- [x] layout_test.rs ``@CleanCut``
- [x] lib_features.rs ``@CleanCut``
- [x] ~liveness.rs~ ``@CleanCut`` Nothing to do
- [x] loops.rs ``@CleanCut``
- [x] naked_functions.rs ``@CleanCut``
- [x] stability.rs ``@CleanCut``
- [x] weak_lang_items.rs ``@CleanCut``
### Tasks
- [x] Rebase on current `master` ``@CleanCut``
- [x] Review work from [the earlier PR](https://github.com/rust-lang/rust/pull/100870) and make sure it all looks good
- [x] compiler/rustc_error_messages/locales/en-US/passes.ftl ``@CleanCut``
- [x] compiler/rustc_passes/src/check_attr.rs ``@CleanCut``
- [x] compiler/rustc_passes/src/errors.rs ``@CleanCut``
- [x] compiler/rustc_passes/src/lang_items.rs ``@CleanCut``
- [x] compiler/rustc_passes/src/lib.rs ``@CleanCut``
- [x] compiler/rustc_passes/src/weak_lang_items.rs ``@CleanCut``
Add variant of `DiagnosticMessage` for eagerly translated messages
(messages in the target language which don't need translated by the
emitter during emission). Also adds `eager_subdiagnostic` function which
is intended to be invoked by the diagnostic derive for subdiagnostic
fields which are marked as needing eager translation.
Signed-off-by: David Wood <david.wood@huawei.com>
- UPDATE - revert migration of logs
- UPDATE - use derive on LinkRlibError enum
- [Gardening] UPDATE - alphabetically sort fluent_messages
- UPDATE - use PathBuf and unify both AddNativeLibrary to use Display (which is what PathBuf uses when conforming to IntoDiagnosticArg)
- UPDATE - fluent messages sort after rebase
Lint against nested opaque types that don't satisfy associated type bounds
See the test failures for examples of places where this lint would fire.
r? `@oli-obk`
errors: rename `typeck.ftl` to `hir_analysis.ftl`
In #102306, `rustc_typeck` was renamed to `rustc_hir_analysis` but the diagnostic resources were not renamed - which is what this pull request changes.
In #102306, `rustc_typeck` was renamed to `rustc_hir_analysis` but the
diagnostic resources were not renamed - which is what this commit
changes.
Signed-off-by: David Wood <david.wood@huawei.com>
Move lint level source explanation to the bottom
So, uhhhhh
r? `@estebank`
## User-facing change
"note: `#[warn(...)]` on by default" and such are moved to the bottom of the diagnostic:
```diff
- = note: `#[warn(unsupported_calling_conventions)]` on by default
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #87678 <https://github.com/rust-lang/rust/issues/87678>
+ = note: `#[warn(unsupported_calling_conventions)]` on by default
```
Why warning is enabled is the least important thing, so it shouldn't be the first note the user reads, IMO.
## Developer-facing change
`struct_span_lint` and similar methods have a different signature.
Before: `..., impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>)`
After: `..., impl Into<DiagnosticMessage>, impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>) -> &'b mut DiagnosticBuilder<'a, ()>`
The reason for this is that `struct_span_lint` needs to edit the diagnostic _after_ `decorate` closure is called. This also makes lint code a little bit nicer in my opinion.
Another option is to use `impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>) -> DiagnosticBuilder<'a, ()>` altough I don't _really_ see reasons to do `let lint = lint.build(message)` everywhere.
## Subtle problem
By moving the message outside of the closure (that may not be called if the lint is disabled) `format!(...)` is executed earlier, possibly formatting `Ty` which may call a query that trims paths that crashes the compiler if there were no warnings...
I don't think it's that big of a deal, considering that we move from `format!(...)` to `fluent` (which is lazy by-default) anyway, however this required adding a workaround which is unfortunate.
## P.S.
I'm sorry, I do not how to make this PR smaller/easier to review. Changes to the lint API affect SO MUCH 😢
Migrate rustc_codegen_gcc to SessionDiagnostics
As part of #100717 this pr migrates diagnostics to `SessionDiagnostics` for the `rustc_codegen_gcc` crate.
``@rustbot`` label +A-translation
Rollup of 8 pull requests
Successful merges:
- #100734 (Split out async_fn_in_trait into a separate feature)
- #101664 (Note if mismatched types have a similar name)
- #101815 (Migrated the rustc_passes annotation without effect diagnostic infrastructure)
- #102042 (Distribute rust-docs-json via rustup.)
- #102066 (rustdoc: remove unnecessary `max-width` on headers)
- #102095 (Deduplicate two functions that would soon have been three)
- #102104 (Set 'exec-env:RUST_BACKTRACE=0' in const-eval-select tests)
- #102112 (Allow full relro on powerpc64-unknown-linux-gnu)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Migrated the rustc_passes annotation without effect diagnostic infrastructure
Small change to move the validation for annotations to the new diagnostic infrastructure.
change AccessLevels representation
Part of RFC (https://github.com/rust-lang/rust/issues/48054). This patch implements effective visibility table with basic methods and change AccessLevels table representation according to it.
r? ``@petrochenkov``
add note for `layout_of` when query depth overflows
Fixes#101747
Added `try_find_layout_root` function to add a note for `layout_of` when query depth overflows. This would make the error in #101747 look like this:
```
error: queries overflow the depth limit!
|
note: Query depth increased by 66 when computing layout of `core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<core::option::Option<alloc::boxed::Box<alloc::string::String>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>`!
--> D:\rust-backup\parallel_rust\query_depth.rs:40:1
|
40 | fn main() {
| ^^^^^^^^^
error: aborting due to previous error
```
cc ``@semicoleon``
change rlib format to distinguish native dependencies
Another one method to solve problem mentioned in #99429.
Changed .rlib format, it contains all bundled native libraries as archieves.
At link time rlib is unpacked and native dependencies linked separately.
New behavior hidden under separate_native_rlib_dependencies flag.
ssa: implement `#[collapse_debuginfo]`
cc #39153rust-lang/compiler-team#386
Debuginfo line information for macro invocations are collapsed by default - line information are replaced by the line of the outermost expansion site. Using `-Zdebug-macros` disables this behaviour.
When the `collapse_debuginfo` feature is enabled, the default behaviour is reversed so that debuginfo is not collapsed by default. In addition, the `#[collapse_debuginfo]` attribute is available and can be applied to macro definitions which will then have their line information collapsed.
r? rust-lang/wg-debugging
translations(rustc_session): migrates rustc_session to use SessionDiagnostic - Pt. 2
# Description
This is the second part of the `rustc_session` [migration](https://github.com/rust-lang/rust/issues/100717#issuecomment-1220279883).
**Please only review this [commit](5018581957) that belongs to the part 2. The other ones are from the PR [#100753](https://github.com/rust-lang/rust/pull/100753) that is not yet merged.**
In this PR, we migrate the files `session.rs` and `config.rs`.
Please not that we have to `allow` the lints rules in some functions from `session.rs` because they are (at least I believe) part of the diagnostic machinery.
This commit removes the allows rules for the SessionDiagnostic lint
that were being used in the session.rs file.
Thanks to the PR #101230 we do not need to annotate the methods with
the allow rule as they are part of the diagnostic machinery.
Debuginfo line information for macro invocations are collapsed by
default - line information are replaced by the line of the outermost
expansion site. Using `-Zdebug-macros` disables this behaviour.
When the `collapse_debuginfo` feature is enabled, the default behaviour
is reversed so that debuginfo is not collapsed by default. In addition,
the `#[collapse_debuginfo]` attribute is available and can be applied to
macro definitions which will then have their line information collapsed.
Signed-off-by: David Wood <david.wood@huawei.com>
Suggest removing unnecessary prefix let in patterns
Helps with #101291, though I think `@estebank` probably wants this:
> Finally, I think it'd be nice if we could detect that we don't know for sure and "just" swallow the rest of the expression (find the next ; accounting for nested braces) or the end of the item (easier).
... to be implemented before we close that issue out completely.
Add warning against unexpected --cfg with --check-cfg
This PR adds a warning when an unexpected `--cfg` is specified but not in the specified list of `--check-cfg`.
This is the follow-up PR I mentioned in https://github.com/rust-lang/rust/pull/99519.
r? `@petrochenkov`
migrate rustc_query_system to use SessionDiagnostic
issues:
* variable list is not supported in fluent
* ~~cannot have two sub diagnostic with the same tag (eg. 2 .note or 2 .help)~~
allow multiple tag with SessionSubdiagnostic derive
- ... when creating diagnostics in rustc_metadata
- use the error_code! macro
- pass macro output to diag.code()
- use fluent from within manual implementation of SessionDiagnostic
- emit the untested errors in case they occur in the wild
- stop panicking in the probably-not-dead code, add fixme to write test
translations(rustc_session): migrates `rustc_session` to use `SessionDiagnostic` - Pt. 1
## Description
This is the first PR for the migration of the module `rustc_session`. You can follow my progress [here](https://github.com/rust-lang/rust/issues/100717#issuecomment-1220279883).
The PR migrates the files `cgu_reuse_tracker` and `parse.rs` to use `SessionDiagnostic `.
Migrate rustc_monomorphize to use SessionDiagnostic
### Description
- Migrates diagnostics in `rustc_monomorphize` to use `SessionDiagnostic`
- Adds an `impl IntoDiagnosticArg for PathBuf`
### TODO / Help!
- [x] I'm having trouble figuring out how to apply an optional note. 😕 Help!?
- Resolved. It was bad docs. Fixed in https://github.com/rust-lang/rustc-dev-guide/pull/1437/files
- [x] `errors:RecursionLimit` should be `#[fatal ...]`, but that doesn't exist so it's `#[error ...]` at the moment.
- Maybe I can switch after this is merged in? --> https://github.com/rust-lang/rust/pull/100694
- Or maybe I need to manually implement `SessionDiagnostic` instead of deriving it?
- [x] How does one go about converting an error inside of [a call to struct_span_lint_hir](8064a49508/compiler/rustc_monomorphize/src/collector.rs (L917-L927))?
- [x] ~What placeholder do you use in the fluent template to refer to the value in a vector? It seems like [this code](0b79f758c9/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs (L83-L114)) ought to have the answer (or something near it)...but I can't figure it out.~ You can't. Punted.
Thought of doing this by having a struct and an enum with Default and Alt cases, but not sure if we wanted to have the text in code instead of having “demangling()” and “demangling-alt()” in the ftl file.
Don’t like the current way of having structs representing the same-ish and using long names to distinguish their expectations, instead of putting this in an enum and handling the different cases inside the type.
I am fine with whichever option the team prefers; also understand having them as separate structs keeps it simple.
Migrate rustc_driver to SessionDiagnostic
First timer noob here 👋🏽 I'm having a problem understanding how I can retrieve the span, and how to properly construct the error structs to avoid the current compilation errors.
Any help pointing me in the right direction would be much appreciated 🙌🏽
Migrate `rustc_attr` crate diagnostics
Hi!
This is my first PR to the rustc project, excited to be part of the development! This PR is part of the diagnostics effort, to make diagnostics translatable.
`@rustbot` label +A-translation
Diagnostics migr const eval
This PR should eventually contain all diagnostic migrations for the `rustc_const_eval` crate.
r? `@davidtwco`
`@rustbot` label +A-translation
Migrate `rustc_ty_utils` to `SessionDiagnostic`
I have migrated the `rustc_ty_utils` crate to use `SessionDiagnostic`, motivated by the [recent blog post about the diagnostic translation effort](https://blog.rust-lang.org/inside-rust/2022/08/16/diagnostic-effort.html).
This is my first PR to the Rust repository, so if I have missed anything, or anything needs to be changed, please let me know! 😄
`@rustbot` label +A-translation
Migrate ast lowering to session diagnostic
I migrated the whole rustc_ast_lowering crate to session diagnostic *except* the for the use of `span_fatal` at /compiler/rustc_ast_lowering/src/expr.rs#L1268 because `#[fatal(...)]` is not yet supported (see https://github.com/rust-lang/rust/pull/100694).
This commit migrates the errors in the function check_expected_reuse
to use the new SessionDiagnostic. It also does some small refactor
for the IncorrectCguReuseType to include the 'at least' word in the
fluent translation file
fluent: mandate slug names to be prefixed by crate name
This is currently only convention, but not actively checked for.
Additionally, improve error messages to highlight the path of the offending fluent file rather than the identifier preceding it.
This will conflict with #100671, so I'll leave it as draft until that's merged.
Migrate `rustc_plugin_impl` to `SessionDiagnostic`
Migration of the `rustc_plugin_impl` crate.
~Draft PR because it is blocked on #100694 for `#[fatal(...)]` support~ (this has been merged, and I've changed over to `#[diag(...)]` now too), but I would also like to know if what I did with `LoadPluginError` is okay, because all it does is display the error message from `libloading` ([See conversation on zulip](https://rust-lang.zulipchat.com/#narrow/stream/147480-t-compiler.2Fwg-diagnostics/topic/.23100717.20diagnostic.20translation/near/294327843)). This crate is apparently for a deprecated feature which is used by servo, so I don't know how much this matters anyway.
Convert diagnostics in parser/expr to SessionDiagnostic
This migrates all the easy cases in `rustc_parse::parser::expr` to `SessionDiagnostic`s, I've left things such as `multipart_suggestion`s out for now in the hopes of a derive API being developed soon.
Migrate rustc_ast_passes diagnostics to `SessionDiagnostic` and translatable messages (first part)
Doing a full migration of the `rustc_ast_passes` crate.
Making a draft here since there's not yet a tracking issue for the migrations going on.
`@rustbot` label +A-translation
Add the diagnostic translation lints to crates that don't emit them
Some of these have a note saying that they should build on a stable compiler, does that mean they shouldn't get these lints? Or can we cfg them out on those?
Migrate "invalid variable declaration" errors to SessionDiagnostic
After seeing the great blog post on Inside Rust, I decided to try my hand at this. Just one diagnostic for now to get used to the workflow and to check if this is the way to do it or if there are any problems.
Do not allow `Drop` impl on foreign fundamental types
`Drop` should not be implemented on `Pin<T>` even if `T` is local.
This does not trigger regular orphan rules is because `Pin` is `#[fundamental]`... but we don't allow specialized `Drop` impls anyways, so these rules are not sufficient to prevent this impl on stable. Let's just choose even stricter rules, since we shouldn't be implementing `Drop` on a foreign ADT ever.
Fixes#99575
Migrate lint reports in typeck::check_unused to LintDiagnostic
In this PR, I migrate two lint reports in `typeck::check_unused` by `LintDiagnostic`, all of which is about extern crates.
```@rustbot``` label +A-translation
r? rust-lang/diagnostics
Migrations for rustc_expand transcribe.rs
This PR includes some migrations to the new diagnostics API for the `rustc_expand` module.
r? ```@davidtwco```
Replace - with _ in fluent slugs to improve developer workflows
This is a proposal to smoothen the compiler contribution experience in the face of the move to fluent.
## Context
The fluent project has introduced a layer of abstraction to compiler errors. Previously, people would write down error messages directly in the same file the code was located to emit them. Now, there is a slug that connects the code in the compiler to the error message in the ftl file.
You can look at 7ef610c003 to see an example of the changes:
Old:
```Rust
let msg = format!(
"bounds on `{}` are most likely incorrect, consider instead \
using `{}` to detect whether a type can be trivially dropped",
predicate,
cx.tcx.def_path_str(needs_drop)
);
lint.build(&msg).emit();
```
New (Rust side):
```Rust
lint.build(fluent::lint::drop_trait_constraints)
.set_arg("predicate", predicate)
.set_arg("needs_drop", cx.tcx.def_path_str(needs_drop))
.emit();
```
New (Fluent side):
```fluent
lint-drop-trait-constraints =
bounds on `{$predicate}` are most likely incorrect, consider instead using `{$needs_drop}` to detect whether a type can be trivially dropped
```
You will note that in the ftl file, the slug is slightly different from the slug in the Rust file: The ftl slug uses `-` (e.g. `lint-drop-trait-constraints`) while the rust slug uses `::` and `_` (e.g. `lint::drop_trait_constraints`). This choice was probably done due to:
* Rust not accepting `-` in identifiers (as it is an operator)
* fluent not supporting the `:` character in slug names (parse error upon attempts)
* all official fluent documentation using `-` instead of `_`
## The problem
The two different types of slugs, one with `-`, and one with `_`, cause difficulties for contributors. Imagine you don't have perfect knowledge of where stuff is in the compiler (i would say this is most people), and you encounter an error for which you think there is something you could improve that is not just a rewording.
So you want to find out where in the compiler's code that error is being emitted. The best way is via grepping.
1. you grep for the message in the compiler's source code. You discover the ftl file and find out the slug for that error.
2. That slug however contains `-` instead of `_`, so you have to manually translate the `-`'s into `_`s, and furthermore either remove the leading module name, or replace the first `-` with a `::`.
3. you do a second grep to get to the emitting location in the compiler's code.
This translation difficulty in step 2 appears also in the other direction when you want to figure out what some code in the compiler is doing and use error messages to help your understanding. Comments and variable names are way less exposed to users so [are more likely going to lie](cc3c5d2700) than error messages.
I think that at least the `-`→`_` translation which makes up most of step 2 can be removed at low cost.
## The solution
If you look closely, the practice of fluent to use `-` is only a stylistic choice and it is not enforced by fluent implementations, neither the playground nor the one the rust compiler uses, that slugs may not contain `_`. Thus, we can in fact migrate the ftl side to `_`. So now we'll have slugs like `lint_drop_trait_constraints` on the ftl side. You only have to do one replacement now to get to the Rust slug: remove the first `_` and place a `::` in its stead. I would argue that this change is in fact useful as it allows you to control whether you want to look at the rust side of things or the ftl side of things via changing the query string only: with an increased number of translations checked into the repository, grepping for raw slugs will return the slug in many ftl files, so an explicit step to look for the source code is always useful. In the other direction (rust to fluent), you don't need a translation at all any more, as you can just take the final piece of the slug (e.g. `drop_trait_constraints`) and grep for that. The PR also adds enforcement to forbid usage of `_` in slug names. Internal slug names (those leading with a `-`) are exempt from that enforcement.
As another workflow that benefits from this change, people who add new errors don't have to do that `-` conversion either.
| Before/After | Fluent slug | Rust slug (no change) |
|--|--|--|
| Before | `lint-drop-trait-constraints` | `lint::drop_trait_constraints`|
| After | `lint_drop_trait_constraints` | `lint::drop_trait_constraints`|
Note that I've suggested this previously in the translation thread on zulip. I think it's important to think about non-translator contribution impact of fluent. I have certainly plans for more improvements, but this is a good first step.
``@rustbot`` label A-diagnostics
Having to replace - with _ (and vice versa) makes the slugs less greppable
and thus constitutes a contributor roadblock.
Result of running this repeatedly up until reaching a fixpoint:
find compiler/rustc_error_messages/locales/en-US/ -type f -exec sed -i 's/\(.+\)-\(.*\)=/\1_\2=/' {} \;
Plus some fixes to update usages of slugs leading with -.
Some command-line options accessible through `sess.opts` are best
accessed through wrapper functions on `Session`, `TyCtxt` or otherwise,
rather than through field access on the option struct in the `Session`.
Adds a new lint which triggers on those options that should be accessed
through a wrapper function so that this is prohibited. Options are
annotated with a new attribute `rustc_lint_opt_deny_field_access` which
can specify the error message (i.e. "use this other function instead")
to be emitted.
A simpler alternative would be to simply rename the options in the
option type so that it is clear they should not be used, however this
doesn't prevent uses, just discourages them. Another alternative would
be to make the option fields private, and adding accessor functions on
the option types, however the wrapper functions sometimes rely on
additional state from `Session` or `TyCtxt` which wouldn't be available
in an function on the option type, so the accessor would simply make the
field available and its use would be discouraged too.
Signed-off-by: David Wood <david.wood@huawei.com>