Skip to content

Commit 20fe7df

Browse files
anpmark-i-m
authored andcommitted
Implicit Caller Location section.
1 parent 595f2f3 commit 20fe7df

File tree

2 files changed

+281
-0
lines changed

2 files changed

+281
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@
109109
- [Updating LLVM](./backend/updating-llvm.md)
110110
- [Debugging LLVM](./backend/debugging.md)
111111
- [Backend Agnostic Codegen](./backend/backend-agnostic.md)
112+
- [Implicit Caller Location](./codegen/implicit-caller-location.md)
112113
- [Profile-guided Optimization](./profile-guided-optimization.md)
113114
- [Sanitizers Support](./sanitizers.md)
114115
- [Debugging Support in Rust Compiler](./debugging-support-in-rustc.md)
Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
# Implicit Caller Location
2+
3+
Approved in [RFC 2091], this feature enables the accurate reporting of caller location during panics
4+
initiated from functions like `Option::unwrap`, `Result::expect`, and `Index::index`. This feature
5+
adds the [`#[track_caller]`][attr-reference] attribute for functions, the
6+
[`caller_location`][intrinsic] intrinsic, and the stabilization-friendly
7+
[`core::panic::Location::caller`][wrapper] wrapper.
8+
9+
## Motivating Example
10+
11+
Take this example program:
12+
13+
```rust
14+
fn main() {
15+
let foo: Option<()> = None;
16+
foo.unwrap(); // this should produce a useful panic message!
17+
}
18+
```
19+
20+
Prior to Rust 1.42, panics like this `unwrap()` printed a location in libcore:
21+
22+
```
23+
$ rustc +1.41.0 example.rs; example.exe
24+
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value',...core\macros\mod.rs:15:40
25+
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
26+
```
27+
28+
As of 1.42, we get a much more helpful message:
29+
30+
```
31+
$ rustc +1.42.0 example.rs; example.exe
32+
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', example.rs:3:5
33+
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
34+
```
35+
36+
These error messages are achieved through a combination of changes to `panic!` internals to make use
37+
of `core::panic::Location::caller` and a number of `#[track_caller]` annotations in the standard
38+
library which propagate caller information.
39+
40+
## Reading Caller Location
41+
42+
Previously, `panic!` made use of the `file!()`, `line!()`, and `column!()` macros to construct a
43+
[`Location`] pointing to where the panic occurred. These macros couldn't be given an overridden
44+
location, so functions which intentionally invoked `panic!` couldn't provide their own location,
45+
hiding the actual source of error.
46+
47+
Internally, `panic!()` now calls [`core::panic::Location::caller()`][wrapper] to find out where it
48+
was expanded. This function is itself annotated with `#[track_caller]` and wraps the
49+
[`caller_location`][intrinsic] compiler intrinsic implemented by rustc. This intrinsic is easiest
50+
explained in terms of how it works in a `const` context.
51+
52+
## Caller Location in `const`
53+
54+
There are two main phases to returning the caller location in a const context: walking up the stack
55+
to find the right location and allocating a const value to return.
56+
57+
### Finding the right `Location`
58+
59+
In a const context we "walk up the stack" from where the intrinsic is invoked, stopping when we
60+
reach the first function call in the stack which does *not* have the attribute. This walk is in
61+
[`InterpCx::find_closest_untracked_caller_location()`][const-find-closest].
62+
63+
Starting at the bottom, we iterate up over stack [`Frame`][const-frame]s in the
64+
[`InterpCx::stack`][const-stack], calling
65+
[`InstanceDef::requires_caller_location`][requires-location] on the
66+
[`Instance`s from each `Frame`][frame-instance]. We stop once we find one that returns `false` and
67+
return the span of the *previous* frame which was the "topmost" tracked function.
68+
69+
### Allocating a static `Location`
70+
71+
Once we have a `Span`, we need to allocate static memory for the `Location`, which is performed by
72+
the [`TyCtxt::const_caller_location()`][const-location-query] query. Internally this calls
73+
[`InterpCx::alloc_caller_location()`][alloc-location] and results in a unique
74+
[memory kind][location-memory-kind] (`MemoryKind::CallerLocation`). The SSA codegen backend is able
75+
to emit code for these same values, and we use this code there as well.
76+
77+
Once our `Location` has been allocated in static memory, our intrinsic returns a reference to it.
78+
79+
## Generating code for `#[track_caller]` callees
80+
81+
To generate efficient code for a tracked function and its callers, we need to provide the same
82+
behavior from the intrinsic's point of view without having a stack to walk up at runtime. We invert
83+
the approach: as we grow the stack down we pass an additional argument to calls of tracked functions
84+
rather than walking up the stack when the intrinsic is called. That additional argument can be
85+
returned wherever the caller location is queried.
86+
87+
The argument we append is of type `&'static core::panic::Location<'staic>`. A reference was chosen
88+
to avoid unnecessary copying because a pointer is a third the size of
89+
`std::mem::size_of::<core::panic::Location>() == 24` at time of writing.
90+
91+
When generating a call to a function which is tracked, we pass the location argument the value of
92+
[`FunctionCx::get_caller_location`][fcx-get].
93+
94+
If the calling function is tracked, `get_caller_location` returns the local in
95+
[`FunctionCx::caller_location`][fcx-location] which was populated by the current caller's caller.
96+
In these cases the intrinsic "returns" a reference which was actually provided in an argument to its
97+
caller.
98+
99+
If the calling function is not tracked, `get_caller_location` allocates a `Location` static from
100+
the current `Span` and returns a reference to that.
101+
102+
We more efficiently achieve the same behavior as a loop starting from the bottom by passing a single
103+
`&Location` value through the `caller_location` fields of multiple `FunctionCx`s as we grow the
104+
stack downward.
105+
106+
### Codegen examples
107+
108+
What does this transformation look like in practice? Take this example which uses the new feature:
109+
110+
```rust
111+
#![feature(track_caller)]
112+
use std::panic::Location;
113+
114+
#[track_caller]
115+
fn print_caller() {
116+
println!("called from {}", Location::caller());
117+
}
118+
119+
fn main() {
120+
print_caller();
121+
}
122+
```
123+
124+
Here `print_caller()` appears to take no arguments, but we compile it to something like this:
125+
126+
```rust
127+
#![feature(panic_internals)]
128+
use std::panic::Location;
129+
130+
fn print_caller(caller: &Location) {
131+
println!("called from {}", caller);
132+
}
133+
134+
fn main() {
135+
print_caller(&Location::internal_constructor(file!(), line!(), column!()));
136+
}
137+
```
138+
139+
### Dynamic Dispatch
140+
141+
In codegen contexts we have to modify the callee ABI to pass this information down the stack, but
142+
the attribute expressly does *not* modify the type of the function. The ABI change must be
143+
transparent to type checking and remain sound in all uses.
144+
145+
Direct calls to tracked functions will always know the full codegen flags for the callee and can
146+
generate appropriate code. Indirect callers won't have this information and it's not encoded in
147+
the type of the function pointer they call, so we generate a [`ReifyShim`] around the function
148+
whenever taking a pointer to it. This shim isn't able to report the actual location of the indirect
149+
call (the function's definition site is reported instead), but it prevents miscompilation and is
150+
probably the best we can do without modifying fully-stabilized type signatures.
151+
152+
> *Note:* We always emit a [`ReifyShim`] when taking a pointer to a tracked function. While the
153+
> constraint here is imposed by codegen contexts, we don't know during MIR construction of the shim
154+
> whether we'll be called in a const context (safe to ignore shim) or in a codegen context (unsafe
155+
> to ignore shim). Even if we did know, the results from const and codegen contexts must agree.
156+
157+
## The Attribute
158+
159+
The `#[track_caller]` attribute is checked alongside other codegen attributes to ensure the
160+
function:
161+
162+
* has the `"Rust"` ABI (as opposed to e.g., `"C"`)
163+
* is not a foreign import (e.g., in an `extern {...}` block)
164+
* is not a closure
165+
* is not `#[naked]`
166+
167+
If the use is valid, we set [`CodegenFnAttrsFlags::TRACK_CALLER`][attrs-flags]. This flag influences
168+
the return value of [`InstanceDef::requires_caller_location`][requires-location] which is in turn
169+
used in both const and codegen contexts to ensure correct propagation.
170+
171+
### Traits
172+
173+
When applied to trait method implementations, the attribute works as it does for regular functions.
174+
175+
When applied to a trait method prototype, the attribute applies to all implementations of the
176+
method. When applied to a default trait method implementation, the attribute takes effect on
177+
that implementation *and* any overrides.
178+
179+
Examples:
180+
181+
```rust
182+
#![feature(track_caller)]
183+
184+
macro_rules! assert_tracked {
185+
() => {{
186+
let location = std::panic::Location::caller();
187+
assert_eq!(location.file(), file!());
188+
assert_ne!(location.line(), line!(), "line should be outside this fn");
189+
println!("called at {}", location);
190+
}};
191+
}
192+
193+
trait TrackedFourWays {
194+
/// All implementations inherit `#[track_caller]`.
195+
#[track_caller]
196+
fn blanket_tracked();
197+
198+
/// Implementors can annotate themselves.
199+
fn local_tracked();
200+
201+
/// This implementation is tracked (overrides are too).
202+
#[track_caller]
203+
fn default_tracked() {
204+
assert_tracked!();
205+
}
206+
207+
/// Overrides of this implementation are tracked (it is too).
208+
#[track_caller]
209+
fn default_tracked_to_override() {
210+
assert_tracked!();
211+
}
212+
}
213+
214+
/// This impl uses the default impl for `default_tracked` and provides its own for
215+
/// `default_tracked_to_override`.
216+
impl TrackedFourWays for () {
217+
fn blanket_tracked() {
218+
assert_tracked!();
219+
}
220+
221+
#[track_caller]
222+
fn local_tracked() {
223+
assert_tracked!();
224+
}
225+
226+
fn default_tracked_to_override() {
227+
assert_tracked!();
228+
}
229+
}
230+
231+
fn main() {
232+
<() as TrackedFourWays>::blanket_tracked();
233+
<() as TrackedFourWays>::default_tracked();
234+
<() as TrackedFourWays>::default_tracked_to_override();
235+
<() as TrackedFourWays>::local_tracked();
236+
}
237+
```
238+
239+
## Background/History
240+
241+
Broadly speaking, this feature's goal is to improve common Rust error messages without breaking
242+
stability guarantees, requiring modifications to end-user source, relying on platform-specific
243+
debug-info, or preventing user-defined types from having the same error-reporting benefits.
244+
245+
Improving the output of these panics has been a goal of proposals since at least mid-2016 (see
246+
[non-viable alternatives] in the approved RFC for details). It took two more years until RFC 2091
247+
was approved, much of its [rationale] for this feature's design having been discovered through the
248+
discussion around several earlier proposals.
249+
250+
The design in the original RFC limited itself to implementations that could be done inside the
251+
compiler at the time without significant refactoring. However in the year and a half between the
252+
approval of the RFC and the actual implementation work, a [revised design] was proposed and written
253+
up on the tracking issue. During the course of implementing that, it was also discovered that an
254+
implementation was possible without modifying the number of arguments in a function's MIR, which
255+
would simplify later stages and unlock use in traits.
256+
257+
Because the RFC's implementation strategy could not readily support traits, the semantics were not
258+
originally specified. They have since been implemented following the path which seemed most correct
259+
to the author and reviewers.
260+
261+
[RFC 2091]: https://github.com/rust-lang/rfcs/blob/master/text/2091-inline-semantic.md
262+
[attr-reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-track_caller-attribute
263+
[intrinsic]: https://doc.rust-lang.org/nightly/core/intrinsics/fn.caller_location.html
264+
[wrapper]: https://doc.rust-lang.org/nightly/core/panic/struct.Location.html#method.caller
265+
[non-viable alternatives]: https://github.com/rust-lang/rfcs/blob/master/text/2091-inline-semantic.md#non-viable-alternatives
266+
[rationale]: https://github.com/rust-lang/rfcs/blob/master/text/2091-inline-semantic.md#rationale
267+
[revised design]: https://github.com/rust-lang/rust/issues/47809#issuecomment-443538059
268+
[attrs-flags]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/middle/codegen_fn_attrs/struct.CodegenFnAttrFlags.html#associatedconstant.TRACK_CALLER
269+
[`ReifyShim`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.InstanceDef.html#variant.ReifyShim
270+
[`Location`]: https://doc.rust-lang.org/core/panic/struct.Location.html
271+
[const-find-closest]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/interpret/struct.InterpCx.html#method.find_closest_untracked_caller_location
272+
[requires-location]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.InstanceDef.html#method.requires_caller_location
273+
[alloc-location]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/interpret/struct.InterpCx.html#method.alloc_caller_location
274+
[fcx-location]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_codegen_ssa/mir/struct.FunctionCx.html#structfield.caller_location
275+
[const-location-query]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TyCtxt.html#method.const_caller_location
276+
[location-memory-kind]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/interpret/enum.MemoryKind.html#variant.CallerLocation
277+
[const-frame]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/interpret/struct.Frame.html
278+
[const-stack]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/interpret/struct.InterpCx.html#structfield.stack
279+
[fcx-get]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_codegen_ssa/mir/struct.FunctionCx.html#method.get_caller_location
280+
[frame-instance]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/interpret/struct.Frame.html#structfield.instance

0 commit comments

Comments
 (0)