about summary refs log tree commit diff
path: root/src/test/ui/proc-macro
AgeCommit message (Collapse)AuthorLines
2022-06-02Revert #96682.Nicholas Nethercote-86/+59
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-05-27proc_macro: don't pass a client-side function pointer through the server.Eduard-Mihai Burtescu-9/+12
2022-05-04Show invisible delimeters (within comments) when pretty printing.Nicholas Nethercote-59/+86
2022-04-28rustc_ast: Harmonize delimiter naming with `proc_macro::Delimiter`Vadim Petrochenkov-1/+1
2022-04-16Implementation for 65853Jack Huey-0/+5
This attempts to bring better error messages to invalid method calls, by applying some heuristics to identify common mistakes. The algorithm is inspired by Levenshtein distance and longest common sub-sequence. In essence, we treat the types of the function, and the types of the arguments you provided as two "words" and compute the edits to get from one to the other. We then modify that algorithm to detect 4 cases: - A function input is missing - An extra argument was provided - The type of an argument is straight up invalid - Two arguments have been swapped - A subset of the arguments have been shuffled (We detect the last two as separate cases so that we can detect two swaps, instead of 4 parameters permuted.) It helps to understand this argument by paying special attention to terminology: "inputs" refers to the inputs being *expected* by the function, and "arguments" refers to what has been provided at the call site. The basic sketch of the algorithm is as follows: - Construct a boolean grid, with a row for each argument, and a column for each input. The cell [i, j] is true if the i'th argument could satisfy the j'th input. - If we find an argument that could satisfy no inputs, provided for an input that can't be satisfied by any other argument, we consider this an "invalid type". - Extra arguments are those that can't satisfy any input, provided for an input that *could* be satisfied by another argument. - Missing inputs are inputs that can't be satisfied by any argument, where the provided argument could satisfy another input - Swapped / Permuted arguments are identified with a cycle detection algorithm. As each issue is found, we remove the relevant inputs / arguments and check for more issues. If we find no issues, we match up any "valid" arguments, and start again. Note that there's a lot of extra complexity: - We try to stay efficient on the happy path, only computing the diagonal until we find a problem, and then filling in the rest of the matrix. - Closure arguments are wrapped in a tuple and need to be unwrapped - We need to resolve closure types after the rest, to allow the most specific type constraints - We need to handle imported C functions that might be variadic in their inputs. I tried to document a lot of this in comments in the code and keep the naming clear.
2022-04-04Rollup merge of #95343 - dtolnay:literals, r=petrochenkovDylan DPC-2/+13
Reduce unnecessary escaping in proc_macro::Literal::character/string I noticed that https://doc.rust-lang.org/proc_macro/struct.Literal.html#method.character is producing unreadable literals that make macro-expanded code unnecessarily hard to read. Since the proc macro server was using `escape_unicode()`, every char is escaped using `\u{…}` regardless of whether there is any need to do so. For example `Literal::character('=')` would previously produce `'\u{3d}'` which unnecessarily obscures the meaning when reading the macro-expanded code. I've changed Literal::string also in this PR because `str`'s `Debug` impl is also smarter than just calling `escape_debug` on every char. For example `Literal::string("ferris's")` would previously produce `"ferris\'s"` but will now produce `"ferris's"`.
2022-04-02ast_lowering: Stop wrapping `ident` matchers into groupsVadim Petrochenkov-18/+6
The lowered forms goes to metadata, for example during encoding of macro definitions
2022-03-27Rollup merge of #91981 - estebank:tweakaroo, r=lcnrDylan DPC-4/+4
Recover suggestions and useful information lost in previous PR Follow up to #91898.
2022-03-27Eagerly replace `{integer}`/`{float}` with `i32`/`f64` for suggestionEsteban Kuber-4/+4
2022-03-26Use str and char's Debug impl to format literalsDavid Tolnay-8/+8
2022-03-26Add test for proc_macro Literal string and character constructorsDavid Tolnay-0/+11
2022-03-26proc-macro: Stop wrapping `ident` matchers into groupsVadim Petrochenkov-414/+21
2022-03-20Filter OnceNote in diagnostic infra.Camille GILLOT-0/+15
2022-03-11run rust-fix in amputate-span.rs. (Thanks to ekuber for pushing me to do this.)Felix S. Klock II-2/+73
2022-03-03Adjusted diagnostic output so that if there is no `use` in a item sequence,Felix S. Klock II-0/+102
then we just suggest the first legal position where you could inject a use. To do this, I added `inject_use_span` field to `ModSpans`, and populate it in parser (it is the span of the first token found after inner attributes, if any). Then I rewrote the use-suggestion code to utilize it, and threw out some stuff that is now unnecessary with this in place. (I think the result is easier to understand.) Then I added a test of issue 87613.
2022-02-07Auto merge of #93179 - Urgau:unreachable-2021, r=m-ou-se,oli-obkbors-3/+1
Fix invalid special casing of the unreachable! macro This pull-request fix an invalid special casing of the `unreachable!` macro in the same way the `panic!` macro was solved, by adding two new internal only macros `unreachable_2015` and `unreachable_2021` edition dependent and turn `unreachable!` into a built-in macro that do dispatching. This logic is stolen from the `panic!` macro. ~~This pull-request also adds an internal feature `format_args_capture_non_literal` that allows capturing arguments from formatted string that expanded from macros. The original RFC #2795 mentioned this as a future possibility. This feature is [required](https://github.com/rust-lang/rust/issues/92137#issuecomment-1018630522) because of concatenation that needs to be done inside the macro:~~ ```rust $crate::concat!("internal error: entered unreachable code: ", $fmt) ``` **In summary** the new behavior for the `unreachable!` macro with this pr is: Edition 2021: ```rust let x = 5; unreachable!("x is {x}"); ``` ``` internal error: entered unreachable code: x is 5 ``` Edition <= 2018: ```rust let x = 5; unreachable!("x is {x}"); ``` ``` internal error: entered unreachable code: x is {x} ``` Also note that the change in this PR are **insta-stable** and **breaking changes** but this a considered as being a [bug](https://github.com/rust-lang/rust/issues/92137#issuecomment-998441613). If someone could start a perf run and then a crater run this would be appreciated. Fixes https://github.com/rust-lang/rust/issues/92137
2022-01-31Bless all pretty printer tests and ui testsDavid Tolnay-2/+1
2022-01-31Fix invalid special casing of the unreachable! macroLoïc BRANSTETT-3/+1
2022-01-30Bless all pretty printer tests and ui testsDavid Tolnay-56/+54
2022-01-23Remove deduplication of early lintsAaron Hill-5/+87
We already have a general mechanism for deduplicating reported lints, so there's no need to have an additional one for early lints specifically. This allows us to remove some `PartialEq` impls.
2022-01-10expand: Pick `cfg`s and `cfg_attrs` one by one, like other attributesVadim Petrochenkov-15/+1
2021-12-09Add needs-unwind to tests that depend on panickingDavid Koloski-0/+1
This directive isn't automatically set by compiletest or x.py, but can be turned on manually for targets that require it.
2021-12-08Rollup merge of #91245 - cameron1024:suggest-i32-u32-char-cast, r=nagisaMatthias Krüger-0/+5
suggest casting between i/u32 and char As discussed in https://github.com/rust-lang/rust/issues/91063 , this adds a suggestion for converting between i32/u32 <-> char with `as`, and a short explanation for why this is safe
2021-12-05Auto merge of #91555 - matthiaskrgr:rollup-pq0iaq7, r=matthiaskrgrbors-35/+35
Rollup of 4 pull requests Successful merges: - #90529 (Skip reborrows in AbstractConstBuilder) - #91437 (Pretty print empty blocks as {}) - #91450 (Don't suggest types whose inner type is erroneous) - #91535 (Stabilize `-Z emit-future-incompat` as `--json future-incompat`) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2021-12-05Rollup merge of #91437 - dtolnay:emptybrace, r=nagisaMatthias Krüger-35/+35
Pretty print empty blocks as {} **Example:** ```rust macro_rules! p { ($e:expr) => { println!("{}", stringify!($e)); }; ($i:item) => { println!("{}", stringify!($i)); }; } fn main() { p!(if true {}); p!(struct S {}); } ``` **Before:** ```console if true { } struct S { } ``` **After:** ```console if true {} struct S {} ``` This affects [`dbg!`](https://doc.rust-lang.org/std/macro.dbg.html), as well as ecosystem uses of stringify such as in [`anyhow::ensure!`](https://docs.rs/anyhow/1/anyhow/macro.ensure.html). Printing a `{ }` in today's heavily rustfmt'd world comes out looking jarring/sloppy.
2021-12-04Use IntoIterator for array impl everywhere.Mara Bos-1/+2
2021-12-01Pretty print empty blocks as {}David Tolnay-35/+35
2021-11-28suggest cast char -> intcameron-0/+5
2021-11-28expand: Turn `ast::Crate` into a first class expansion targetVadim Petrochenkov-10/+21
And stop creating a fake `mod` item for the crate root when expanding a crate.
2021-11-14Move some tests to more reasonable directoriesCaio-0/+84
2021-11-13Auto merge of #87264 - mystor:expand_literal, r=petrochenkovbors-0/+257
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 expressions will be supported before the method is stabilized. In earlier versions of this PR, this method exclusively returned `Literal`, and spans on returned literals were stripped of expansion context before being returned to be as conservative as possible about permission leakage. The method's naming has been generalized to eventually support arbitrary expressions, and the context stripping has been removed (https://github.com/rust-lang/rust/pull/87264#discussion_r674863279), which should allow for more general APIs like "format_args_implicits" (https://github.com/rust-lang/rust/issues/67984) to be supported as well. ## API Surface ```rust impl TokenStream { pub fn expand_expr(&self) -> Result<TokenStream, ExpandError>; } #[non_exhaustive] pub struct ExpandError; impl Debug for ExpandError { ... } impl Display for ExpandError { ... } impl Error for ExpandError {} impl !Send for ExpandError {} impl !Sync for ExpandError {} ```
2021-11-12proc_macro: Add an expand_expr method to TokenStreamNika Layzell-0/+257
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-11Shorten Span of unused macro lintsMarcel Hellwig-1/+1
The span has been recuded to the actual ident, instead of linting the *whole* macro.
2021-11-06Auto merge of #90297 - dtolnay:dotzero, r=petrochenkovbors-0/+10
Append .0 to unsuffixed float if it would otherwise become int token Previously the unsuffixed f32/f64 constructors of `proc_macro::Literal` would create literal tokens that are definitely not a float: ```rust Literal::f32_unsuffixed(10.0) // 10 Literal::f32_suffixed(10.0) // 10f32 Literal::f64_unsuffixed(10.0) // 10 Literal::f64_suffixed(10.0) // 10f64 ``` Notice that the `10` are actually integer tokens if you were to reparse them, not float tokens. This diff updates `Literal::f32_unsuffixed` and `Literal::f64_unsuffixed` to produce tokens that unambiguously parse as a float. This matches longstanding behavior of the proc-macro2 crate's implementation of these APIs dating back at least 3.5 years, so it's likely an unobjectionable behavior. ```rust Literal::f32_unsuffixed(10.0) // 10.0 Literal::f32_suffixed(10.0) // 10f32 Literal::f64_unsuffixed(10.0) // 10.0 Literal::f64_suffixed(10.0) // 10f64 ``` Fixes https://github.com/dtolnay/syn/issues/1085.
2021-11-05Add test to confirm fnn_unsuffixed does not emit exponent notationDavid Tolnay-0/+6
2021-10-30Rollup merge of #90202 - matthewjasper:xcrate-hygiene, r=petrochenkovGuillaume Gomez-0/+4
Improve and test cross-crate hygiene - Decode the parent expansion for traits and enums in `rustc_resolve`, this was already being used for resolution in typeck - Avoid suggesting importing names with def-site hygiene, since it's often not useful - Add more tests r? `@petrochenkov`
2021-10-25Append .0 to unsuffixed float if it would otherwise become int tokenDavid Tolnay-0/+4
2021-10-25Edit error messages for rustc_resolve::AmbiguityKind variantspierwill-15/+29
Emit description of the ambiguity as a note. Co-authored-by: Noah Lev <camelidcamel@gmail.com> Co-authored-by: Vadim Petrochenkov <vadim.petrochenkov@gmail.com>
2021-10-21Handle cross-crate module `ExpnId`s consistentlyMatthew Jasper-0/+4
- Always use the ExpnId serialized to `tables` - Use the Id for traits and enums from other crates in resolution.
2021-10-18Make all proc-macro back-compat lints deny-by-defaultAaron Hill-86/+84
The affected crates have had plenty of time to update. By keeping these as lints rather than making them hard errors, we ensure that downstream crates will still be able to compile, even if they transitive depend on broken versions of the affected crates. This should hopefully discourage anyone from writing any new code which relies on the backwards-compatibility behavior.
2021-10-15Bless testsCameron Steffen-75/+75
2021-10-10Stabilize proc_macro::is_availablebjorn3-3/+0
2021-10-04Make `proc_macro_derive_resolution_fallback` a future-breakage lintAaron Hill-0/+72
When `cargo report future-incompatibilities` is stabilized (see #71249), this will cause dependencies that trigger this lint to be included in the report.
2021-10-02resolve: Cache module loading for all foreign modulesVadim Petrochenkov-5/+11
It was previously cached for modules loaded from `fn get_module`, but not for modules loaded from `fn build_reduced_graph_for_external_crate_res`. This also makes all foreign modules use their real parent, span and expansion instead of possibly a parent/span/expansion of their reexport. An ICE happening on attempt to decode expansions for foreign enums and traits is avoided. Also local enums and traits are now added to the module map.
2021-09-24Stabilize `feature(macro_attributes_in_derive_output)`Vadim Petrochenkov-107/+38
2021-09-24builtin_macros: Make #[derive(A, B, ...)] cfg-eval its input only for `A, B, ↵Vadim Petrochenkov-2/+46
...`
2021-09-13Auto merge of #87915 - estebank:fancy-spans, r=oli-obkbors-1/+1
Use smaller spans for some structured suggestions Use more accurate suggestion spans for * argument parse error * fully qualified path * missing code block type * numeric casts
2021-09-05Rollup merge of #88257 - estebank:invalid-attr-error, r=oli-obkMara Bos-3/+22
Provide more context on incorrect inner attribute Suggest changing an inner attribute into an outer attribute if followed by an item.
2021-09-02Provide more context on incorrect inner attributeEsteban Kuber-3/+22
Suggest changing an inner attribute into an outer attribute if followed by an item.
2021-09-01Stop sorting bodies by span.Camille GILLOT-8/+8
The definition order is already close to the span order, and only differs in corner cases.