Skip to content

Commit dc7559b

Browse files
authored
Rollup merge of #107789 - jieyouxu:issue-107745, r=lcnr
Avoid exposing type parameters and implementation details sourced from macro expansions Fixes #107745. ~~I would like to **request some guidance** for this issue, because I don't think this is a good fix (a band-aid at best).~~ ### The Problem The code ```rust fn main() { println!("{:?}", []); } ``` gets desugared into (`rustc +nightly --edition=2018 issue-107745.rs -Z unpretty=hir`): ```rust #[prelude_import] use std::prelude::rust_2018::*; #[macro_use] extern crate std; fn main() { { ::std::io::_print(<#[lang = "format_arguments"]>::new_v1(&["", "\n"], &[<#[lang = "format_argument"]>::new_debug(&[])])); }; } ``` so the diagnostics code tries to be as specific and helpful as possible, and I think it finds that `[]` needs a type parameter and so does `new_debug`. But since `[]` doesn't have an origin for the type parameter definition, it points to `new_debug` instead and leaks the internal implementation detail since all `[]` has is an type inference variable. ### ~~The Bad Fix~~ ~~This PR currently tries to fix the problem by bypassing the generated function `<#[lang = "format_argument"]>::new_debug` to avoid its generic parameter (I think it is auto-generated from the argument `[_; 0]`?) from getting collected as an `InsertableGenericArg`. This is problematic because it also prevents the help from getting displayed.~~ ~~I think this fix is not ideal and hard-codes the format generated code pattern, but I can't think of a better fix. I have tried asking on Zulip but no responses there yet.~~
2 parents d1ac43a + b58347a commit dc7559b

8 files changed

+59
-26
lines changed

compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs

+14-9
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,12 @@ fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinte
158158
if infcx.probe_ty_var(ty_vid).is_ok() {
159159
warn!("resolved ty var in error message");
160160
}
161-
if let TypeVariableOriginKind::TypeParameterDefinition(name, _) =
162-
infcx.inner.borrow_mut().type_variables().var_origin(ty_vid).kind
161+
162+
let mut infcx_inner = infcx.inner.borrow_mut();
163+
let ty_vars = infcx_inner.type_variables();
164+
let var_origin = ty_vars.var_origin(ty_vid);
165+
if let TypeVariableOriginKind::TypeParameterDefinition(name, _) = var_origin.kind
166+
&& !var_origin.span.from_expansion()
163167
{
164168
Some(name)
165169
} else {
@@ -254,7 +258,7 @@ impl<'tcx> InferCtxt<'tcx> {
254258
if let TypeVariableOriginKind::TypeParameterDefinition(name, def_id) =
255259
var_origin.kind
256260
{
257-
if name != kw::SelfUpper {
261+
if name != kw::SelfUpper && !var_origin.span.from_expansion() {
258262
return InferenceDiagnosticsData {
259263
name: name.to_string(),
260264
span: Some(var_origin.span),
@@ -780,7 +784,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
780784
// The sources are listed in order of preference here.
781785
let tcx = self.infcx.tcx;
782786
let ctx = CostCtxt { tcx };
783-
let base_cost = match source.kind {
787+
match source.kind {
784788
InferSourceKind::LetBinding { ty, .. } => ctx.ty_cost(ty),
785789
InferSourceKind::ClosureArg { ty, .. } => ctx.ty_cost(ty),
786790
InferSourceKind::GenericArg { def_id, generic_args, .. } => {
@@ -797,17 +801,17 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
797801
InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => {
798802
30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 }
799803
}
800-
};
801-
802-
let suggestion_may_apply = if source.from_expansion() { 10000 } else { 0 };
803-
804-
base_cost + suggestion_may_apply
804+
}
805805
}
806806

807807
/// Uses `fn source_cost` to determine whether this inference source is preferable to
808808
/// previous sources. We generally prefer earlier sources.
809809
#[instrument(level = "debug", skip(self))]
810810
fn update_infer_source(&mut self, mut new_source: InferSource<'tcx>) {
811+
if new_source.from_expansion() {
812+
return;
813+
}
814+
811815
let cost = self.source_cost(&new_source) + self.attempt;
812816
debug!(?cost);
813817
self.attempt += 1;
@@ -819,6 +823,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> {
819823
// `let x: _ = iter.collect();`, as this is a very common case.
820824
*def_id = Some(did);
821825
}
826+
822827
if cost < self.infer_source_cost {
823828
self.infer_source_cost = cost;
824829
self.infer_source = Some(new_source);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// ignore-tidy-linelength
2+
3+
// Regression test for #107745.
4+
// Previously need_type_info::update_infer_source will consider expressions originating from
5+
// macro expressions as candiate "previous sources". This unfortunately can mean that
6+
// for macros expansions such as `format!()` internal implementation details can leak, such as:
7+
//
8+
// ```
9+
// error[E0282]: type annotations needed
10+
// --> src/main.rs:2:22
11+
// |
12+
//2 | println!("{:?}", []);
13+
// | ^^ cannot infer type of the type parameter `T` declared on the associated function `new_debug`
14+
// ```
15+
16+
fn main() {
17+
println!("{:?}", []);
18+
//~^ ERROR type annotations needed
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0282]: type annotations needed
2+
--> $DIR/issue-107745-avoid-expr-from-macro-expansion.rs:17:22
3+
|
4+
LL | println!("{:?}", []);
5+
| ^^ cannot infer type
6+
|
7+
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
8+
9+
error: aborting due to previous error
10+
11+
For more information about this error, try `rustc --explain E0282`.

tests/ui/issues/issue-16966.stderr

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
error[E0282]: type annotations needed
2-
--> $DIR/issue-16966.rs:2:5
2+
--> $DIR/issue-16966.rs:2:12
33
|
44
LL | panic!(std::default::Default::default());
5-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type of the type parameter `M` declared on the function `begin_panic`
6-
|
7-
= note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type
86

97
error: aborting due to previous error
108

tests/ui/parser/missing-closing-angle-bracket-eq-constraint.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ fn test2<T1, T2>(arg1 : T1, arg2 : T2) {
1717
fn test3<'a>(arg : &'a u32) {
1818
let v : Vec<'a = vec![];
1919
//~^ ERROR: expected one of
20-
//~| ERROR: type annotations needed for `Vec<T>`
20+
//~| ERROR: type annotations needed for `Vec<_>`
2121
}
2222

2323
fn main() {}

tests/ui/parser/missing-closing-angle-bracket-eq-constraint.stderr

+6-6
Original file line numberDiff line numberDiff line change
@@ -39,26 +39,26 @@ help: you might have meant to end the type parameters here
3939
LL | let v : Vec<'a> = vec![];
4040
| +
4141

42-
error[E0282]: type annotations needed for `Vec<T>`
42+
error[E0282]: type annotations needed for `Vec<_>`
4343
--> $DIR/missing-closing-angle-bracket-eq-constraint.rs:7:7
4444
|
4545
LL | let v : Vec<(u32,_) = vec![];
4646
| ^
4747
|
48-
help: consider giving `v` an explicit type, where the type for type parameter `T` is specified
48+
help: consider giving `v` an explicit type, where the placeholders `_` are specified
4949
|
50-
LL | let v: Vec<T> : Vec<(u32,_) = vec![];
50+
LL | let v: Vec<_> : Vec<(u32,_) = vec![];
5151
| ++++++++
5252

53-
error[E0282]: type annotations needed for `Vec<T>`
53+
error[E0282]: type annotations needed for `Vec<_>`
5454
--> $DIR/missing-closing-angle-bracket-eq-constraint.rs:18:7
5555
|
5656
LL | let v : Vec<'a = vec![];
5757
| ^
5858
|
59-
help: consider giving `v` an explicit type, where the type for type parameter `T` is specified
59+
help: consider giving `v` an explicit type, where the placeholders `_` are specified
6060
|
61-
LL | let v: Vec<T> : Vec<'a = vec![];
61+
LL | let v: Vec<_> : Vec<'a = vec![];
6262
| ++++++++
6363

6464
error: aborting due to 5 previous errors

tests/ui/type/type-check/cannot_infer_local_or_vec.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
error[E0282]: type annotations needed for `Vec<T>`
1+
error[E0282]: type annotations needed for `Vec<_>`
22
--> $DIR/cannot_infer_local_or_vec.rs:2:9
33
|
44
LL | let x = vec![];
55
| ^
66
|
7-
help: consider giving `x` an explicit type, where the type for type parameter `T` is specified
7+
help: consider giving `x` an explicit type, where the placeholders `_` are specified
88
|
9-
LL | let x: Vec<T> = vec![];
9+
LL | let x: Vec<_> = vec![];
1010
| ++++++++
1111

1212
error: aborting due to previous error

tests/ui/type/type-check/cannot_infer_local_or_vec_in_tuples.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
error[E0282]: type annotations needed for `(Vec<T>,)`
1+
error[E0282]: type annotations needed for `(Vec<_>,)`
22
--> $DIR/cannot_infer_local_or_vec_in_tuples.rs:2:9
33
|
44
LL | let (x, ) = (vec![], );
55
| ^^^^^ ---------- type must be known at this point
66
|
7-
help: consider giving this pattern a type, where the type for type parameter `T` is specified
7+
help: consider giving this pattern a type, where the placeholders `_` are specified
88
|
9-
LL | let (x, ): (Vec<T>,) = (vec![], );
9+
LL | let (x, ): (Vec<_>,) = (vec![], );
1010
| +++++++++++
1111

1212
error: aborting due to previous error

0 commit comments

Comments
 (0)