mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-05-30 10:31:03 +00:00
cargo +nightly fmt (#3540)
* cargo +nightly fmt * add cargo-fmt check to ci * update ci * fmt * fmt * skip macro * ignore bridges
This commit is contained in:
@@ -1,15 +1,14 @@
|
||||
//! A dummy to be used with cargo expand
|
||||
|
||||
use polkadot_overseer_gen::*;
|
||||
use polkadot_node_network_protocol::WrongVariant;
|
||||
|
||||
use polkadot_overseer_gen::*;
|
||||
|
||||
/// Concrete subsystem implementation for `MsgStrukt` msg type.
|
||||
#[derive(Default)]
|
||||
pub struct AwesomeSubSys;
|
||||
|
||||
impl ::polkadot_overseer_gen::Subsystem<XxxSubsystemContext<MsgStrukt>, Yikes> for AwesomeSubSys {
|
||||
fn start(self, _ctx: XxxSubsystemContext<MsgStrukt>) -> SpawnedSubsystem < Yikes > {
|
||||
impl ::polkadot_overseer_gen::Subsystem<XxxSubsystemContext<MsgStrukt>, Yikes> for AwesomeSubSys {
|
||||
fn start(self, _ctx: XxxSubsystemContext<MsgStrukt>) -> SpawnedSubsystem<Yikes> {
|
||||
unimplemented!("starting yay!")
|
||||
}
|
||||
}
|
||||
@@ -18,22 +17,19 @@ impl ::polkadot_overseer_gen::Subsystem<XxxSubsystemContext<MsgStrukt>, Yikes> f
|
||||
pub struct GoblinTower;
|
||||
|
||||
impl ::polkadot_overseer_gen::Subsystem<XxxSubsystemContext<Plinko>, Yikes> for GoblinTower {
|
||||
fn start(self, _ctx: XxxSubsystemContext<Plinko>) -> SpawnedSubsystem < Yikes > {
|
||||
fn start(self, _ctx: XxxSubsystemContext<Plinko>) -> SpawnedSubsystem<Yikes> {
|
||||
unimplemented!("welcum")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// A signal sent by the overseer.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SigSigSig;
|
||||
|
||||
|
||||
/// The external event.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EvX;
|
||||
|
||||
|
||||
impl EvX {
|
||||
pub fn focus<'a, T>(&'a self) -> Result<EvX, ()> {
|
||||
unimplemented!("dispatch")
|
||||
@@ -75,7 +71,6 @@ impl From<NetworkMsg> for MsgStrukt {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum NetworkMsg {
|
||||
A,
|
||||
@@ -83,18 +78,15 @@ pub enum NetworkMsg {
|
||||
C,
|
||||
}
|
||||
|
||||
|
||||
impl NetworkMsg {
|
||||
fn focus(&self) -> Result<Self, WrongVariant> {
|
||||
Ok(match self {
|
||||
Self::B => return Err(WrongVariant),
|
||||
Self::A | Self::C => self.clone()
|
||||
Self::A | Self::C => self.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
#[overlord(signal=SigSigSig, event=EvX, error=Yikes, network=NetworkMsg, gen=AllMessages)]
|
||||
struct Xxx {
|
||||
#[subsystem(MsgStrukt)]
|
||||
@@ -109,7 +101,7 @@ struct Xxx {
|
||||
#[derive(Debug, Clone)]
|
||||
struct DummySpawner;
|
||||
|
||||
impl SpawnNamed for DummySpawner{
|
||||
impl SpawnNamed for DummySpawner {
|
||||
fn spawn_blocking(&self, name: &'static str, _future: futures::future::BoxFuture<'static, ()>) {
|
||||
unimplemented!("spawn blocking {}", name)
|
||||
}
|
||||
|
||||
@@ -80,10 +80,8 @@ pub(crate) fn impl_builder(info: &OverseerInfo) -> proc_macro2::TokenStream {
|
||||
|
||||
let consumes = &info.consumes();
|
||||
|
||||
let subsyste_ctx_name = Ident::new(
|
||||
&(overseer_name.to_string() + "SubsystemContext"),
|
||||
overseer_name.span()
|
||||
);
|
||||
let subsyste_ctx_name =
|
||||
Ident::new(&(overseer_name.to_string() + "SubsystemContext"), overseer_name.span());
|
||||
|
||||
let builder_where_clause = quote! {
|
||||
where
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use super::*;
|
||||
use proc_macro2::{TokenStream, Ident};
|
||||
use proc_macro2::{Ident, TokenStream};
|
||||
use quote::quote;
|
||||
use syn::Path;
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use quote::quote;
|
||||
use syn::Result;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{spanned::Spanned, Result};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -30,21 +29,24 @@ pub(crate) fn impl_message_wrapper_enum(info: &OverseerInfo) -> Result<proc_macr
|
||||
let message_wrapper = &info.message_wrapper;
|
||||
|
||||
let (outgoing_from_impl, outgoing_decl) = if let Some(outgoing) = outgoing {
|
||||
let outgoing_variant = outgoing
|
||||
.get_ident()
|
||||
.ok_or_else(||{
|
||||
syn::Error::new(outgoing.span(), "Missing identifier to use as enum variant for outgoing.")
|
||||
})?;
|
||||
(quote! {
|
||||
impl ::std::convert::From< #outgoing > for #message_wrapper {
|
||||
fn from(message: #outgoing) -> Self {
|
||||
#message_wrapper :: #outgoing_variant ( message )
|
||||
let outgoing_variant = outgoing.get_ident().ok_or_else(|| {
|
||||
syn::Error::new(
|
||||
outgoing.span(),
|
||||
"Missing identifier to use as enum variant for outgoing.",
|
||||
)
|
||||
})?;
|
||||
(
|
||||
quote! {
|
||||
impl ::std::convert::From< #outgoing > for #message_wrapper {
|
||||
fn from(message: #outgoing) -> Self {
|
||||
#message_wrapper :: #outgoing_variant ( message )
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
quote! {
|
||||
#outgoing_variant ( #outgoing ) ,
|
||||
})
|
||||
},
|
||||
quote! {
|
||||
#outgoing_variant ( #outgoing ) ,
|
||||
},
|
||||
)
|
||||
} else {
|
||||
(TokenStream::new(), TokenStream::new())
|
||||
};
|
||||
|
||||
@@ -23,8 +23,10 @@ use super::*;
|
||||
/// which acts as the gateway to constructing the overseer.
|
||||
pub(crate) fn impl_misc(info: &OverseerInfo) -> proc_macro2::TokenStream {
|
||||
let overseer_name = info.overseer_name.clone();
|
||||
let subsystem_sender_name = Ident::new(&(overseer_name.to_string() + "SubsystemSender"), overseer_name.span());
|
||||
let subsystem_ctx_name = Ident::new(&(overseer_name.to_string() + "SubsystemContext"), overseer_name.span());
|
||||
let subsystem_sender_name =
|
||||
Ident::new(&(overseer_name.to_string() + "SubsystemSender"), overseer_name.span());
|
||||
let subsystem_ctx_name =
|
||||
Ident::new(&(overseer_name.to_string() + "SubsystemContext"), overseer_name.span());
|
||||
let consumes = &info.consumes();
|
||||
let signal = &info.extern_signal_ty;
|
||||
let wrapper_message = &info.message_wrapper;
|
||||
|
||||
@@ -52,7 +52,8 @@ pub(crate) fn impl_overseer_struct(info: &OverseerInfo) -> proc_macro2::TokenStr
|
||||
let message_channel_capacity = info.message_channel_capacity;
|
||||
let signal_channel_capacity = info.signal_channel_capacity;
|
||||
|
||||
let log_target = syn::LitStr::new(overseer_name.to_string().to_lowercase().as_str(), overseer_name.span());
|
||||
let log_target =
|
||||
syn::LitStr::new(overseer_name.to_string().to_lowercase().as_str(), overseer_name.span());
|
||||
|
||||
let ts = quote! {
|
||||
const STOP_DELAY: ::std::time::Duration = ::std::time::Duration::from_secs(1);
|
||||
|
||||
@@ -16,18 +16,18 @@
|
||||
|
||||
#![deny(unused_crate_dependencies)]
|
||||
|
||||
use proc_macro2::{Span, Ident, TokenStream};
|
||||
use syn::{parse2, Result};
|
||||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
use quote::{quote, ToTokens};
|
||||
use syn::{parse2, Result};
|
||||
|
||||
mod impl_builder;
|
||||
mod impl_channels_out;
|
||||
mod impl_dispatch;
|
||||
mod impl_message_wrapper;
|
||||
mod impl_misc;
|
||||
mod impl_overseer;
|
||||
mod parse_attr;
|
||||
mod parse_struct;
|
||||
mod impl_channels_out;
|
||||
mod impl_dispatch;
|
||||
mod impl_message_wrapper;
|
||||
|
||||
use impl_builder::*;
|
||||
use impl_channels_out::*;
|
||||
@@ -42,28 +42,36 @@ use parse_struct::*;
|
||||
mod tests;
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn overlord(attr: proc_macro::TokenStream, item: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
pub fn overlord(
|
||||
attr: proc_macro::TokenStream,
|
||||
item: proc_macro::TokenStream,
|
||||
) -> proc_macro::TokenStream {
|
||||
let attr: TokenStream = attr.into();
|
||||
let item: TokenStream = item.into();
|
||||
impl_overseer_gen(attr, item).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
impl_overseer_gen(attr, item)
|
||||
.unwrap_or_else(|err| err.to_compile_error())
|
||||
.into()
|
||||
}
|
||||
|
||||
pub(crate) fn impl_overseer_gen(attr: TokenStream, orig: TokenStream) -> Result<proc_macro2::TokenStream> {
|
||||
pub(crate) fn impl_overseer_gen(
|
||||
attr: TokenStream,
|
||||
orig: TokenStream,
|
||||
) -> Result<proc_macro2::TokenStream> {
|
||||
let args: AttrArgs = parse2(attr)?;
|
||||
let message_wrapper = args.message_wrapper;
|
||||
|
||||
let of: OverseerGuts = parse2(orig)?;
|
||||
|
||||
let support_crate_name = if cfg!(test) {
|
||||
quote!{crate}
|
||||
quote! {crate}
|
||||
} else {
|
||||
use proc_macro_crate::{crate_name, FoundCrate};
|
||||
let crate_name = crate_name("polkadot-overseer-gen")
|
||||
.expect("Support crate polkadot-overseer-gen is present in `Cargo.toml`. qed");
|
||||
match crate_name {
|
||||
FoundCrate::Itself => quote!{crate},
|
||||
FoundCrate::Name(name) => Ident::new(&name, Span::call_site()).to_token_stream(),
|
||||
}
|
||||
FoundCrate::Itself => quote! {crate},
|
||||
FoundCrate::Name(name) => Ident::new(&name, Span::call_site()).to_token_stream(),
|
||||
}
|
||||
};
|
||||
let info = OverseerInfo {
|
||||
support_crate_name,
|
||||
|
||||
@@ -15,12 +15,14 @@
|
||||
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use proc_macro2::Span;
|
||||
use std::collections::{hash_map::RandomState, HashMap};
|
||||
use syn::parse::{Parse, ParseBuffer};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Error, Ident, LitInt, Path, Result, Token};
|
||||
use quote::{quote, ToTokens};
|
||||
use std::collections::{hash_map::RandomState, HashMap};
|
||||
use syn::{
|
||||
parse::{Parse, ParseBuffer},
|
||||
punctuated::Punctuated,
|
||||
spanned::Spanned,
|
||||
Error, Ident, LitInt, Path, Result, Token,
|
||||
};
|
||||
|
||||
mod kw {
|
||||
syn::custom_keyword!(event);
|
||||
@@ -33,62 +35,45 @@ mod kw {
|
||||
syn::custom_keyword!(message_capacity);
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum OverseerAttrItem {
|
||||
ExternEventType {
|
||||
tag: kw::event,
|
||||
eq_token: Token![=],
|
||||
value: Path
|
||||
},
|
||||
ExternNetworkType {
|
||||
tag: kw::network,
|
||||
eq_token: Token![=],
|
||||
value: Path
|
||||
},
|
||||
ExternOverseerSignalType {
|
||||
tag: kw::signal,
|
||||
eq_token: Token![=],
|
||||
value: Path
|
||||
},
|
||||
ExternErrorType {
|
||||
tag: kw::error,
|
||||
eq_token: Token![=],
|
||||
value: Path
|
||||
},
|
||||
OutgoingType {
|
||||
tag: kw::outgoing,
|
||||
eq_token: Token![=],
|
||||
value: Path
|
||||
},
|
||||
MessageWrapperName {
|
||||
tag: kw::gen,
|
||||
eq_token: Token![=],
|
||||
value: Ident
|
||||
},
|
||||
SignalChannelCapacity {
|
||||
tag: kw::signal_capacity,
|
||||
eq_token: Token![=],
|
||||
value: usize
|
||||
},
|
||||
MessageChannelCapacity {
|
||||
tag: kw::message_capacity,
|
||||
eq_token: Token![=],
|
||||
value: usize
|
||||
},
|
||||
ExternEventType { tag: kw::event, eq_token: Token![=], value: Path },
|
||||
ExternNetworkType { tag: kw::network, eq_token: Token![=], value: Path },
|
||||
ExternOverseerSignalType { tag: kw::signal, eq_token: Token![=], value: Path },
|
||||
ExternErrorType { tag: kw::error, eq_token: Token![=], value: Path },
|
||||
OutgoingType { tag: kw::outgoing, eq_token: Token![=], value: Path },
|
||||
MessageWrapperName { tag: kw::gen, eq_token: Token![=], value: Ident },
|
||||
SignalChannelCapacity { tag: kw::signal_capacity, eq_token: Token![=], value: usize },
|
||||
MessageChannelCapacity { tag: kw::message_capacity, eq_token: Token![=], value: usize },
|
||||
}
|
||||
|
||||
impl ToTokens for OverseerAttrItem {
|
||||
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
|
||||
let ts = match self {
|
||||
Self::ExternEventType { tag, eq_token, value } => { quote!{ #tag #eq_token, #value } }
|
||||
Self::ExternNetworkType { tag, eq_token, value } => { quote!{ #tag #eq_token, #value } }
|
||||
Self::ExternOverseerSignalType { tag, eq_token, value } => { quote!{ #tag #eq_token, #value } }
|
||||
Self::ExternErrorType { tag, eq_token, value } => { quote!{ #tag #eq_token, #value } }
|
||||
Self::OutgoingType { tag, eq_token, value } => { quote!{ #tag #eq_token, #value } }
|
||||
Self::MessageWrapperName { tag, eq_token, value } => { quote!{ #tag #eq_token, #value } }
|
||||
Self::SignalChannelCapacity { tag, eq_token, value } => { quote!{ #tag #eq_token, #value } }
|
||||
Self::MessageChannelCapacity { tag, eq_token, value } => { quote!{ #tag #eq_token, #value } }
|
||||
Self::ExternEventType { tag, eq_token, value } => {
|
||||
quote! { #tag #eq_token, #value }
|
||||
},
|
||||
Self::ExternNetworkType { tag, eq_token, value } => {
|
||||
quote! { #tag #eq_token, #value }
|
||||
},
|
||||
Self::ExternOverseerSignalType { tag, eq_token, value } => {
|
||||
quote! { #tag #eq_token, #value }
|
||||
},
|
||||
Self::ExternErrorType { tag, eq_token, value } => {
|
||||
quote! { #tag #eq_token, #value }
|
||||
},
|
||||
Self::OutgoingType { tag, eq_token, value } => {
|
||||
quote! { #tag #eq_token, #value }
|
||||
},
|
||||
Self::MessageWrapperName { tag, eq_token, value } => {
|
||||
quote! { #tag #eq_token, #value }
|
||||
},
|
||||
Self::SignalChannelCapacity { tag, eq_token, value } => {
|
||||
quote! { #tag #eq_token, #value }
|
||||
},
|
||||
Self::MessageChannelCapacity { tag, eq_token, value } => {
|
||||
quote! { #tag #eq_token, #value }
|
||||
},
|
||||
};
|
||||
tokens.extend(ts.into_iter());
|
||||
}
|
||||
@@ -137,7 +122,7 @@ impl Parse for OverseerAttrItem {
|
||||
Ok(OverseerAttrItem::SignalChannelCapacity {
|
||||
tag: input.parse::<kw::signal_capacity>()?,
|
||||
eq_token: input.parse()?,
|
||||
value: input.parse::<LitInt>()?.base10_parse::<usize>()?
|
||||
value: input.parse::<LitInt>()?.base10_parse::<usize>()?,
|
||||
})
|
||||
} else if lookahead.peek(kw::message_capacity) {
|
||||
Ok(OverseerAttrItem::MessageChannelCapacity {
|
||||
@@ -169,42 +154,47 @@ pub(crate) struct AttrArgs {
|
||||
|
||||
macro_rules! extract_variant {
|
||||
($unique:expr, $variant:ident ; default = $fallback:expr) => {
|
||||
extract_variant!($unique, $variant)
|
||||
.unwrap_or_else(|| { $fallback })
|
||||
extract_variant!($unique, $variant).unwrap_or_else(|| $fallback)
|
||||
};
|
||||
($unique:expr, $variant:ident ; err = $err:expr) => {
|
||||
extract_variant!($unique, $variant)
|
||||
.ok_or_else(|| {
|
||||
Error::new(Span::call_site(), $err)
|
||||
})
|
||||
extract_variant!($unique, $variant).ok_or_else(|| Error::new(Span::call_site(), $err))
|
||||
};
|
||||
($unique:expr, $variant:ident) => {
|
||||
$unique.values()
|
||||
.find_map(|item| {
|
||||
if let OverseerAttrItem:: $variant { value, ..} = item {
|
||||
Some(value.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
$unique.values().find_map(|item| {
|
||||
if let OverseerAttrItem::$variant { value, .. } = item {
|
||||
Some(value.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
impl Parse for AttrArgs {
|
||||
fn parse(input: &ParseBuffer) -> Result<Self> {
|
||||
let items: Punctuated<OverseerAttrItem, Token![,]> = input.parse_terminated(OverseerAttrItem::parse)?;
|
||||
let items: Punctuated<OverseerAttrItem, Token![,]> =
|
||||
input.parse_terminated(OverseerAttrItem::parse)?;
|
||||
|
||||
let mut unique = HashMap::<std::mem::Discriminant<OverseerAttrItem>, OverseerAttrItem, RandomState>::default();
|
||||
let mut unique = HashMap::<
|
||||
std::mem::Discriminant<OverseerAttrItem>,
|
||||
OverseerAttrItem,
|
||||
RandomState,
|
||||
>::default();
|
||||
for item in items {
|
||||
if let Some(first) = unique.insert(std::mem::discriminant(&item), item.clone()) {
|
||||
let mut e = Error::new(item.span(), format!("Duplicate definition of overseer generation type found"));
|
||||
let mut e = Error::new(
|
||||
item.span(),
|
||||
format!("Duplicate definition of overseer generation type found"),
|
||||
);
|
||||
e.combine(Error::new(first.span(), "previously defined here."));
|
||||
return Err(e);
|
||||
return Err(e)
|
||||
}
|
||||
}
|
||||
|
||||
let signal_channel_capacity = extract_variant!(unique, SignalChannelCapacity; default = 64_usize);
|
||||
let message_channel_capacity = extract_variant!(unique, MessageChannelCapacity; default = 1024_usize);
|
||||
let signal_channel_capacity =
|
||||
extract_variant!(unique, SignalChannelCapacity; default = 64_usize);
|
||||
let message_channel_capacity =
|
||||
extract_variant!(unique, MessageChannelCapacity; default = 1024_usize);
|
||||
|
||||
let error = extract_variant!(unique, ExternErrorType; err = "Must declare the overseer error type via `error=..`.")?;
|
||||
let event = extract_variant!(unique, ExternEventType; err = "Must declare the overseer event type via `event=..`.")?;
|
||||
|
||||
@@ -15,13 +15,13 @@
|
||||
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use std::collections::{hash_map::RandomState, HashSet, HashMap};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use std::collections::{hash_map::RandomState, HashMap, HashSet};
|
||||
use syn::{
|
||||
Attribute, Field, FieldsNamed, Ident, Token, Type, AttrStyle, Path,
|
||||
Error, GenericParam, ItemStruct, Result, Visibility
|
||||
parse::{Parse, ParseStream},
|
||||
punctuated::Punctuated,
|
||||
spanned::Spanned,
|
||||
AttrStyle, Attribute, Error, Field, FieldsNamed, GenericParam, Ident, ItemStruct, Path, Result,
|
||||
Token, Type, Visibility,
|
||||
};
|
||||
|
||||
use quote::{quote, ToTokens};
|
||||
@@ -32,7 +32,6 @@ mod kw {
|
||||
syn::custom_keyword!(blocking);
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum SubSysAttrItem {
|
||||
/// The subsystem is still a work in progress
|
||||
@@ -64,15 +63,20 @@ impl Parse for SubSysAttrItem {
|
||||
impl ToTokens for SubSysAttrItem {
|
||||
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
|
||||
let ts = match self {
|
||||
Self::Wip(wip) => { quote!{ #wip } }
|
||||
Self::Blocking(blocking) => { quote!{ #blocking } }
|
||||
Self::NoDispatch(no_dispatch) => { quote!{ #no_dispatch } }
|
||||
Self::Wip(wip) => {
|
||||
quote! { #wip }
|
||||
},
|
||||
Self::Blocking(blocking) => {
|
||||
quote! { #blocking }
|
||||
},
|
||||
Self::NoDispatch(no_dispatch) => {
|
||||
quote! { #no_dispatch }
|
||||
},
|
||||
};
|
||||
tokens.extend(ts.into_iter());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// A field of the struct annotated with
|
||||
/// `#[subsystem(no_dispatch, , A | B | C)]`
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -106,28 +110,22 @@ fn try_type_to_path(ty: Type, span: Span) -> Result<Path> {
|
||||
|
||||
macro_rules! extract_variant {
|
||||
($unique:expr, $variant:ident ; default = $fallback:expr) => {
|
||||
extract_variant!($unique, $variant)
|
||||
.unwrap_or_else(|| { $fallback })
|
||||
extract_variant!($unique, $variant).unwrap_or_else(|| $fallback)
|
||||
};
|
||||
($unique:expr, $variant:ident ; err = $err:expr) => {
|
||||
extract_variant!($unique, $variant)
|
||||
.ok_or_else(|| {
|
||||
Error::new(Span::call_site(), $err)
|
||||
})
|
||||
extract_variant!($unique, $variant).ok_or_else(|| Error::new(Span::call_site(), $err))
|
||||
};
|
||||
($unique:expr, $variant:ident) => {
|
||||
$unique.values()
|
||||
.find_map(|item| {
|
||||
if let SubSysAttrItem:: $variant ( _ ) = item {
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
$unique.values().find_map(|item| {
|
||||
if let SubSysAttrItem::$variant(_) = item {
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
pub(crate) struct SubSystemTags {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) attrs: Vec<Attribute>,
|
||||
@@ -158,12 +156,19 @@ impl Parse for SubSystemTags {
|
||||
|
||||
let consumes = content.parse::<Path>()?;
|
||||
|
||||
let mut unique = HashMap::<std::mem::Discriminant<SubSysAttrItem>, SubSysAttrItem, RandomState>::default();
|
||||
let mut unique = HashMap::<
|
||||
std::mem::Discriminant<SubSysAttrItem>,
|
||||
SubSysAttrItem,
|
||||
RandomState,
|
||||
>::default();
|
||||
for item in items {
|
||||
if let Some(first) = unique.insert(std::mem::discriminant(&item), item.clone()) {
|
||||
let mut e = Error::new(item.span(), format!("Duplicate definition of subsystem attribute found"));
|
||||
let mut e = Error::new(
|
||||
item.span(),
|
||||
format!("Duplicate definition of subsystem attribute found"),
|
||||
);
|
||||
e.combine(Error::new(first.span(), "previously defined here."));
|
||||
return Err(e);
|
||||
return Err(e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,10 +233,7 @@ impl OverseerInfo {
|
||||
}
|
||||
|
||||
pub(crate) fn variant_names(&self) -> Vec<Ident> {
|
||||
self.subsystems
|
||||
.iter()
|
||||
.map(|ssf| ssf.generic.clone())
|
||||
.collect::<Vec<_>>()
|
||||
self.subsystems.iter().map(|ssf| ssf.generic.clone()).collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
pub(crate) fn variant_names_without_wip(&self) -> Vec<Ident> {
|
||||
@@ -272,13 +274,8 @@ impl OverseerInfo {
|
||||
self.baggage
|
||||
.iter()
|
||||
.map(|bag| {
|
||||
let BaggageField {
|
||||
vis,
|
||||
field_ty,
|
||||
field_name,
|
||||
..
|
||||
} = bag;
|
||||
quote!{ #vis #field_name: #field_ty }
|
||||
let BaggageField { vis, field_ty, field_name, .. } = bag;
|
||||
quote! { #vis #field_name: #field_ty }
|
||||
})
|
||||
.collect::<Vec<TokenStream>>()
|
||||
}
|
||||
@@ -330,7 +327,11 @@ pub(crate) struct OverseerGuts {
|
||||
}
|
||||
|
||||
impl OverseerGuts {
|
||||
pub(crate) fn parse_fields(name: Ident, baggage_generics: HashSet<Ident>, fields: FieldsNamed) -> Result<Self> {
|
||||
pub(crate) fn parse_fields(
|
||||
name: Ident,
|
||||
baggage_generics: HashSet<Ident>,
|
||||
fields: FieldsNamed,
|
||||
) -> Result<Self> {
|
||||
let n = fields.named.len();
|
||||
let mut subsystems = Vec::with_capacity(n);
|
||||
let mut baggage = Vec::with_capacity(n);
|
||||
@@ -340,14 +341,16 @@ impl OverseerGuts {
|
||||
// for the builder pattern besides other places.
|
||||
let mut unique_subsystem_idents = HashSet::<Ident>::new();
|
||||
for Field { attrs, vis, ident, ty, .. } in fields.named.into_iter() {
|
||||
let mut consumes = attrs.iter().filter(|attr| attr.style == AttrStyle::Outer).filter_map(|attr| {
|
||||
let span = attr.path.span();
|
||||
attr.path.get_ident().filter(|ident| *ident == "subsystem").map(move |_ident| {
|
||||
let attr_tokens = attr.tokens.clone();
|
||||
(attr_tokens, span)
|
||||
})
|
||||
});
|
||||
let ident = ident.ok_or_else(|| Error::new(ty.span(), "Missing identifier for member. BUG"))?;
|
||||
let mut consumes =
|
||||
attrs.iter().filter(|attr| attr.style == AttrStyle::Outer).filter_map(|attr| {
|
||||
let span = attr.path.span();
|
||||
attr.path.get_ident().filter(|ident| *ident == "subsystem").map(move |_ident| {
|
||||
let attr_tokens = attr.tokens.clone();
|
||||
(attr_tokens, span)
|
||||
})
|
||||
});
|
||||
let ident =
|
||||
ident.ok_or_else(|| Error::new(ty.span(), "Missing identifier for member. BUG"))?;
|
||||
|
||||
if let Some((attr_tokens, span)) = consumes.next() {
|
||||
if let Some((_attr_tokens2, span2)) = consumes.next() {
|
||||
@@ -355,7 +358,7 @@ impl OverseerGuts {
|
||||
let mut err = Error::new(span, "The first subsystem annotation is at");
|
||||
err.combine(Error::new(span2, "but another here for the same field."));
|
||||
err
|
||||
});
|
||||
})
|
||||
}
|
||||
let mut consumes_paths = Vec::with_capacity(attrs.len());
|
||||
let attr_tokens = attr_tokens.clone();
|
||||
@@ -363,9 +366,17 @@ impl OverseerGuts {
|
||||
consumes_paths.push(variant.consumes);
|
||||
|
||||
let field_ty = try_type_to_path(ty, span)?;
|
||||
let generic = field_ty.get_ident().ok_or_else(|| Error::new(field_ty.span(), "Must be an identifier, not a path."))?.clone();
|
||||
let generic = field_ty
|
||||
.get_ident()
|
||||
.ok_or_else(|| {
|
||||
Error::new(field_ty.span(), "Must be an identifier, not a path.")
|
||||
})?
|
||||
.clone();
|
||||
if let Some(previous) = unique_subsystem_idents.get(&generic) {
|
||||
let mut e = Error::new(generic.span(), format!("Duplicate subsystem names `{}`", generic));
|
||||
let mut e = Error::new(
|
||||
generic.span(),
|
||||
format!("Duplicate subsystem names `{}`", generic),
|
||||
);
|
||||
e.combine(Error::new(previous.span(), "previously defined here."));
|
||||
return Err(e)
|
||||
}
|
||||
@@ -381,7 +392,10 @@ impl OverseerGuts {
|
||||
});
|
||||
} else {
|
||||
let field_ty = try_type_to_path(ty, ident.span())?;
|
||||
let generic = field_ty.get_ident().map(|ident| baggage_generics.contains(ident)).unwrap_or_default();
|
||||
let generic = field_ty
|
||||
.get_ident()
|
||||
.map(|ident| baggage_generics.contains(ident))
|
||||
.unwrap_or_default();
|
||||
baggage.push(BaggageField { field_name: ident, generic, field_ty, vis });
|
||||
}
|
||||
}
|
||||
@@ -411,21 +425,23 @@ impl Parse for OverseerGuts {
|
||||
baggage_generic_idents.insert(param.ident.clone());
|
||||
param.eq_token = None;
|
||||
param.default = None;
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
generic
|
||||
})
|
||||
.collect();
|
||||
|
||||
Self::parse_fields(name, baggage_generic_idents, named)
|
||||
}
|
||||
syn::Fields::Unit => {
|
||||
Err(Error::new(ds.fields.span(), "Must be a struct with named fields. Not an unit struct."))
|
||||
}
|
||||
syn::Fields::Unnamed(unnamed) => {
|
||||
Err(Error::new(unnamed.span(), "Must be a struct with named fields. Not an unnamed fields struct."))
|
||||
}
|
||||
},
|
||||
syn::Fields::Unit => Err(Error::new(
|
||||
ds.fields.span(),
|
||||
"Must be a struct with named fields. Not an unit struct.",
|
||||
)),
|
||||
syn::Fields::Unnamed(unnamed) => Err(Error::new(
|
||||
unnamed.span(),
|
||||
"Must be a struct with named fields. Not an unnamed fields struct.",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,39 +62,34 @@
|
||||
|
||||
pub use polkadot_overseer_gen_proc_macro::overlord;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use tracing;
|
||||
#[doc(hidden)]
|
||||
pub use metered;
|
||||
#[doc(hidden)]
|
||||
pub use polkadot_node_primitives::SpawnNamed;
|
||||
#[doc(hidden)]
|
||||
pub use tracing;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use async_trait::async_trait;
|
||||
#[doc(hidden)]
|
||||
pub use futures::{
|
||||
self,
|
||||
select,
|
||||
StreamExt,
|
||||
FutureExt,
|
||||
poll,
|
||||
future::{
|
||||
Fuse, Future, BoxFuture
|
||||
},
|
||||
stream::{
|
||||
self, select, FuturesUnordered,
|
||||
},
|
||||
task::{
|
||||
Poll, Context,
|
||||
},
|
||||
channel::{mpsc, oneshot},
|
||||
future::{BoxFuture, Fuse, Future},
|
||||
poll, select,
|
||||
stream::{self, select, FuturesUnordered},
|
||||
task::{Context, Poll},
|
||||
FutureExt, StreamExt,
|
||||
};
|
||||
#[doc(hidden)]
|
||||
pub use std::pin::Pin;
|
||||
#[doc(hidden)]
|
||||
pub use async_trait::async_trait;
|
||||
|
||||
use std::sync::{
|
||||
atomic::{self, AtomicUsize},
|
||||
Arc,
|
||||
};
|
||||
#[doc(hidden)]
|
||||
pub use std::time::Duration;
|
||||
use std::sync::{Arc, atomic::{self, AtomicUsize}};
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use futures_timer::Delay;
|
||||
@@ -103,7 +98,6 @@ pub use polkadot_node_network_protocol::WrongVariant;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -134,15 +128,12 @@ pub enum ToOverseer {
|
||||
impl fmt::Debug for ToOverseer {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::SpawnJob{ name, .. } => writeln!(f, "SpawnJob{{ {}, ..}}", name),
|
||||
Self::SpawnBlockingJob{ name, .. } => writeln!(f, "SpawnBlockingJob{{ {}, ..}}", name),
|
||||
Self::SpawnJob { name, .. } => writeln!(f, "SpawnJob{{ {}, ..}}", name),
|
||||
Self::SpawnBlockingJob { name, .. } => writeln!(f, "SpawnBlockingJob{{ {}, ..}}", name),
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// A helper trait to map a subsystem to smth. else.
|
||||
pub trait MapSubsystem<T> {
|
||||
/// The output type of the mapping.
|
||||
@@ -152,7 +143,10 @@ pub trait MapSubsystem<T> {
|
||||
fn map_subsystem(&self, sub: T) -> Self::Output;
|
||||
}
|
||||
|
||||
impl<F, T, U> MapSubsystem<T> for F where F: Fn(T) -> U {
|
||||
impl<F, T, U> MapSubsystem<T> for F
|
||||
where
|
||||
F: Fn(T) -> U,
|
||||
{
|
||||
type Output = U;
|
||||
|
||||
fn map_subsystem(&self, sub: T) -> U {
|
||||
@@ -178,10 +172,7 @@ pub struct MessagePacket<T> {
|
||||
|
||||
/// Create a packet from its parts.
|
||||
pub fn make_packet<T>(signals_received: usize, message: T) -> MessagePacket<T> {
|
||||
MessagePacket {
|
||||
signals_received,
|
||||
message,
|
||||
}
|
||||
MessagePacket { signals_received, message }
|
||||
}
|
||||
|
||||
/// Incoming messages from both the bounded and unbounded channel.
|
||||
@@ -190,7 +181,6 @@ pub type SubsystemIncomingMessages<M> = self::stream::Select<
|
||||
self::metered::UnboundedMeteredReceiver<MessagePacket<M>>,
|
||||
>;
|
||||
|
||||
|
||||
/// Watermark to track the received signals.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct SignalsReceived(Arc<AtomicUsize>);
|
||||
@@ -208,8 +198,6 @@ impl SignalsReceived {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// A trait to support the origin annotation
|
||||
/// such that errors across subsystems can be easier tracked.
|
||||
pub trait AnnotateErrorOrigin: 'static + Send + Sync + std::error::Error {
|
||||
@@ -227,12 +215,8 @@ pub trait AnnotateErrorOrigin: 'static + Send + Sync + std::error::Error {
|
||||
///
|
||||
/// In essence it's just a new type wrapping a `BoxFuture`.
|
||||
pub struct SpawnedSubsystem<E>
|
||||
where
|
||||
E: std::error::Error
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static
|
||||
+ From<self::OverseerError>,
|
||||
where
|
||||
E: std::error::Error + Send + Sync + 'static + From<self::OverseerError>,
|
||||
{
|
||||
/// Name of the subsystem being spawned.
|
||||
pub name: &'static str,
|
||||
@@ -274,7 +258,8 @@ pub enum OverseerError {
|
||||
/// An additional annotation tag for the origin of `source`.
|
||||
origin: &'static str,
|
||||
/// The wrapped error. Marked as source for tracking the error chain.
|
||||
#[source] source: Box<dyn 'static + std::error::Error + Send + Sync>
|
||||
#[source]
|
||||
source: Box<dyn 'static + std::error::Error + Send + Sync>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -303,7 +288,6 @@ impl SubsystemMeters {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Set of readouts of the `Meter`s of a subsystem.
|
||||
pub struct SubsystemMeterReadouts {
|
||||
#[allow(missing_docs)]
|
||||
@@ -377,7 +361,7 @@ pub trait SubsystemContext: Send + 'static {
|
||||
/// The sender type as provided by `sender()` and underlying.
|
||||
type Sender: SubsystemSender<Self::AllMessages> + Send + 'static;
|
||||
/// The error type.
|
||||
type Error: ::std::error::Error + ::std::convert::From< OverseerError > + Sync + Send + 'static;
|
||||
type Error: ::std::error::Error + ::std::convert::From<OverseerError> + Sync + Send + 'static;
|
||||
|
||||
/// Try to asynchronously receive a message.
|
||||
///
|
||||
@@ -392,7 +376,7 @@ pub trait SubsystemContext: Send + 'static {
|
||||
fn spawn(
|
||||
&mut self,
|
||||
name: &'static str,
|
||||
s: ::std::pin::Pin<Box<dyn crate::Future<Output = ()> + Send>>
|
||||
s: ::std::pin::Pin<Box<dyn crate::Future<Output = ()> + Send>>,
|
||||
) -> Result<(), Self::Error>;
|
||||
|
||||
/// Spawn a blocking child task on the executor's dedicated thread pool.
|
||||
@@ -404,22 +388,24 @@ pub trait SubsystemContext: Send + 'static {
|
||||
|
||||
/// Send a direct message to some other `Subsystem`, routed based on message type.
|
||||
async fn send_message<X>(&mut self, msg: X)
|
||||
where
|
||||
Self::AllMessages: From<X>,
|
||||
X: Send,
|
||||
where
|
||||
Self::AllMessages: From<X>,
|
||||
X: Send,
|
||||
{
|
||||
self.sender().send_message(<Self::AllMessages>::from(msg)).await
|
||||
}
|
||||
|
||||
/// Send multiple direct messages to other `Subsystem`s, routed based on message type.
|
||||
async fn send_messages<X, T>(&mut self, msgs: T)
|
||||
where
|
||||
T: IntoIterator<Item = X> + Send,
|
||||
T::IntoIter: Send,
|
||||
Self::AllMessages: From<X>,
|
||||
X: Send,
|
||||
where
|
||||
T: IntoIterator<Item = X> + Send,
|
||||
T::IntoIter: Send,
|
||||
Self::AllMessages: From<X>,
|
||||
X: Send,
|
||||
{
|
||||
self.sender().send_messages(msgs.into_iter().map(|x| <Self::AllMessages>::from(x))).await
|
||||
self.sender()
|
||||
.send_messages(msgs.into_iter().map(|x| <Self::AllMessages>::from(x)))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a message using the unbounded connection.
|
||||
@@ -449,10 +435,9 @@ where
|
||||
E: std::error::Error + Send + Sync + 'static + From<self::OverseerError>,
|
||||
{
|
||||
/// Start this `Subsystem` and return `SpawnedSubsystem`.
|
||||
fn start(self, ctx: Ctx) -> SpawnedSubsystem < E >;
|
||||
fn start(self, ctx: Ctx) -> SpawnedSubsystem<E>;
|
||||
}
|
||||
|
||||
|
||||
/// Sender end of a channel to interface with a subsystem.
|
||||
#[async_trait::async_trait]
|
||||
pub trait SubsystemSender<Message>: Send + Clone + 'static {
|
||||
@@ -461,7 +446,9 @@ pub trait SubsystemSender<Message>: Send + Clone + 'static {
|
||||
|
||||
/// Send multiple direct messages to other `Subsystem`s, routed based on message type.
|
||||
async fn send_messages<T>(&mut self, msgs: T)
|
||||
where T: IntoIterator<Item = Message> + Send, T::IntoIter: Send;
|
||||
where
|
||||
T: IntoIterator<Item = Message> + Send,
|
||||
T::IntoIter: Send;
|
||||
|
||||
/// Send a message onto the unbounded queue of some other `Subsystem`, routed based on message
|
||||
/// type.
|
||||
@@ -488,27 +475,27 @@ pub trait TimeoutExt: Future {
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Timeout {
|
||||
future: self,
|
||||
delay: Delay::new(duration),
|
||||
}
|
||||
Timeout { future: self, delay: Delay::new(duration) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> TimeoutExt for F where F: Future{}
|
||||
impl<F> TimeoutExt for F where F: Future {}
|
||||
|
||||
impl<F> Future for Timeout<F> where F: Future {
|
||||
impl<F> Future for Timeout<F>
|
||||
where
|
||||
F: Future,
|
||||
{
|
||||
type Output = Option<F::Output>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
|
||||
let this = self.project();
|
||||
|
||||
if this.delay.poll(ctx).is_ready() {
|
||||
return Poll::Ready(None);
|
||||
return Poll::Ready(None)
|
||||
}
|
||||
|
||||
if let Poll::Ready(output) = this.future.poll(ctx) {
|
||||
return Poll::Ready(Some(output));
|
||||
return Poll::Ready(Some(output))
|
||||
}
|
||||
|
||||
Poll::Pending
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
// The generated code requires quite a bit of surrounding code to work.
|
||||
// Please refer to [the examples](examples/dummy.rs) and
|
||||
// [the minimal usage example](../examples/minimal-example.rs).
|
||||
|
||||
Reference in New Issue
Block a user