use quote::{format_ident, quote};
use crate::{
emit::leading,
model::{
Grant, PollEntry, PollMode, RecordModel, default_polling_name, default_sweeps_name,
poll_grants_name,
},
};
struct Seat<'a> {
position: usize,
entry: &'a PollEntry,
lent: Option<Lent<'a>>,
handler: Option<syn::Ident>,
executor: Option<Executor>,
cell: Option<syn::Ident>,
}
struct Lent<'a> {
grants: &'a [Grant],
handles: Vec<syn::Ident>,
context: syn::Ident,
}
struct Executor {
parameter: syn::Ident,
field: syn::Ident,
asynchronous: bool,
shipped: Option<&'static str>,
}
struct Vocabulary {
seats: proc_macro2::TokenStream,
source: proc_macro2::TokenStream,
swept: proc_macro2::TokenStream,
async_tick: proc_macro2::TokenStream,
tick: proc_macro2::TokenStream,
spawn: proc_macro2::TokenStream,
async_spawn: proc_macro2::TokenStream,
}
impl RecordModel {
pub(super) fn polling_face(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
if self.polls.is_none() {
return Default::default();
}
let seats = self.seats();
let (record, vis) = (&self.record, &self.vis);
let mut types = proc_macro2::TokenStream::new();
let mut doors = proc_macro2::TokenStream::new();
for seat in &seats {
let (context, sockets) = self.clock_face(seat);
types.extend(context);
doors.extend(sockets);
}
let parameters = self.parameters(&seats);
let declaration = self.declared_parameters(&seats, ¶meters);
let lending = default_polling_name(record);
let fields: Vec<proc_macro2::TokenStream> = seats
.iter()
.flat_map(|seat| self.lending_fields(seat))
.collect();
let sealed = fields.is_empty();
let doc = leading(&format!(
"What a [`{record}`]'s ticks are LENT — one clock's context per `poll(…)` entry that wrote a \
`write` word, the citizen each mounted entry runs, and the executor each detached one runs \
on."
));
let seat_note = leading(
"A tick reaches ONE of these seats, the one its own clock owns, and the runtime is what \
picks: a sweep never sees this value. A clock that granted nothing and mounted nothing holds \
no field here and needs none. What it all buys is that deleting a clock deletes its grants \
and its citizen, because they were never anywhere else.",
);
let sealed_note = leading(
"SEALED and EMPTY, because no clock of this node was granted a store or mounted a citizen — \
there is no state a deployment could put here and none it could take out. It exists so that \
`Resident::polling` takes the same kind of value from every polling node, and so that a \
later `write` or `handler` word is a field rather than a new type.",
);
types.extend(if sealed {
quote! {
#[doc = #doc]
#[doc = ""]
#[doc = #sealed_note]
#[derive(::core::fmt::Debug, ::core::default::Default)]
#vis struct #lending(());
}
} else {
{
let declared = angled(&declaration);
quote! {
#[doc = #doc]
#[doc = ""]
#[doc = #seat_note]
#vis struct #lending #declared {
#(#fields)*
}
}
}
});
if !sealed {
doors.extend(self.lending_debug(&lending, &seats, ¶meters));
}
types.extend(self.sweep_trait(&seats));
doors.extend(self.lending_doors(&lending, &seats, ¶meters, sealed));
(types, doors)
}
fn seats(&self) -> Vec<Seat<'_>> {
let Some(polls) = self.polls.as_ref() else {
return Vec::new();
};
let mut minted: Vec<syn::Ident> = Vec::new();
let mut seats = Vec::with_capacity(polls.entries.len());
for (position, entry) in polls.entries.iter().enumerate() {
let lent = entry.grants.as_ref().map(|grants| {
let grants = grants.grants.as_slice();
let handles = grants
.iter()
.map(|grant| {
let bare = handle(grant, None);
let name = if minted.contains(&bare) {
handle(grant, Some(&entry.variant))
} else {
bare
};
minted.push(name.clone());
name
})
.collect();
Lent {
grants,
handles,
context: poll_grants_name(&self.record, &entry.variant),
}
});
let handler = entry
.mounted()
.then(|| format_ident!("{}_handler", entry.name));
let executor = entry.mode.detached().then(|| Executor {
parameter: format_ident!("{}Executor", entry.variant),
field: format_ident!("{}_executor", entry.name),
asynchronous: !entry.mode.blocking(),
shipped: match entry.mode {
PollMode::Spawn => Some("Thread"),
PollMode::Rayon => Some("Rayon"),
_ => None,
},
});
let cell = (entry.mode.lapses() && !entry.concurrent)
.then(|| format_ident!("{}_in_flight", entry.name));
seats.push(Seat {
position,
entry,
lent,
handler,
executor,
cell,
});
}
seats
}
fn parameters<'a>(&self, seats: &'a [Seat<'a>]) -> Vec<&'a syn::Ident> {
let mut parameters: Vec<&syn::Ident> = seats
.iter()
.filter_map(|seat| seat.lent.as_ref())
.flat_map(|lent| lent.handles.iter())
.collect();
let engines = || seats.iter().filter_map(|seat| seat.executor.as_ref());
parameters.extend(
engines()
.filter(|engine| engine.asynchronous)
.chain(engines().filter(|engine| !engine.asynchronous))
.map(|engine| &engine.parameter),
);
parameters
}
fn declared_parameters(
&self,
seats: &[Seat<'_>],
parameters: &[&syn::Ident],
) -> Vec<proc_macro2::TokenStream> {
parameters
.iter()
.map(|parameter| {
let shipped = seats
.iter()
.filter_map(|seat| seat.executor.as_ref())
.find(|engine| &&engine.parameter == parameter)
.and_then(|engine| engine.shipped);
match shipped {
Some(shipped) => {
let citizen = self.framework(&["drive"], shipped);
quote!(#parameter = #citizen)
}
None => quote!(#parameter),
}
})
.collect()
}
fn clock_face(&self, seat: &Seat<'_>) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let (record, vis) = (&self.record, &self.vis);
let Some(Lent {
grants,
handles,
context,
}) = seat.lent.as_ref()
else {
return Default::default();
};
let name = &seat.entry.name;
let doc = leading(&format!(
"What a [`{record}`]'s `{name}` ticks are LENT — one write socket per grant the `{name}` \
entry wrote, holding the handle that grant reaches."
));
let teeth_note = leading(&format!(
"A store the `{name}` entry did NOT grant has no `AsyncLands` impl here, so a tick reaching for \
one is `E0277` at the line that reached — INCLUDING a store a sibling clock was granted, \
which is the whole of what seating the word in the entry buys. The capability is a bound \
this type satisfies rather than anything checked at run time."
));
let held_note = leading(
"One type parameter per grant, in the order the entry granted them, because what a write \
handle IS belongs to whoever opened it. The bound sits on the forwarding impl, where it is \
spent. The runtime holds this value inside the node's lending and lends it per tick; the \
node struct holds only its own state.",
);
let clone_note = leading(
"`Clone` is derived so that a DETACHED clock can be handed an owned context per tick. The \
bound falls on the handles, so a context whose handles are not cloneable simply has no \
`Clone` — and a detached mode over it is refused at the declaration that wrote the word.",
);
let fields = grants.iter().zip(handles).map(|(grant, handle)| {
let mount = grant.mount.safe();
let doc = leading(&format!(
"The handle `{}`'s store is written through.",
path_text(&grant.node),
));
quote! {
#[doc = #doc]
#mount: #handle,
}
});
let types = quote! {
#[doc = #doc]
#[doc = ""]
#[doc = #teeth_note]
#[doc = ""]
#[doc = #held_note]
#[doc = ""]
#[doc = #clone_note]
#[derive(::core::fmt::Debug, ::core::clone::Clone)]
#vis struct #context<#(#handles),*> {
#(#fields)*
}
};
let taken = grants.iter().zip(handles).map(|(grant, handle)| {
let mount = grant.mount.safe();
quote!(#mount: #handle)
});
let held = grants.iter().map(|grant| {
let mount = grant.mount.safe();
quote!(#mount,)
});
let new_doc = leading(&format!(
"Hold these handles for a [`{record}`]'s `{name}` ticks, in the order the entry granted \
them.\n\nBuilding one is the moment a deployment decides what each of this clock's grants \
actually reaches — and two clocks granted one store build two of these, so they may be given \
two different handles onto it."
));
let sockets = self.clock_sockets(context, grants, handles);
let doors = quote! {
impl<#(#handles),*> #context<#(#handles),*> {
#[doc = #new_doc]
#[allow(clippy::too_many_arguments)]
#[inline]
#[must_use]
#vis const fn new(#(#taken),*) -> Self {
Self { #(#held)* }
}
}
#sockets
};
(types, doors)
}
fn clock_sockets(
&self,
context: &syn::Ident,
grants: &[Grant],
handles: &[syn::Ident],
) -> proc_macro2::TokenStream {
let async_lands = self.framework(&["drive"], "AsyncLands");
let lands = self.framework(&["drive"], "Lands");
let commit = self.framework(&["drive"], "Commit");
let sockets = grants.iter().zip(handles).map(|(grant, handle)| {
let (mount, node) = (grant.mount.safe(), &grant.node);
let named = path_text(node);
let doc = leading(&format!(
"The `write = \"{named}\"` grant, as the write socket this clock's ASYNC ticks call.\n\nA \
clock that did not grant `{named}` mints no impl, so reaching for it is an unsatisfied \
bound at the line that reached rather than a permission refused at run time."
));
let blocking_doc = leading(&format!(
"The `write = \"{named}\"` grant, as the write socket this clock's SYNC ticks call.\n\nIt \
exists only where the handle a deployment installed can land without awaiting — the \
engine's own fact — so a `block`, `spawn` or `rayon` tick over an async-only handle is an \
unsatisfied bound naming both roads."
));
quote! {
#[doc = #doc]
impl<#(#handles),*> #async_lands<#node> for #context<#(#handles),*>
where
#handle: #async_lands<#node>,
{
type Error = <#handle as #async_lands<#node>>::Error;
#[inline]
fn land(
&mut self,
items: &[#node],
) -> impl ::core::future::Future<Output = #commit<Self::Error>> + ::core::marker::Send
{
<#handle as #async_lands<#node>>::land(&mut self.#mount, items)
}
}
#[doc = #blocking_doc]
impl<#(#handles),*> #lands<#node> for #context<#(#handles),*>
where
#handle: #lands<#node>,
{
type Error = <#handle as #lands<#node>>::Error;
#[inline]
fn land(&mut self, items: &[#node]) -> #commit<Self::Error> {
<#handle as #lands<#node>>::land(&mut self.#mount, items)
}
}
}
});
quote!(#(#sockets)*)
}
fn sweep_trait(&self, seats: &[Seat<'_>]) -> proc_macro2::TokenStream {
let (record, vis) = (&self.record, &self.vis);
let sweeping: Vec<&Seat<'_>> = seats.iter().filter(|seat| !seat.entry.mounted()).collect();
if sweeping.is_empty() {
return proc_macro2::TokenStream::new();
}
let sweeps = default_sweeps_name(record);
let generics = angled(&swept_held(seats));
let answer = quote! {
impl ::core::future::Future<Output = ::core::result::Result<Self::Info, Self::Error>>
+ ::core::marker::Send
};
let entries = sweeping.iter().map(|seat| {
let name = &seat.entry.name;
let world = if seat.entry.mode.blocking() {
"It runs where the driver runs, so its answer is a plain `Result`."
} else {
"It is awaited in the driver's own loop."
};
let taken = seat.lent.as_ref().map(|lent| {
let (context, handles) = (&lent.context, &lent.handles);
quote!(, grants: &mut #context<#(#handles),*>)
});
let granted = match seat.lent.as_ref() {
Some(lent) => format!(
"Its context lands {} and nothing else.",
lent
.grants
.iter()
.map(|grant| format!("`{}`", path_text(&grant.node)))
.collect::<Vec<_>>()
.join(", ")
),
None => "Its entry granted nothing, so it is lent nothing — a clock that only looks, or \
that works through what the node value already holds."
.to_owned(),
};
let doc = leading(&format!(
"The `{name}` clock came due, and it runs `{}`. {granted}\n\n{world}\n\nNo position is \
passed, because there is nothing left to tell apart: this entry IS the clock.",
seat.entry.mode.as_str()
));
if seat.entry.mode.blocking() {
quote! {
#[doc = #doc]
fn #name(&mut self #taken) -> ::core::result::Result<Self::Info, Self::Error>;
}
} else {
quote! {
#[doc = #doc]
fn #name(&mut self #taken) -> #answer;
}
}
});
let sweeps_doc = leading(&format!(
"What a [`{record}`]'s operator does when one of its `light` clocks comes due — one entry \
per such clock, each lent that clock's own grants, and a clock that granted nothing lent \
nothing."
));
let split_note = leading(
"A clock that wrote `handler = \"…\"` has NO entry here: its body is a citizen the deployment \
built rather than a method on the node. A node whose every clock mounted one emits no trait \
at all.",
);
let answer_note = leading(
"ONE `Info` and ONE `Error` for the whole node, because the resident has one observation \
stream and one effect table. Two clocks answering in two types is not a thing that can be \
true, so it is not a thing that can be written: a second `type Info` in this impl is \
`E0201`. An INLINE mounted citizen is bound to this same pair on the route, so it cannot \
disagree either.",
);
let missing_note = leading(
"A clock whose entry is never written is `E0046` at the impl block, missing the poll's own \
word — the declaration's `light` clocks and the operator's entries are the same list, \
checked by the compiler at the place an author would fix it.",
);
quote! {
#[doc = #sweeps_doc]
#[doc = ""]
#[doc = #split_note]
#[doc = ""]
#[doc = #answer_note]
#[doc = ""]
#[doc = #missing_note]
#vis trait #sweeps #generics {
type Info;
type Error;
#(#entries)*
}
}
}
fn lending_debug(
&self,
lending: &syn::Ident,
seats: &[Seat<'_>],
parameters: &[&syn::Ident],
) -> proc_macro2::TokenStream {
let generics = angled(parameters);
let named = lending.to_string();
let handles: Vec<&syn::Ident> = seats
.iter()
.filter_map(|seat| seat.lent.as_ref())
.flat_map(|lent| lent.handles.iter())
.collect();
let shown = seats.iter().filter(|seat| seat.lent.is_some()).map(|seat| {
let (field, spelled) = (&seat.entry.name, seat.entry.name.to_string());
quote!(.field(#spelled, &self.#field))
});
let hidden = seats
.iter()
.any(|seat| seat.handler.is_some() || seat.executor.is_some() || seat.cell.is_some());
let ending = if hidden {
quote!(.finish_non_exhaustive())
} else {
quote!(.finish())
};
let printable = (!handles.is_empty()).then(|| quote!(where #(#handles: ::core::fmt::Debug,)*));
quote! {
impl #generics ::core::fmt::Debug for #lending #generics
#printable
{
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.debug_struct(#named)
#(#shown)*
#ending
}
}
}
}
fn lending_fields(&self, seat: &Seat<'_>) -> Vec<proc_macro2::TokenStream> {
let name = &seat.entry.name;
let mut fields = Vec::new();
if let Some(lent) = seat.lent.as_ref() {
let (context, handles) = (&lent.context, &lent.handles);
let doc = leading(&format!("What the `{name}` clock's ticks are lent."));
fields.push(quote! {
#[doc = #doc]
#name: #context<#(#handles),*>,
});
}
if let (Some(field), Some(mounted)) = (seat.handler.as_ref(), seat.entry.body.citizen()) {
let doc = leading(&format!(
"The citizen the `{name}` clock ticks — `handler = \"{}\"`.",
path_text(mounted)
));
fields.push(quote! {
#[doc = #doc]
#field: #mounted,
});
}
if let Some(engine) = seat.executor.as_ref() {
let (field, parameter) = (&engine.field, &engine.parameter);
let doc = leading(&format!(
"Where the `{name}` clock's detached ticks run. The `{}` word selects {}; a deployment \
holding a pool of its own names that type here instead, which is what makes the executor a \
seam rather than a vocabulary.",
seat.entry.mode.as_str(),
match engine.shipped {
Some(shipped) => format!("the shipped `{shipped}`"),
None => "whichever executor the deployment installed".to_owned(),
}
));
fields.push(quote! {
#[doc = #doc]
#field: #parameter,
});
}
if let Some(cell) = seat.cell.as_ref() {
let cell_type = self.framework(&["drive"], "AtMostOne");
let doc = leading(&format!(
"AT MOST ONE `{name}` tick in flight. The default for a detached SYNC clock, because a \
thread that waits is a stack: a tick arriving while its predecessor still runs is skipped, \
and says so. `concurrent` on the entry removes this field."
));
fields.push(quote! {
#[doc = #doc]
#cell: #cell_type,
});
}
fields
}
fn lending_doors(
&self,
lending: &syn::Ident,
seats: &[Seat<'_>],
parameters: &[&syn::Ident],
sealed: bool,
) -> proc_macro2::TokenStream {
let (record, vis) = (&self.record, &self.vis);
let generics = angled(parameters);
let new_doc = leading(&format!(
"Hold one context per granting clock, one citizen per mounted clock and one executor per \
detached clock, in the order [`{record}`] declared them.\n\nThis is the value handed to \
`Resident::polling`. Each clock's context was built separately, which is where a deployment \
decided what that clock reaches; each executor is named here, which is where a deployment \
displaces a shipped one."
));
let constructor = if sealed {
let sealed_doc = leading(&format!(
"The lending a [`{record}`] needs — which is nothing, because no clock of it was granted a \
store or mounted a citizen."
));
quote! {
impl #lending {
#[doc = #sealed_doc]
#[inline]
#[must_use]
#vis const fn new() -> Self {
Self(())
}
}
}
} else {
let taken = seats.iter().flat_map(Seat::taken);
let stored = seats.iter().flat_map(Seat::stored);
let constness = seats
.iter()
.all(|seat| seat.cell.is_none())
.then(|| quote!(const));
quote! {
impl #generics #lending #generics {
#[doc = #new_doc]
#[allow(clippy::too_many_arguments)]
#[inline]
#[must_use]
#vis #constness fn new(#(#taken),*) -> Self {
Self { #(#stored)* }
}
}
}
};
let seam = self.route(lending, seats, parameters, sealed);
quote! {
#constructor
#seam
}
}
fn route(
&self,
lending: &syn::Ident,
seats: &[Seat<'_>],
parameters: &[&syn::Ident],
sealed: bool,
) -> proc_macro2::TokenStream {
let record = &self.record;
let sweeps = default_sweeps_name(record);
let words = Vocabulary {
seats: self.framework(&["drive"], "Seats"),
source: self.framework(&["drive"], "PollUpstream"),
swept: self.framework(&["drive"], "Swept"),
async_tick: self.framework(&["drive"], "AsyncTick"),
tick: self.framework(&["drive"], "Tick"),
spawn: self.framework(&["drive"], "Spawn"),
async_spawn: self.framework(&["drive"], "AsyncSpawn"),
};
let send = quote!(::core::marker::Send);
let swept = swept_held(seats);
let swept_generics = angled(&swept);
let sweeping = seats.iter().any(|seat| !seat.entry.mounted());
let anchor = seats
.iter()
.find(|seat| seat.entry.mounted() && !seat.entry.mode.detached());
let (info, error) = if let Some(seat) = anchor {
let mounted = seat.entry.body.citizen().expect("a mounted seat");
let (face, context) = (seat.face(&words), seat.context());
(
quote!(<#mounted as #face<#context>>::Info),
quote!(<#mounted as #face<#context>>::Error),
)
} else if sweeping {
(
quote!(<O as #sweeps #swept_generics>::Info),
quote!(<O as #sweeps #swept_generics>::Error),
)
} else {
(quote!(()), quote!(::core::convert::Infallible))
};
let mut bounds: Vec<proc_macro2::TokenStream> = vec![match (sweeping, anchor.is_some()) {
(true, true) => quote!(O: #sweeps<#(#swept,)* Info = #info, Error = #error> + #send),
(true, false) => quote!(O: #sweeps #swept_generics + #send),
(false, _) => quote!(O: #send),
}];
for handle in seats
.iter()
.filter_map(|seat| seat.lent.as_ref())
.flat_map(|lent| lent.handles.iter())
{
bounds.push(quote!(#handle: #send));
}
for seat in seats {
if let Some(engine) = seat.executor.as_ref() {
let (parameter, seam) = (
&engine.parameter,
if engine.asynchronous {
&words.async_spawn
} else {
&words.spawn
},
);
bounds.push(quote!(#parameter: #seam + #send));
}
let Some(mounted) = seat.entry.body.citizen() else {
continue;
};
let (face, context) = (seat.face(&words), seat.context());
if seat.entry.mode.detached() {
bounds.push(quote!(#mounted: #face<#context> + ::core::clone::Clone + #send + 'static));
if seat.lent.is_some() {
bounds.push(quote!(#context: ::core::clone::Clone + #send + 'static));
}
} else if anchor.is_some_and(|first| first.position == seat.position) {
bounds.push(quote!(#mounted: #face<#context>));
} else {
bounds.push(quote!(#mounted: #face<#context, Info = #info, Error = #error>));
}
}
let arms = seats
.iter()
.map(|seat| seat.arm(&sweeps, &swept_generics, &words));
let unrouted = format!(
"a `{record}` tick from a position its own schedule never minted — the arms below are every \
clock the declaration wrote, so reaching this line means a source was rung against the wrong \
node"
);
let seats_doc = leading(
"Seat `operator` at the clock that rang, and run what that clock declared.\n\nEvery clock the \
declaration wrote has an arm: an unmounted one calls the operator's own entry, a mounted one \
runs its citizen, and the entry's mode decides whether that happens here or on an \
executor.\n\nThe receiver is the LENDING and not the operator, and that is forced rather \
than chosen: the bridge from a position to a per-clock entry can only be a blanket over the \
operator, and such an impl is `E0210` — an uncovered type parameter before the first local \
type. Written this way round the self type is local and the impl is legal.",
);
let operator = if sweeping {
quote!(operator)
} else {
quote!(_operator)
};
let generics = angled(parameters);
let (subject, all) = if sealed {
(quote!(#lending), quote!(<O>))
} else {
(quote!(#lending #generics), quote!(<O, #(#parameters),*>))
};
let (seats_trait, source, swept) = (&words.seats, &words.source, &words.swept);
quote! {
impl #all #seats_trait<O> for #subject
where
#(#bounds,)*
{
type Error = #error;
type Info = #info;
#[doc = #seats_doc]
async fn seat(
&mut self,
#operator: &mut O,
source: #source,
) -> ::core::result::Result<#swept<Self::Info>, Self::Error> {
match source.index() {
#(#arms)*
_ => ::core::unreachable!(#unrouted),
}
}
}
}
}
pub(super) fn declared_grants(&self) -> Vec<proc_macro2::TokenStream> {
let grant = self.framework(&["drive"], "Grant");
self
.polls
.iter()
.flat_map(|polls| polls.granting())
.flat_map(|(_, entry)| {
let clock = entry.name.to_string();
entry
.grants
.iter()
.flat_map(|grants| &grants.grants)
.map(move |granted| (clock.clone(), granted))
})
.map(|(clock, granted)| {
let node = &granted.node;
let named = path_text(node);
quote!(#grant::of::<#node>(#clock, #named))
})
.collect()
}
}
impl Seat<'_> {
fn face<'a>(&self, words: &'a Vocabulary) -> &'a proc_macro2::TokenStream {
if self.entry.mode.blocking() {
&words.tick
} else {
&words.async_tick
}
}
fn context(&self) -> proc_macro2::TokenStream {
match self.lent.as_ref() {
Some(lent) => {
let (context, handles) = (&lent.context, &lent.handles);
quote!(#context<#(#handles),*>)
}
None => quote!(()),
}
}
fn taken(&self) -> Vec<proc_macro2::TokenStream> {
let mut taken = Vec::new();
if let Some(lent) = self.lent.as_ref() {
let (name, context, handles) = (&self.entry.name, &lent.context, &lent.handles);
taken.push(quote!(#name: #context<#(#handles),*>));
}
if let (Some(field), Some(mounted)) = (self.handler.as_ref(), self.entry.body.citizen()) {
taken.push(quote!(#field: #mounted));
}
if let Some(engine) = self.executor.as_ref() {
let (field, parameter) = (&engine.field, &engine.parameter);
taken.push(quote!(#field: #parameter));
}
taken
}
fn stored(&self) -> Vec<proc_macro2::TokenStream> {
let mut stored = Vec::new();
if self.lent.is_some() {
let name = &self.entry.name;
stored.push(quote!(#name,));
}
if let Some(field) = self.handler.as_ref() {
stored.push(quote!(#field,));
}
if let Some(engine) = self.executor.as_ref() {
let field = &engine.field;
stored.push(quote!(#field,));
}
if let Some(cell) = self.cell.as_ref() {
stored.push(quote!(#cell: ::core::default::Default::default(),));
}
stored
}
fn arm(
&self,
sweeps: &syn::Ident,
swept_generics: &proc_macro2::TokenStream,
words: &Vocabulary,
) -> proc_macro2::TokenStream {
let (index, name, swept) = (self.position, &self.entry.name, &words.swept);
let Some(mounted) = self.entry.body.citizen() else {
let lent = self.lent.as_ref().map(|_| quote!(, &mut self.#name));
let call = quote!(<O as #sweeps #swept_generics>::#name(operator #lent));
return if self.entry.mode.blocking() {
quote!(#index => #call.map(#swept::Ran),)
} else {
quote!(#index => #call.await.map(#swept::Ran),)
};
};
let handler = self
.handler
.as_ref()
.expect("a mounted seat holds a citizen");
let (face, context) = (self.face(words), self.context());
let tick = quote!(<#mounted as #face<#context>>::tick);
let ungranted = self.lent.is_none().then(|| quote!(let mut ungranted = ();));
let lent = match self.lent.as_ref() {
Some(_) => quote!(&mut self.#name),
None => quote!(&mut ungranted),
};
if !self.entry.mode.detached() {
let call = if self.entry.mode.blocking() {
quote!(#tick(&mut self.#handler, #lent))
} else {
quote!(#tick(&mut self.#handler, #lent).await)
};
return quote! {
#index => {
#ungranted
#call.map(#swept::Ran)
}
};
}
let engine = self.executor.as_ref().expect("a detached seat holds one");
let field = &engine.field;
let claim = self.cell.as_ref().map(|cell| {
quote! {
let claim = match self.#cell.claim() {
::core::option::Option::Some(claim) => claim,
::core::option::Option::None => {
return ::core::result::Result::Ok(#swept::Lapped);
}
};
}
});
let held = self.cell.as_ref().map(|_| quote!(let _claim = claim;));
let grants = match self.lent.as_ref() {
Some(_) => quote!(let mut grants = ::core::clone::Clone::clone(&self.#name);),
None => quote!(let mut grants = ();),
};
let (spawn, async_spawn) = (&words.spawn, &words.async_spawn);
if engine.asynchronous {
quote! {
#index => {
#claim
let mut handler = ::core::clone::Clone::clone(&self.#handler);
#grants
#async_spawn::spawn(&self.#field, async move {
#held
let _ = #tick(&mut handler, &mut grants).await;
});
::core::result::Result::Ok(#swept::Dispatched)
}
}
} else {
quote! {
#index => {
#claim
let mut handler = ::core::clone::Clone::clone(&self.#handler);
#grants
#spawn::spawn(&self.#field, move || {
#held
let _ = #tick(&mut handler, &mut grants);
});
::core::result::Result::Ok(#swept::Dispatched)
}
}
}
}
}
fn swept_held<'a>(seats: &'a [Seat<'a>]) -> Vec<&'a syn::Ident> {
seats
.iter()
.filter(|seat| !seat.entry.mounted())
.filter_map(|seat| seat.lent.as_ref())
.flat_map(|lent| lent.handles.iter())
.collect()
}
fn angled<T: quote::ToTokens>(parameters: &[T]) -> proc_macro2::TokenStream {
if parameters.is_empty() {
proc_macro2::TokenStream::new()
} else {
quote!(<#(#parameters),*>)
}
}
fn handle(grant: &Grant, clock: Option<&syn::Ident>) -> syn::Ident {
let segment = &grant
.node
.segments
.last()
.expect("a path has at least one segment")
.ident;
match clock {
Some(clock) => format_ident!("{clock}{segment}Handle"),
None => format_ident!("{segment}Handle"),
}
}
fn path_text(path: &syn::Path) -> String {
path
.segments
.iter()
.map(|segment| segment.ident.to_string())
.collect::<Vec<_>>()
.join("::")
}
#[cfg(test)]
mod bound_tests;
#[cfg(test)]
mod registered_tests;
#[cfg(test)]
mod tests;