diff options
| author | Ethan D. Twardy <[email protected]> | 2024-07-04 14:55:44 +0000 |
|---|---|---|
| committer | Miguel Ojeda <[email protected]> | 2024-11-01 21:02:53 +0000 |
| commit | 7e06561fcd9636b6483c5fcd8fe935475f4944f8 (patch) | |
| tree | d7da72455abd034411b96d050a0df1844f511269 /rust/macros/paste.rs | |
| parent | rust: enable macros::module! tests (diff) | |
| download | kernel-7e06561fcd9636b6483c5fcd8fe935475f4944f8.tar.gz kernel-7e06561fcd9636b6483c5fcd8fe935475f4944f8.zip | |
rust: macros: enable paste! use from macro_rules!
According to the rustdoc for the proc_macro crate[1], tokens captured
from a "macro variable" (e.g. from within macro_rules!) may be delimited
by invisible tokens and be contained within a proc_macro::Group.
Previously, this scenario was not handled by macros::paste, which caused
a proc-macro panic when the corresponding tests are enabled. Enable the
tests, and handle this case by making macros::paste::concat recursive.
Link: https://doc.rust-lang.org/stable/proc_macro/enum.Delimiter.html [1]
Signed-off-by: Ethan D. Twardy <[email protected]>
Reviewed-by: Alice Ryhl <[email protected]>
Link: https://github.com/Rust-for-Linux/linux/issues/1076
Link: https://lore.kernel.org/r/[email protected]
[ Rebased (one fix was already applied) and reworded. Remove unneeded
`rust` as language in examples. - Miguel ]
Signed-off-by: Miguel Ojeda <[email protected]>
Diffstat (limited to 'rust/macros/paste.rs')
| -rw-r--r-- | rust/macros/paste.rs | 15 |
1 files changed, 12 insertions, 3 deletions
diff --git a/rust/macros/paste.rs b/rust/macros/paste.rs index f40d42b35b58..6529a387673f 100644 --- a/rust/macros/paste.rs +++ b/rust/macros/paste.rs @@ -2,7 +2,7 @@ use proc_macro::{Delimiter, Group, Ident, Spacing, Span, TokenTree}; -fn concat(tokens: &[TokenTree], group_span: Span) -> TokenTree { +fn concat_helper(tokens: &[TokenTree]) -> Vec<(String, Span)> { let mut tokens = tokens.iter(); let mut segments = Vec::new(); let mut span = None; @@ -46,12 +46,21 @@ fn concat(tokens: &[TokenTree], group_span: Span) -> TokenTree { }; segments.push((value, sp)); } - _ => panic!("unexpected token in paste segments"), + Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::None => { + let tokens = group.stream().into_iter().collect::<Vec<TokenTree>>(); + segments.append(&mut concat_helper(tokens.as_slice())); + } + token => panic!("unexpected token in paste segments: {:?}", token), }; } + segments +} + +fn concat(tokens: &[TokenTree], group_span: Span) -> TokenTree { + let segments = concat_helper(tokens); let pasted: String = segments.into_iter().map(|x| x.0).collect(); - TokenTree::Ident(Ident::new(&pasted, span.unwrap_or(group_span))) + TokenTree::Ident(Ident::new(&pasted, group_span)) } pub(crate) fn expand(tokens: &mut Vec<TokenTree>) { |
