Commit Graph

191 Commits

Author SHA1 Message Date
Jacob Pratt
87ec0738ab
Span::{before, after}Span::{start, end} 2023-06-20 19:40:25 -04:00
Jacob Pratt
dc76991d2f
Remove LineColumn, Span::start, Span::end 2023-06-20 19:40:24 -04:00
Deadbeef
a49570fd20 fix TODO comments 2023-05-02 10:32:07 +00:00
bors
1151ea6006 Auto merge of #109002 - michaelvanstraten:master, r=petrochenkov
Added byte position range for `proc_macro::Span`

Currently, the [`Debug`](https://doc.rust-lang.org/beta/proc_macro/struct.Span.html#impl-Debug-for-Span) implementation for [`proc_macro::Span`](https://doc.rust-lang.org/beta/proc_macro/struct.Span.html#) calls the debug function implemented in the trait implementation of `server::Span` for the type `Rustc` in the `rustc-expand` crate.

The current implementation, of the referenced function, looks something like this:
```rust
fn debug(&mut self, span: Self::Span) -> String {
    if self.ecx.ecfg.span_debug {
        format!("{:?}", span)
    } else {
        format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
    }
}
```

It returns the byte position of the [`Span`](https://doc.rust-lang.org/beta/proc_macro/struct.Span.html#) as an interpolated string.

Because this is currently the only way to get a spans position in the file, I might lead someone, who is interested in this information, to parsing this interpolated string back into a range of bytes, which I think is a very non-rusty way.

The proposed `position()`, method implemented in this PR, gives the ability to directly get this info.
It returns a [`std::ops::Range`](https://doc.rust-lang.org/std/ops/struct.Range.html#) wrapping the lowest and highest byte of the [`Span`](https://doc.rust-lang.org/beta/proc_macro/struct.Span.html#).

I put it behind the `proc_macro_span` feature flag because many of the other functions that have a similar footprint also are annotated with it, I don't actually know if this is right.

It would be great if somebody could take a look at this, thank you very much in advanced.
2023-04-21 10:47:27 +00:00
KaDiWa
ad2b34d0e3
remove some unneeded imports 2023-04-12 19:27:18 +02:00
Michael van Straten
c67ae04aca Renamed to byte_range and changed Range generics [skip ci] 2023-03-11 12:15:19 +01:00
Michael van Straten
3dbeb69503 added byte position range for proc_macro::Span 2023-03-10 21:19:25 +01:00
Michael van Straten
b8c6d2211e added byte position range for proc_macro::Span 2023-03-10 21:19:25 +01:00
bors
adb4bfd25d Auto merge of #105671 - lukas-code:depreciate-char, r=scottmcm
Use associated items of `char` instead of freestanding items in `core::char`

The associated functions and constants on `char` have been stable since 1.52 and the freestanding items have soft-deprecated since 1.62 (https://github.com/rust-lang/rust/pull/95566). This PR ~~marks them as "deprecated in future", similar to the integer and floating point modules (`core::{i32, f32}` etc)~~ replaces all uses of `core::char::*` with `char::*` to prepare for future deprecation of `core::char::*`.
2023-02-12 11:09:06 +00:00
bors
40fda7b3fe Auto merge of #107318 - matthiaskrgr:rollup-776kd81, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #97373 (impl DispatchFromDyn for Cell and UnsafeCell)
 - #106625 (Remove backwards compat for LLVM 12 coverage format)
 - #106779 (Avoid __cxa_thread_atexit_impl on Emscripten)
 - #106811 (Append .dwp to the binary filename instead of replacing the existing extension.)
 - #106836 (Remove optimistic spinning from `mpsc::SyncSender`)
 - #106946 (implement Hash for proc_macro::LineColumn)
 - #107074 (remove unnecessary check for opaque types)
 - #107287 (Improve fn pointer notes)
 - #107304 (Use `can_eq` to compare types for default assoc type error)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-01-26 09:14:05 +00:00
David Tolnay
25f0147db2
implement Hash for proc_macro::LineColumn 2023-01-16 11:41:19 -08:00
Lukas Markeffsky
76e216f29b Use associated items of char instead of freestanding items in core::char 2023-01-14 11:58:41 +01:00
mejrs
f92000816e Improve proc macro attribute diagnostics 2023-01-12 00:11:11 +01:00
jonathanCogan
db47071df2 Replace libstd, libcore, liballoc in line comments. 2022-12-30 14:00:42 +01:00
jonathanCogan
72067c77bd Replace libstd, libcore, liballoc in docs. 2022-12-30 14:00:40 +01:00
est31
3c809b3c5c Add a "the" to proc_macro documentation 2022-12-12 16:19:18 +01:00
Mark Rousskov
455a7bc685 Bump version placeholders to release 2022-11-06 17:11:02 -05:00
est31
d89fb1dee5 Stabilize proc_macro::Span::source_text
Splits proc_macro::Span::source_text into a new feature gate and stabilizes it.
2022-10-18 17:13:41 +02:00
Nicholas Nethercote
ed6f4813bb A tiny fix for define_client_side.
The return type can only appear once.
2022-10-05 13:10:28 +11:00
jam1garner
527f7887b8
Fix typo in proc_macro Span::eq 2022-09-17 19:15:30 -04:00
Dylan DPC
93177758fc
Rollup merge of #100767 - kadiwa4:escape_ascii, r=jackh726
Remove manual <[u8]>::escape_ascii

`@rustbot` label: +C-cleanup
2022-09-12 15:21:30 +05:30
Nika Layzell
efda49712b proc_macro/bridge: use the cross-thread executor for nested proc-macros
While working on some other changes in the bridge, I noticed that when
running a nested proc-macro (which is currently only possible using
the unstable `TokenStream::expand_expr`), any symbols held by the
proc-macro client would be invalidated, as the same thread would be used
for the nested macro by default, and the interner doesn't handle nested
use.

After discussing with @eddyb, we decided the best approach might be to
force the use of the cross-thread executor for nested invocations, as it
will never re-use thread-local storage, avoiding the issue. This
shouldn't impact performance, as expand_expr is still unstable, and
infrequently used.

This was chosen rather than making the client symbol interner handle
nested invocations, as that would require replacing the internal
interner `Vec` with a `BTreeMap` (as valid symbol id ranges could now be
disjoint), and the symbol interner is known to be fairly perf-sensitive.

This patch adds checks to the execution strategy to use the cross-thread
executor when doing nested invocations. An alternative implementation
strategy could be to track this information in the `ExtCtxt`, however a
thread-local in the `proc_macro` crate was chosen to add an assertion so
that `rust-analyzer` is aware of the issue if it implements
`expand_expr` in the future.

r? @eddyb
2022-09-04 14:06:26 -04:00
KaDiWa
a297631bdc
use <[u8]>::escape_ascii instead of core::ascii::escape_default 2022-08-19 19:00:37 +02:00
Nika Layzell
1c7c792dda proc_macro/bridge: send diagnostics over the bridge as a struct
This removes some RPC when creating and emitting diagnostics, and
simplifies the bridge slightly.

After this change, there are no remaining methods which take advantage
of the support for `&mut` references to objects in the store as
arguments, meaning that support for them could technically be removed if
we wanted. The only remaining uses of immutable references into the
store are `TokenStream` and `SourceFile`.
2022-08-06 15:49:43 -04:00
Nika Layzell
6d1650fe45 proc_macro: use crossbeam channels for the proc_macro cross-thread bridge
This is done by having the crossbeam dependency inserted into the
proc_macro server code from the server side, to avoid adding a
dependency to proc_macro.

In addition, this introduces a -Z command-line option which will switch
rustc to run proc-macros using this cross-thread executor. With the
changes to the bridge in #98186, #98187, #98188 and #98189, the
performance of the executor should be much closer to same-thread
execution.

In local testing, the crossbeam executor was substantially more
performant than either of the two existing CrossThread strategies, so
they have been removed to keep things simple.
2022-07-29 17:38:12 -04:00
David Tolnay
63e74aba81
Expose size_hint() for TokenStream's iterator 2022-07-24 20:36:22 -07:00
Matthias Krüger
a5a681100c
Rollup merge of #99516 - m-ou-se:proc-macro-tracked-tracking-issue, r=Mark-Simulacrum
Use new tracking issue for proc_macro::tracked_*.
2022-07-20 18:58:22 +02:00
Mara Bos
12ff7a0d66 Use new tracking issue for proc_macro::tracked_*. 2022-07-20 17:35:06 +02:00
Nika Layzell
c4acac6443 proc_macro: Move subspan to be a method on Span in the bridge
This method is still only used for Literal::subspan, however the
implementation only depends on the Span component, so it is simpler and
more efficient for now to pass down only the information that is needed.
In the future, if more information about the Literal is required in the
implementation (e.g. to validate that spans line up as expected with
source text), that extra information can be added back with extra
arguments.
2022-07-18 13:06:51 -04:00
Nika Layzell
b34c79f8f1 proc_macro: stop using a remote object handle for Literal
This builds on the symbol infrastructure built for `Ident` to replicate
the `LitKind` and `Lit` structures in rustc within the `proc_macro`
client, allowing literals to be fully created and interacted with from
the client thread. Only parsing and subspan operations still require
sync RPC.
2022-07-18 13:06:51 -04:00
Nika Layzell
491fccfbe3 proc_macro: stop using a remote object handle for Ident
Doing this for all unicode identifiers would require a dependency on
`unicode-normalization` and `rustc_lexer`, which is currently not
possible for `proc_macro` due to it being built concurrently with `std`
and `core`. Instead, ASCII identifiers are validated locally, and an RPC
message is used to validate unicode identifiers when needed.

String values are interned on the both the server and client when
deserializing, to avoid unnecessary copies and keep Ident cheap to copy and
move. This appears to be important for performance.

The client-side interner is based roughly on the one from rustc_span, and uses
an arena inspired by rustc_arena.

RPC messages passing symbols always include the full value. This could
potentially be optimized in the future if it is revealed to be a
performance bottleneck.

Despite now having a relevant implementaion of Display for Ident, ToString is
still specialized, as it is a hot-path for this object.

The symbol infrastructure will also be used for literals in the next
part.
2022-07-18 12:59:14 -04:00
Nika Layzell
e0dce6ec8d proc_macro: Specialize Punct::to_string
This was removed in a previous part, however it should be specialized for
to_string performance and consistency.
2022-07-18 12:59:14 -04:00
Nika Layzell
17e96879d8 proc_macro: use fxhash within the proc_macro crate
Unfortunately, as it is difficult to depend on crates from within proc_macro,
this is done by vendoring a copy of the hasher as a module rather than
depending on the rustc_hash crate.

This probably doesn't have a substantial impact up-front, however will be more
relevant once symbols are interned within the proc_macro client.
2022-07-18 12:59:14 -04:00
Nika Layzell
64a7d57046 review changes
longer names for RPC generics and reduced dependency on macros in the server.
2022-06-28 09:54:29 -04:00
Nika Layzell
f28dfdf1c7 proc_macro: stop using a remote object handle for Group
This greatly reduces round-trips to fetch relevant extra information about the
token in proc macro code, and avoids RPC messages to create Group tokens.
2022-06-26 22:20:33 -04:00
Nika Layzell
72bfe618fa proc_macro: stop using a remote object handle for Punct
This greatly reduces round-trips to fetch relevant extra information about the
token in proc macro code, and avoids RPC messages to create Punct tokens.
2022-06-26 22:20:33 -04:00
Nika Layzell
e32ee19b3a proc_macro: Rename ExpnContext to ExpnGlobals, and unify method on Server trait 2022-06-26 12:48:33 -04:00
Nika Layzell
2456ff8928 proc_macro: remove Context trait, and put span methods directly on Server 2022-06-25 12:26:21 -04:00
Nika Layzell
55f052d9c9 proc_macro: cache static spans in client's thread-local state
This greatly improves the performance of the very frequently called
`call_site()` macro when running in a cross-thread configuration.
2022-06-25 10:28:11 -04:00
bors
2b646bd533 Auto merge of #98224 - eddyb:proc-macro-spurious-repr, r=bjorn3
proc_macro/bridge: remove `#[repr(C)]` from non-ABI-relevant types.

Not sure how this happened, maybe some of these were passed through the bridge a long time ago?

r? `@bjorn3`
2022-06-19 17:32:12 +00:00
Eduard-Mihai Burtescu
83545d3216 proc_macro/bridge: remove #[repr(C)] from non-ABI-relevant types. 2022-06-18 09:14:25 +00:00
Nika Layzell
df925fda9c review fixups 2022-06-17 22:10:07 -04:00
Nika Layzell
af51424008 Move empty final TokenStream handling to server side of bridge 2022-06-17 11:07:42 -04:00
Nika Layzell
4d45af9e73 Try to reduce codegen complexity of TokenStream's FromIterator and Extend impls
This is an experimental patch to try to reduce the codegen complexity of
TokenStream's FromIterator and Extend implementations for downstream
crates, by moving the core logic into a helper type. This might help
improve build performance of crates which depend on proc_macro as
iterators are used less, and the compiler may take less time to do
things like attempt specializations or other iterator optimizations.

The change intentionally sacrifices some optimization opportunities,
such as using the specializations for collecting iterators derived from
Vec::into_iter() into Vec.

This is one of the simpler potential approaches to reducing the amount
of code generated in crates depending on proc_macro, so it seems worth
trying before other more-involved changes.
2022-06-17 00:42:26 -04:00
Nika Layzell
0a049fd30d proc_macro: reduce the number of messages required to create, extend, and iterate TokenStreams
This significantly reduces the cost of common interactions with TokenStream
when running with the CrossThread execution strategy, by reducing the number of
RPC calls required.
2022-06-17 00:42:26 -04:00
Nika Layzell
2b17219468 proc_macro: use macros to simplify aggregate Mark/Unmark definitions 2022-06-16 23:16:30 -04:00
Nika Layzell
1793ee0658 proc_macro: support encoding/decoding Vec<T> 2022-06-14 22:12:46 -04:00
Nika Layzell
7678e6ad85 proc_macro: support encoding/decoding structs with type parameters 2022-06-14 22:12:46 -04:00
Eduard-Mihai Burtescu
07c7ba7205 proc_macro: bypass RandomState to remove ASLR-like effects. 2022-06-13 07:59:44 +00:00
bors
bb55bd449e Auto merge of #95565 - jackh726:remove-borrowck-mode, r=nikomatsakis
Remove migrate borrowck mode

Closes #58781
Closes #43234

# Stabilization proposal

This PR proposes the stabilization of `#![feature(nll)]` and the removal of `-Z borrowck`. Current borrow checking behavior of item bodies is currently done by first infering regions *lexically* and reporting any errors during HIR type checking. If there *are* any errors, then MIR borrowck (NLL) never occurs. If there *aren't* any errors, then MIR borrowck happens and any errors there would be reported. This PR removes the lexical region check of item bodies entirely and only uses MIR borrowck. Because MIR borrowck could never *not* be run for a compiled program, this should not break any programs. It does, however, change diagnostics significantly and allows a slightly larger set of programs to compile.

Tracking issue: #43234
RFC: https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md
Version: 1.63 (2022-06-30 => beta, 2022-08-11 => stable).

## Motivation

Over time, the Rust borrow checker has become "smarter" and thus allowed more programs to compile. There have been three different implementations: AST borrowck, MIR borrowck, and polonius (well, in progress). Additionally, there is the "lexical region resolver", which (roughly) solves the constraints generated through HIR typeck. It is not a full borrow checker, but does emit some errors.

The AST borrowck was the original implementation of the borrow checker and was part of the initially stabilized Rust 1.0. In mid 2017, work began to implement the current MIR borrow checker and that effort ompleted by the end of 2017, for the most part. During 2018, efforts were made to migrate away from the AST borrow checker to the MIR borrow checker - eventually culminating into "migrate" mode - where HIR typeck with lexical region resolving following by MIR borrow checking - being active by default in the 2018 edition.

In early 2019, migrate mode was turned on by default in the 2015 edition as well, but with MIR borrowck errors emitted as warnings. By late 2019, these warnings were upgraded to full errors. This was followed by the complete removal of the AST borrow checker.

In the period since, various errors emitted by the MIR borrow checker have been improved to the point that they are mostly the same or better than those emitted by the lexical region resolver.

While there do remain some degradations in errors (tracked under the [NLL-diagnostics tag](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3ANLL-diagnostics), those are sufficiently small and rare enough that increased flexibility of MIR borrow check-only is now a worthwhile tradeoff.

## What is stabilized

As said previously, this does not fundamentally change the landscape of accepted programs. However, there are a [few](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3ANLL-fixed-by-NLL) cases where programs can compile under `feature(nll)`, but not otherwise.

There are two notable patterns that are "fixed" by this stabilization. First, the `scoped_threads` feature, which is a continutation of a pre-1.0 API, can sometimes emit a [weird lifetime error](https://github.com/rust-lang/rust/issues/95527) without NLL. Second, actually seen in the standard library. In the `Extend` impl for `HashMap`, there is an implied bound of `K: 'a` that is available with NLL on but not without - this is utilized in the impl.

As mentioned before, there are a large number of diagnostic differences. Most of them are better, but some are worse. None are serious or happen often enough to need to block this PR. The biggest change is the loss of error code for a number of lifetime errors in favor of more general "lifetime may not live long enough" error. While this may *seem* bad, the former error codes were just attempts to somewhat-arbitrarily bin together lifetime errors of the same type; however, on paper, they end up being roughly the same with roughly the same kinds of solutions.

## What isn't stabilized

This PR does not completely remove the lexical region resolver. In the future, it may be possible to remove that (while still keeping HIR typeck) or to remove it together with HIR typeck.

## Tests

Many test outputs get updated by this PR. However, there are number of tests specifically geared towards NLL under `src/test/ui/nll`

## History

* On 2017-07-14, [tracking issue opened](https://github.com/rust-lang/rust/issues/43234)
* On 2017-07-20, [initial empty MIR pass added](https://github.com/rust-lang/rust/pull/43271)
* On 2017-08-29, [RFC opened](https://github.com/rust-lang/rfcs/pull/2094)
* On 2017-11-16, [Integrate MIR type-checker with NLL](https://github.com/rust-lang/rust/pull/45825)
* On 2017-12-20, [NLL feature complete](https://github.com/rust-lang/rust/pull/46862)
* On 2018-07-07, [Don't run AST borrowck on mir mode](https://github.com/rust-lang/rust/pull/52083)
* On 2018-07-27, [Add migrate mode](https://github.com/rust-lang/rust/pull/52681)
* On 2019-04-22, [Enable migrate mode on 2015 edition](https://github.com/rust-lang/rust/pull/59114)
* On 2019-08-26, [Don't downgrade errors on 2015 edition](https://github.com/rust-lang/rust/pull/64221)
* On 2019-08-27, [Remove AST borrowck](https://github.com/rust-lang/rust/pull/64790)
2022-06-07 05:04:14 +00:00
bors
cb0584f86b Auto merge of #97604 - nnethercote:inline-bridge-Buffer-methods, r=eddyb
Inline `bridge::Buffer` methods.

This fixes a performance regression caused by making `Buffer`
non-generic in #97004.

r? `@eddyb`
2022-06-04 04:51:26 +00:00
Jack Huey
410dcc9674 Fully stabilize NLL 2022-06-03 17:16:41 -04:00
Nicholas Nethercote
77e1069a5d Revert #96682.
The change was "Show invisible delimiters (within comments) when pretty
printing". It's useful to show these delimiters, but is a breaking
change for some proc macros.

Fixes #97608.
2022-06-02 11:22:16 +10:00
Nicholas Nethercote
dee353da1d Inline bridge::Buffer methods.
This fixes a performance regression caused by making `Buffer`
non-generic in #97004.
2022-06-01 09:21:35 +10:00
Eduard-Mihai Burtescu
78a83b0d5f proc_macro: don't pass a client-side function pointer through the server. 2022-05-27 19:29:21 +00:00
Nicholas Nethercote
41c10dde95 Cut down associated_item.
The part of it dealing with types obfuscates and makes the code less
concise. This commit removes that part.
2022-05-27 16:02:24 +10:00
Nicholas Nethercote
e6fa19a3ce Remove unnecessary blank line. 2022-05-27 16:02:24 +10:00
Nicholas Nethercote
f5c9c1215c Rename b as buf in several places.
Because it's easy to confuse with `bridge`.
2022-05-27 15:58:35 +10:00
Nicholas Nethercote
c2c505737f Add some comments about _marker fields.
There is some non-obvious information required to understand them.
2022-05-27 15:58:35 +10:00
Nicholas Nethercote
9a785e0aa5 Clarify a comment.
`reverse_encode` isn't necessary to please the borrow checker, it's to
match the ordering done by `reverse_decode`.
2022-05-27 15:58:35 +10:00
Nicholas Nethercote
2ece157e17 Make Buffer<T> non-generic.
`u8` is the only type that makes sense for `T`, as demonstrated by the
fact that several impls and functions are hardwired to `Buffer<u8>`.
2022-05-27 15:58:35 +10:00
Nicholas Nethercote
e02789c9f8 Improve formatting in associated_item! definition. 2022-05-27 15:58:35 +10:00
Nicholas Nethercote
a61a85eb24 Add some comments. 2022-05-27 15:58:35 +10:00
Nicholas Nethercote
2469ed0142 Fix a typo in a comment. 2022-05-27 15:58:35 +10:00
Nicholas Nethercote
fd01fbc058 Remove some unnecessary rustc_allow_const_fn_unstable attributes. 2022-05-13 16:01:18 +10:00
Nicholas Nethercote
5022d764cf Show invisible delimeters (within comments) when pretty printing. 2022-05-04 10:06:06 +10:00
Vadim Petrochenkov
2733ec1be3 rustc_ast: Harmonize delimiter naming with proc_macro::Delimiter 2022-04-28 10:04:29 +03:00
Dylan DPC
93db30aa7f
Rollup merge of #96149 - est31:remove_unused_macro_matchers, r=petrochenkov
Remove unused macro rules

Removes rules of internal macros that weren't triggered.
2022-04-26 01:21:20 +02:00
Vadim Petrochenkov
f5ca02c334 proc_macro: Add a workaround for rustdoc 2022-04-19 22:49:27 +03:00
est31
3c1e1661e7 Remove unused macro rules 2022-04-18 23:28:06 +02:00
Dylan DPC
e232cb42e6
Rollup merge of #95308 - bjorn3:more_stable_proc_macro, r=Mark-Simulacrum
Reduce the amount of unstable features used in libproc_macro

This makes it easier to adapt the source for stable when copying it into rust-analyzer to load rustc compiled proc macros.
2022-04-09 12:52:02 +02:00
bjorn3
7eda975b06 Use PhantomData directly in Bridge 2022-04-06 18:53:19 +02:00
Pietro Albini
181d28bb61
trivial cfg(bootstrap) changes 2022-04-05 23:18:40 +02:00
bjorn3
6eab9802c9 Add note about feature gates 2022-03-25 19:04:30 +01:00
bjorn3
ec7efa75f9 Avoid negative impls in the bridge 2022-03-25 17:24:27 +01:00
bjorn3
4b67506baa Remove usage of extern_types feature gate 2022-03-25 17:24:27 +01:00
bjorn3
681ea25b20 Remove usage of panic_update_hook feature gate 2022-03-25 17:24:27 +01:00
bjorn3
e85722946a Remove unused auto_traits feature gate 2022-03-25 17:24:27 +01:00
T-O-R-U-S
72a25d05bf Use implicit capture syntax in format_args
This updates the standard library's documentation to use the new syntax. The
documentation is worthwhile to update as it should be more idiomatic
(particularly for features like this, which are nice for users to get acquainted
with). The general codebase is likely more hassle than benefit to update: it'll
hurt git blame, and generally updates can be done by folks updating the code if
(and when) that makes things more readable with the new format.

A few places in the compiler and library code are updated (mostly just due to
already having been done when this commit was first authored).
2022-03-10 10:23:40 -05:00
Eric Holk
7723506d13 Stabilize const_fn_fn_ptr_basics and const_fn_trait_bound 2022-03-07 08:47:15 -08:00
bors
a0984b4e4c Auto merge of #92598 - Badel2:panic-update-hook, r=yaahc
Implement `panic::update_hook`

Add a new function `panic::update_hook` to allow creating panic hooks that forward the call to the previously set panic hook, without race conditions. It works by taking a closure that transforms the old panic hook into a new one, while ensuring that during the execution of the closure no other thread can modify the panic hook. This is a small function so I hope it can be discussed here without a formal RFC, however if you prefer I can write one.

Consider the following example:

```rust
let prev = panic::take_hook();
panic::set_hook(Box::new(move |info| {
    println!("panic handler A");
    prev(info);
}));
```

This is a common pattern in libraries that need to do something in case of panic: log panic to a file, record code coverage, send panic message to a monitoring service, print custom message with link to github to open a new issue, etc. However it is impossible to avoid race conditions with the current API, because two threads can execute in this order:

* Thread A calls `panic::take_hook()`
* Thread B calls `panic::take_hook()`
* Thread A calls `panic::set_hook()`
* Thread B calls `panic::set_hook()`

And the result is that the original panic hook has been lost, as well as the panic hook set by thread A. The resulting panic hook will be the one set by thread B, which forwards to the default panic hook. This is not considered a big issue because the panic handler setup is usually run during initialization code, probably before spawning any other threads.

Using the new `panic::update_hook` function, this race condition is impossible, and the result will be either `A, B, original` or `B, A, original`.

```rust
panic::update_hook(|prev| {
    Box::new(move |info| {
        println!("panic handler A");
        prev(info);
    })
});
```

I found one real world use case here: 988cf403e7/src/detection.rs (L32) the workaround is to detect the race condition and panic in that case.

The pattern of `take_hook` + `set_hook` is very common, you can see some examples in this pull request, so I think it's natural to have a function that combines them both. Also using `update_hook` instead of `take_hook` + `set_hook` reduces the number of calls to `HOOK_LOCK.write()` from 2 to 1, but I don't expect this to make any difference in performance.

### Unresolved questions:

* `panic::update_hook` takes a closure, if that closure panics the error message is "panicked while processing panic" which is not nice. This is a consequence of holding the `HOOK_LOCK` while executing the closure. Could be avoided using `catch_unwind`?

* Reimplement `panic::set_hook` as `panic::update_hook(|_prev| hook)`?
2022-01-16 02:18:42 +00:00
Badel2
8ef3ce866e Change panic::update_hook to simplify usage
And to remove possibility of panics while changing the panic handler,
because that resulted in a double panic.
2022-01-08 00:57:59 +01:00
Badel2
8bdf5c3de6 Implement panic::update_hook 2022-01-07 17:28:20 +01:00
Deadbeef
06a1c14d52
Switch all libraries to the 2021 edition 2021-12-23 19:03:47 +08:00
Anuvrat
90aa8fb3d5 made compiler happy 2021-12-14 16:42:16 +05:30
Nika Layzell
3e4d3d2a29 proc_macro: Add an expand_expr method to TokenStream
This feature is aimed at giving proc macros access to powers similar to
those used by builtin macros such as `format_args!` or `concat!`. These
macros are able to accept macros in place of string literal parameters,
such as the format string, as they perform recursive macro expansion
while being expanded.

This can be especially useful in many cases thanks to helper macros like
`concat!`, `stringify!` and `include_str!` which are often used to
construct string literals at compile-time in user code.

For now, this method only allows expanding macros which produce
literals, although more expresisons will be supported before the method
is stabilized.
2021-11-12 15:41:40 -05:00
David Tolnay
c5025f0e4e
Append .0 to unsuffixed float if it would otherwise become int token 2021-10-25 20:30:47 -07:00
bjorn3
09dd213cd2 Stabilize proc_macro::is_available 2021-10-10 14:09:54 +02:00
Manish Goregaokar
000dbd27f1
Rollup merge of #86165 - m-ou-se:proc-macro-span-shrink, r=dtolnay
Add proc_macro::Span::{before, after}.

This adds `proc_macro::Span::before()` and `proc_macro::Span::after()` to get a zero width span at the start or end of the span.

These are equivalent to rustc's `Span::shrink_to_lo()` and `Span::shrink_to_hi()` but with a less cryptic name. They are useful when generating diagnostlics like "missing \<thing\> after \<thing\>".

E.g.

```rust
syn::Error::new(ident.span().after(), "missing `:` after field name").into_compile_error()
```
2021-09-10 08:23:14 -07:00
Frank Steffahn
bf88b113ea Fix typos “a”→“an” 2021-08-22 15:35:11 +02:00
Klim Tsoutsman
75e80358d2
Change proc_macro::Diagnostics docs
Add links

Fit 100-character limit
2021-08-07 23:54:34 +10:00
bors
71ff9b41e9 Auto merge of #87712 - est31:line-column-1-based, r=petrochenkov
Proc macro spans: make columns 1 based

This makes proc macro spans consistent with the `column!()` macro as well as `std::panic::Location`, as both are 1-based.

https://github.com/rust-lang/rust/issues/54725#issuecomment-497246753
2021-08-04 04:27:35 +00:00
David Tolnay
3744dc8687
Remove space after negative sign in Literal to_string 2021-08-03 10:40:52 -07:00
est31
7d20789c02 Make the UTF-8 statement more explicit and explicitly test for it 2021-08-03 03:33:05 +02:00
est31
50fcd454c7 Make columns 1 based 2021-08-03 03:10:10 +02:00
bors
b53a93db2d Auto merge of #87535 - lf-:authors, r=Mark-Simulacrum
rfc3052 followup: Remove authors field from Cargo manifests

Since RFC 3052 soft deprecated the authors field, hiding it from
crates.io, docs.rs, and making Cargo not add it by default, and it is
not generally up to date/useful information for contributors, we may as well
remove it from crates in this repo.
2021-08-02 05:49:17 +00:00
Jade
3cf820e17d rfc3052: Remove authors field from Cargo manifests
Since RFC 3052 soft deprecated the authors field anyway, hiding it from
crates.io, docs.rs, and making Cargo not add it by default, and it is
not generally up to date/useful information, we should remove it from
crates in this repo.
2021-07-29 14:56:05 -07:00
Ali Malik
e43254aad1 Fix may not to appropriate might not or must not 2021-07-29 01:15:20 -04:00
Mara Bos
f9be6cd898 Add tracking issue number to proc_macro_span_shrink. 2021-07-28 16:34:45 +02:00
Yuki Okushi
45470a3bcd
Rollup merge of #84029 - drahnr:master, r=petrochenkov
add `track_path::path` fn for usage in `proc_macro`s

Adds a way to declare a dependency on external files without including them, to either re-trigger the build of a file as well as covering the use case of including dependencies within the `rustc` invocation, such that tools like `sccache`/`cachepot` are able to handle references to external files which are not included.

Ref #73921
2021-07-03 03:15:07 +09:00