Try not to rely on prelude in ruma-api-macros generated code

… and fix some lines that were too wide
This commit is contained in:
Jonas Platte 2020-08-01 01:20:42 +02:00
parent 12c7a4a17c
commit f5c529bc36
No known key found for this signature in database
GPG Key ID: 7D261D771D915378
3 changed files with 61 additions and 51 deletions

View File

@ -93,7 +93,7 @@ impl ToTokens for Api {
let non_auth_endpoint_impl = if requires_authentication.value { let non_auth_endpoint_impl = if requires_authentication.value {
quote! { quote! {
impl ruma_api::NonAuthEndpoint for Request {} impl ::ruma_api::NonAuthEndpoint for Request {}
} }
} else { } else {
TokenStream::new() TokenStream::new()
@ -116,7 +116,8 @@ impl ToTokens for Api {
let extract_request_path = if self.request.has_path_fields() { let extract_request_path = if self.request.has_path_fields() {
quote! { quote! {
let path_segments: Vec<&str> = request.uri().path()[1..].split('/').collect(); let path_segments: ::std::vec::Vec<&::std::primitive::str> =
request.uri().path()[1..].split('/').collect();
} }
} else { } else {
TokenStream::new() TokenStream::new()
@ -142,12 +143,12 @@ impl ToTokens for Api {
let mut header_kvs = self.request.append_header_kvs(); let mut header_kvs = self.request.append_header_kvs();
if requires_authentication.value { if requires_authentication.value {
header_kvs.push(quote! { header_kvs.push(quote! {
ruma_api::exports::http::header::AUTHORIZATION, ::ruma_api::exports::http::header::AUTHORIZATION,
ruma_api::exports::http::header::HeaderValue::from_str( ::ruma_api::exports::http::header::HeaderValue::from_str(
&format!( &::std::format!(
"Bearer {}", "Bearer {}",
access_token.ok_or_else( access_token.ok_or_else(
ruma_api::error::IntoHttpError::needs_authentication ::ruma_api::error::IntoHttpError::needs_authentication
)? )?
) )
)? )?
@ -162,11 +163,11 @@ impl ToTokens for Api {
TokenStream::new() TokenStream::new()
}; };
let extract_request_body = if self.request.has_body_fields() let extract_request_body =
|| self.request.newtype_body_field().is_some() if self.request.has_body_fields() || self.request.newtype_body_field().is_some() {
{
quote! { quote! {
let request_body: <RequestBody as ::ruma_api::Outgoing>::Incoming = ::ruma_api::try_deserialize!( let request_body: <RequestBody as ::ruma_api::Outgoing>::Incoming =
::ruma_api::try_deserialize!(
request, request,
::ruma_api::exports::serde_json::from_slice(request.body().as_slice()) ::ruma_api::exports::serde_json::from_slice(request.body().as_slice())
); );
@ -193,11 +194,11 @@ impl ToTokens for Api {
TokenStream::new() TokenStream::new()
}; };
let typed_response_body_decl = if self.response.has_body_fields() let typed_response_body_decl =
|| self.response.newtype_body_field().is_some() if self.response.has_body_fields() || self.response.newtype_body_field().is_some() {
{
quote! { quote! {
let response_body: <ResponseBody as ::ruma_api::Outgoing>::Incoming = ::ruma_api::try_deserialize!( let response_body: <ResponseBody as ::ruma_api::Outgoing>::Incoming =
::ruma_api::try_deserialize!(
response, response,
::ruma_api::exports::serde_json::from_slice(response.body().as_slice()), ::ruma_api::exports::serde_json::from_slice(response.body().as_slice()),
); );
@ -222,20 +223,26 @@ impl ToTokens for Api {
let error = &self.error; let error = &self.error;
let api = quote! { let api = quote! {
// FIXME: These can't conflict with other imports, but it would still be nice not to
// bring anything into scope that code outside the macro could then rely on.
use ::std::convert::TryInto as _;
use ::ruma_api::exports::serde::de::Error as _; use ::ruma_api::exports::serde::de::Error as _;
use ::ruma_api::exports::serde::Deserialize as _; use ::ruma_api::exports::serde::Deserialize as _;
use ::ruma_api::Endpoint as _; use ::ruma_api::Endpoint as _;
use std::convert::TryInto as _;
#[doc = #request_doc] #[doc = #request_doc]
#request_type #request_type
impl std::convert::TryFrom<::ruma_api::exports::http::Request<Vec<u8>>> for #request_try_from_type { impl ::std::convert::TryFrom<::ruma_api::exports::http::Request<Vec<u8>>>
for #request_try_from_type
{
type Error = ::ruma_api::error::FromHttpRequestError; type Error = ::ruma_api::error::FromHttpRequestError;
#[allow(unused_variables)] #[allow(unused_variables)]
fn try_from(request: ::ruma_api::exports::http::Request<Vec<u8>>) -> Result<Self, Self::Error> { fn try_from(
request: ::ruma_api::exports::http::Request<Vec<u8>>
) -> ::std::result::Result<Self, Self::Error> {
#extract_request_path #extract_request_path
#extract_request_query #extract_request_query
#extract_request_headers #extract_request_headers
@ -253,11 +260,13 @@ impl ToTokens for Api {
#[doc = #response_doc] #[doc = #response_doc]
#response_type #response_type
impl std::convert::TryFrom<Response> for ::ruma_api::exports::http::Response<Vec<u8>> { impl ::std::convert::TryFrom<Response>
for ::ruma_api::exports::http::Response<Vec<u8>>
{
type Error = ::ruma_api::error::IntoHttpError; type Error = ::ruma_api::error::IntoHttpError;
#[allow(unused_variables)] #[allow(unused_variables)]
fn try_from(response: Response) -> Result<Self, Self::Error> { fn try_from(response: Response) -> ::std::result::Result<Self, Self::Error> {
let response = ::ruma_api::exports::http::Response::builder() let response = ::ruma_api::exports::http::Response::builder()
.header(::ruma_api::exports::http::header::CONTENT_TYPE, "application/json") .header(::ruma_api::exports::http::header::CONTENT_TYPE, "application/json")
#serialize_response_headers #serialize_response_headers
@ -269,13 +278,15 @@ impl ToTokens for Api {
} }
} }
impl std::convert::TryFrom<::ruma_api::exports::http::Response<Vec<u8>>> for #response_try_from_type { impl ::std::convert::TryFrom<::ruma_api::exports::http::Response<Vec<u8>>>
for #response_try_from_type
{
type Error = ::ruma_api::error::FromHttpResponseError<#error>; type Error = ::ruma_api::error::FromHttpResponseError<#error>;
#[allow(unused_variables)] #[allow(unused_variables)]
fn try_from( fn try_from(
response: ::ruma_api::exports::http::Response<Vec<u8>>, response: ::ruma_api::exports::http::Response<Vec<u8>>,
) -> Result<Self, Self::Error> { ) -> ::std::result::Result<Self, Self::Error> {
if response.status().as_u16() < 400 { if response.status().as_u16() < 400 {
#extract_response_headers #extract_response_headers
@ -310,7 +321,7 @@ impl ToTokens for Api {
#[allow(unused_mut, unused_variables)] #[allow(unused_mut, unused_variables)]
fn try_into_http_request( fn try_into_http_request(
self, self,
base_url: &str, base_url: &::std::primitive::str,
access_token: ::std::option::Option<&str>, access_token: ::std::option::Option<&str>,
) -> ::std::result::Result< ) -> ::std::result::Result<
::ruma_api::exports::http::Request<Vec<u8>>, ::ruma_api::exports::http::Request<Vec<u8>>,

View File

@ -138,10 +138,10 @@ fn strip_lifetimes(field_type: &mut Type) -> bool {
if path.is_ident("str") { if path.is_ident("str") {
// &str -> String // &str -> String
*field_type = parse_quote! { String }; *field_type = parse_quote! { ::std::string::String };
} else if segs.contains(&"DeviceId".into()) || segs.contains(&"ServerName".into()) { } else if segs.contains(&"DeviceId".into()) || segs.contains(&"ServerName".into()) {
// The identifiers that need to be boxed `Box<T>` since they are DST's. // The identifiers that need to be boxed `Box<T>` since they are DST's.
*field_type = parse_quote! { Box<#path> }; *field_type = parse_quote! { ::std::boxed::Box<#path> };
} else { } else {
// &T -> T // &T -> T
*field_type = Type::Path(ty_path.clone()); *field_type = Type::Path(ty_path.clone());

View File

@ -45,9 +45,9 @@ pub(crate) fn request_path_string_and_parse(
Span::call_site(), Span::call_site(),
); );
format_args.push(quote! { format_args.push(quote! {
ruma_api::exports::percent_encoding::utf8_percent_encode( ::ruma_api::exports::percent_encoding::utf8_percent_encode(
&self.#path_var.to_string(), &self.#path_var.to_string(),
ruma_api::exports::percent_encoding::NON_ALPHANUMERIC, ::ruma_api::exports::percent_encoding::NON_ALPHANUMERIC,
) )
}); });
format_string.replace_range(start_of_segment..end_of_segment, "{}"); format_string.replace_range(start_of_segment..end_of_segment, "{}");
@ -65,17 +65,16 @@ pub(crate) fn request_path_string_and_parse(
let path_var_ident = Ident::new(path_var, Span::call_site()); let path_var_ident = Ident::new(path_var, Span::call_site());
quote! { quote! {
#path_var_ident: { #path_var_ident: {
use std::ops::Deref as _; use ::ruma_api::error::RequestDeserializationError;
use ruma_api::error::RequestDeserializationError;
let segment = path_segments.get(#i).unwrap().as_bytes(); let segment = path_segments.get(#i).unwrap().as_bytes();
let decoded = ::ruma_api::try_deserialize!( let decoded = ::ruma_api::try_deserialize!(
request, request,
ruma_api::exports::percent_encoding::percent_decode(segment) ::ruma_api::exports::percent_encoding::percent_decode(segment)
.decode_utf8(), .decode_utf8(),
); );
::ruma_api::try_deserialize!(request, std::convert::TryFrom::try_from(decoded.deref())) ::ruma_api::try_deserialize!(request, ::std::convert::TryFrom::try_from(&*decoded))
} }
} }
}, },
@ -107,14 +106,14 @@ pub(crate) fn build_query_string(request: &Request) -> TokenStream {
// ensure that it won't fail. // ensure that it won't fail.
fn assert_trait_impl<T>() fn assert_trait_impl<T>()
where where
T: std::iter::IntoIterator<Item = (std::string::String, std::string::String)>, T: ::std::iter::IntoIterator<Item = (::std::string::String, ::std::string::String)>,
{} {}
assert_trait_impl::<#field_type>(); assert_trait_impl::<#field_type>();
let request_query = RequestQuery(self.#field_name); let request_query = RequestQuery(self.#field_name);
format_args!( format_args!(
"?{}", "?{}",
ruma_api::exports::ruma_serde::urlencoded::to_string(request_query)? ::ruma_api::exports::ruma_serde::urlencoded::to_string(request_query)?
) )
}) })
} else if request.has_query_fields() { } else if request.has_query_fields() {
@ -127,7 +126,7 @@ pub(crate) fn build_query_string(request: &Request) -> TokenStream {
format_args!( format_args!(
"?{}", "?{}",
ruma_api::exports::ruma_serde::urlencoded::to_string(request_query)? ::ruma_api::exports::ruma_serde::urlencoded::to_string(request_query)?
) )
}) })
} else { } else {
@ -179,7 +178,7 @@ pub(crate) fn build_request_body(request: &Request) -> TokenStream {
quote! { quote! {
{ {
let request_body = RequestBody #request_body_initializers; let request_body = RequestBody #request_body_initializers;
ruma_api::exports::serde_json::to_vec(&request_body)? ::ruma_api::exports::serde_json::to_vec(&request_body)?
} }
} }
} else { } else {