1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Generates the bounds for a particular subsystem `Context` and associate `type Sender`.
//!
//!
//! ## Implement `trait Subsystem<Context, Error>` via `subsystem`
//!
//! ```ignore
//! # use orchestra_proc_macro::subsystem;
//! # mod somewhere {
//! # use orchestra_proc_macro::orchestra;
//! # pub use orchestra::*;
//! #
//! # #[derive(Debug, thiserror::Error)]
//! # #[error("Yikes!")]
//! # pub struct Yikes;
//! # impl From<OrchestraError> for Yikes {
//! #   fn from(_: OrchestraError) -> Yikes { Yikes }
//! # }
//! # impl From<mpsc::SendError> for Yikes {
//! #   fn from(_: mpsc::SendError) -> Yikes { Yikes }
//! # }
//! #
//! # #[derive(Debug)]
//! # pub struct Eve;
//! #
//! # #[derive(Debug, Clone)]
//! # pub struct Sig;
//! #
//! # #[derive(Debug, Clone, Copy)]
//! # pub struct A;
//! # #[derive(Debug, Clone, Copy)]
//! # pub struct B;
//! #
//! # #[orchestra(signal=Sig, gen=AllOfThem, event=Eve, error=Yikes)]
//! # pub struct Wonderland {
//! # 	#[subsystem(A, sends: [B])]
//! # 	foo: Foo,
//! # 	#[subsystem(B, sends: [A])]
//! # 	bar: Bar,
//! # }
//! # }
//! # use somewhere::{Yikes, SpawnedSubsystem};
//! #
//! # struct FooSubsystem;
//! #
//! #[subsystem(Foo, error = Yikes, prefix = somewhere)]
//! impl<Context> FooSubsystem {
//!    fn start(self, context: Context) -> SpawnedSubsystem<Yikes> {
//!	       // ..
//!        # let _ = context;
//!        # unimplemented!()
//!    }
//! }
//! ```
//!
//! expands to
//!
//! ```ignore
//! # use orchestra_proc_macro::subsystem;
//! # mod somewhere {
//! # use orchestra_proc_macro::orchestra;
//! # pub use orchestra::*;
//! #
//! # #[derive(Debug, thiserror::Error)]
//! # #[error("Yikes!")]
//! # pub struct Yikes;
//! # impl From<OrchestraError> for Yikes {
//! #   fn from(_: OrchestraError) -> Yikes { Yikes }
//! # }
//! # impl From<mpsc::SendError> for Yikes {
//! #   fn from(_: mpsc::SendError) -> Yikes { Yikes }
//! # }
//! #
//! # #[derive(Debug)]
//! # pub struct Eve;
//! #
//! # #[derive(Debug, Clone)]
//! # pub struct Sig;
//! #
//! # #[derive(Debug, Clone, Copy)]
//! # pub struct A;
//! # #[derive(Debug, Clone, Copy)]
//! # pub struct B;
//! #
//! # #[orchestra(signal=Sig, gen=AllOfThem, event=Eve, error=Yikes)]
//! # pub struct Wonderland {
//! # 	#[subsystem(A, sends: [B])]
//! # 	foo: Foo,
//! # 	#[subsystem(B, sends: [A])]
//! # 	bar: Bar,
//! # }
//! # }
//! # use somewhere::{Yikes, SpawnedSubsystem};
//! # use orchestra as support_crate;
//! #
//! # struct FooSubsystem;
//! #
//! impl<Context> support_crate::Subsystem<Context, Yikes> for FooSubsystem
//! where
//! 	Context: somewhere::FooContextTrait,
//!     Context: support_crate::SubsystemContext,
//!		<Context as somewhere::FooContextTrait>::Sender: somewhere::FooSenderTrait,
//!		<Context as support_crate::SubsystemContext>::Sender: somewhere::FooSenderTrait,
//! {
//!       fn start(self, context: Context) -> SpawnedSubsystem<Yikes> {
//!        // ..
//!        # let _ = context;
//!        # unimplemented!()
//!       }
//! }
//! ```
//!
//! where `support_crate` is either equivalent to `somewhere` or derived from the cargo manifest.
//!
//!
//! ## Add additional trait bounds for a generic `Context` via `contextbounds`
//!
//! ### To an `ImplItem`
//!
//! ```ignore
//! #[contextbounds(Foo, prefix = somewhere)]
//! impl<Context> X {
//! ..
//! }
//! ```
//!
//! expands to
//!
//! ```ignore
//! impl<Context> X
//! where
//! 	Context: somewhere::FooSubsystemTrait,
//!     Context: support_crate::SubsystemContext,
//!		<Context as somewhere::FooContextTrait>::Sender: somewhere::FooSenderTrait,
//!		<Context as support_crate::SubsystemContext>::Sender: somewhere::FooSenderTrait,
//! {
//! }
//! ```
//!
//! ### To a free standing `Fn` (not a method, that's covered by the above)
//!
//! ```ignore
//! #[contextbounds(Foo, prefix = somewhere)]
//! fn do_smth<Context>(context: &mut Context) {
//! ..
//! }
//! ```
//!
//! expands to
//!
//! ```ignore
//! fn do_smth<Context>(context: &mut Context)
//! where
//! 	Context: somewhere::FooSubsystemTrait,
//!     Context: support_crate::SubsystemContext,
//!		<Context as somewhere::FooContextTrait>::Sender: somewhere::FooSenderTrait,
//!		<Context as support_crate::SubsystemContext>::Sender: somewhere::FooSenderTrait,
//! {
//! }
//! ```
use proc_macro2::TokenStream;
use quote::{format_ident, ToTokens};
use syn::{parse2, parse_quote, punctuated::Punctuated, Result};

use super::{parse::*, *};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MakeSubsystem {
	/// Implements `trait Subsystem` and apply the trait bounds to the `Context` generic.
	///
	/// Relevant to `impl Item` only.
	ImplSubsystemTrait,
	/// Only apply the trait bounds to the context.
	AddContextTraitBounds,
}

pub(crate) fn impl_subsystem_context_trait_bounds(
	attr: TokenStream,
	orig: TokenStream,
	make_subsystem: MakeSubsystem,
) -> Result<proc_macro2::TokenStream> {
	let args = parse2::<SubsystemAttrArgs>(attr.clone())?;
	let span = args.span();
	let SubsystemAttrArgs { error_path, subsystem_ident, trait_prefix_path, .. } = args;

	let mut item = parse2::<syn::Item>(orig)?;

	// always prefer the direct usage, if it's not there, let's see if there is
	// a `prefix=*` provided. Either is ok.

	// Technically this is two different things:
	// The place where the `#[orchestra]` is annotated is where all `trait *SenderTrait` and
	// `trait *ContextTrait` types exist.
	// The other usage is the true support crate `orchestra`, where the static ones
	// are declared.
	// Right now, if the `support_crate` is not included, it falls back silently to the `trait_prefix_path`.
	let support_crate = support_crate()
		.or_else(|_e| {
			trait_prefix_path.clone().ok_or_else(|| {
				syn::Error::new(attr.span(), "Couldn't find `orchestra` in manifest, but also missing a `prefix=` to help trait bound resolution")
			})
		})?;

	let trait_prefix_path = trait_prefix_path.unwrap_or_else(|| parse_quote! { self });
	if trait_prefix_path.segments.trailing_punct() {
		return Err(syn::Error::new(trait_prefix_path.span(), "Must not end with `::`"))
	}

	let subsystem_ctx_trait = format_ident!("{}ContextTrait", subsystem_ident);
	let subsystem_sender_trait = format_ident!("{}SenderTrait", subsystem_ident);

	let extra_where_predicates: Punctuated<syn::WherePredicate, syn::Token![,]> = parse_quote! {
		Context: #trait_prefix_path::#subsystem_ctx_trait,
		Context: #support_crate::SubsystemContext,
		<Context as #trait_prefix_path::#subsystem_ctx_trait>::Sender: #trait_prefix_path::#subsystem_sender_trait,
		<Context as #support_crate::SubsystemContext>::Sender: #trait_prefix_path::#subsystem_sender_trait,
	};

	let apply_ctx_bound_if_present = move |generics: &mut syn::Generics| -> bool {
		if generics
			.params
			.iter()
			.find(|generic| match generic {
				syn::GenericParam::Type(ty) if ty.ident == "Context" => true,
				_ => false,
			})
			.is_some()
		{
			let where_clause = generics.make_where_clause();
			where_clause.predicates.extend(extra_where_predicates.clone());
			true
		} else {
			false
		}
	};

	match item {
		syn::Item::Impl(ref mut struktured_impl) => {
			if make_subsystem == MakeSubsystem::ImplSubsystemTrait {
				let error_path = error_path.ok_or_else(|| {
					syn::Error::new(
						span,
						"Must annotate the identical orchestra error type via `error=..`.",
					)
				})?;
				// Only replace the subsystem trait if it's desired.
				struktured_impl.trait_.replace((
					None,
					parse_quote! {
						#support_crate::Subsystem<Context, #error_path>
					},
					syn::token::For::default(),
				));
			}

			apply_ctx_bound_if_present(&mut struktured_impl.generics);
			for item in struktured_impl.items.iter_mut() {
				match item {
					syn::ImplItem::Method(method) => {
						apply_ctx_bound_if_present(&mut method.sig.generics);
					},
					_others => {
						// don't error, just nop
					},
				}
			}
		},
		syn::Item::Fn(ref mut struktured_fn) => {
			if make_subsystem == MakeSubsystem::ImplSubsystemTrait {
				return Err(syn::Error::new(struktured_fn.span(), "Cannot make a free function a subsystem, did you mean to apply `contextbound` instead?"));
			}
			apply_ctx_bound_if_present(&mut struktured_fn.sig.generics);
		},
		other =>
			return Err(syn::Error::new(
				other.span(),
				"Macro can only be annotated on functions or struct implementations",
			)),
	};

	Ok(item.to_token_stream())
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn is_path() {
		let _p: Path = parse_quote! { self };
		let _p: Path = parse_quote! { crate };
		let _p: Path = parse_quote! { ::foo };
		let _p: Path = parse_quote! { bar };
	}
}