ACP: add proc_macro::ToTokens
to support proc_macro::quote
#431
Labels
ACP-accepted
API Change Proposal is accepted (seconded with no objections)
api-change-proposal
A proposal to add or alter unstable APIs in the standard libraries
T-libs-api
Proposal
Problem statement
Context: rust-lang/rust#54722 (comment)
Our version of
quote!
currently relies onFrom<TokenStream>
, which has some limitations:Ident
,Literal
cannot be quoted directly; they need to be converted to aTokenStream
outside of thequote!
invocation firstu32
,&str
, etc cannot be quoted directly&TokenStream
cannot be quoted; they need to be cloned outside ofpm::quote!
These are pretty notable limitations compared to
quote::quote!
, for which all of the above work.Motivating examples or use cases
The following does not work:
Reusing the same item is inconvenient:
Solution sketch
Add
proc_macro::ToTokens
that is identical toquote::ToTokens
:Implement this for most types that have
quote::ToTokens
, including:TokenTree
,TokenStream
Literal
,Ident
,Punct
,Group
T: ToTokens
:&T
&mut T
Box<T>
Rc<T>
Option<T>
Cow<T>
Literal
s: integer and float primitives,bool
,char
,str
,String
,CStr
,CString
proc_macro2
will be able to implementpm::ToTokens
on its token types so they are accepted bypm::quote!
Change
pm::quote
to make use ofToTokens
when it expands, rather thanFrom
Reimplement some
TokenStream
conversion traits in terms ofToTokens
if this can be done without breakageThis does some of the job
quote::TokenStreamExt
.Alternatives
From<X> for TokenStream
but add this impl more of the types listed above. Having a dedicated trait seems less fragile, especially for literal types.to_token_stream
andinto_token_stream
fromToTokens
or gating them separately since they are just for convenience, rather than helping to solve aToTokens
doesn't seem quite accurate, but I don't know what would be better (ToTokenStream
?ExtendTokenStream
? Those seem a bit clunky).impl<T: ToTokens> ToTokens for T
is provided, shouldto_tokens
takeself
by value rather than by reference so cloning isn't always necessary? (fn to_tokens(self, tokens: &mut TokenStream)
)Links and related work
quote!
macro inproc_macro
rust#54722quote::ToTokens
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
Second, if there's a concrete solution:
The text was updated successfully, but these errors were encountered: