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
// 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.

use super::kw;
use proc_macro2::Span;
use quote::{quote, ToTokens};
use std::collections::{hash_map::RandomState, HashMap};
use syn::{
	parse::{Parse, ParseBuffer},
	punctuated::Punctuated,
	spanned::Spanned,
	Error, Ident, LitBool, LitInt, Path, Result, Token,
};

#[derive(Clone, Debug)]
enum OrchestraAttrItem {
	ExternEventType { tag: kw::event, eq_token: Token![=], value: Path },
	ExternOrchestraSignalType { 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 },
	BoxedMessages { tag: kw::boxed_messages, eq_token: Token![=], value: bool },
	SignalChannelCapacity { tag: kw::signal_capacity, eq_token: Token![=], value: usize },
	MessageChannelCapacity { tag: kw::message_capacity, eq_token: Token![=], value: usize },
}

impl ToTokens for OrchestraAttrItem {
	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::ExternOrchestraSignalType { 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::BoxedMessages { tag, eq_token, value } => {
				quote! { #tag #eq_token, #value }
			},
		};
		tokens.extend(ts.into_iter());
	}
}

impl Parse for OrchestraAttrItem {
	fn parse(input: &ParseBuffer) -> Result<Self> {
		let lookahead = input.lookahead1();
		if lookahead.peek(kw::event) {
			Ok(OrchestraAttrItem::ExternEventType {
				tag: input.parse::<kw::event>()?,
				eq_token: input.parse()?,
				value: input.parse()?,
			})
		} else if lookahead.peek(kw::signal) {
			Ok(OrchestraAttrItem::ExternOrchestraSignalType {
				tag: input.parse::<kw::signal>()?,
				eq_token: input.parse()?,
				value: input.parse()?,
			})
		} else if lookahead.peek(kw::error) {
			Ok(OrchestraAttrItem::ExternErrorType {
				tag: input.parse::<kw::error>()?,
				eq_token: input.parse()?,
				value: input.parse()?,
			})
		} else if lookahead.peek(kw::outgoing) {
			Ok(OrchestraAttrItem::OutgoingType {
				tag: input.parse::<kw::outgoing>()?,
				eq_token: input.parse()?,
				value: input.parse()?,
			})
		} else if lookahead.peek(kw::gen) {
			Ok(OrchestraAttrItem::MessageWrapperName {
				tag: input.parse::<kw::gen>()?,
				eq_token: input.parse()?,
				value: input.parse()?,
			})
		} else if lookahead.peek(kw::signal_capacity) {
			Ok(OrchestraAttrItem::SignalChannelCapacity {
				tag: input.parse::<kw::signal_capacity>()?,
				eq_token: input.parse()?,
				value: input.parse::<LitInt>()?.base10_parse::<usize>()?,
			})
		} else if lookahead.peek(kw::message_capacity) {
			Ok(OrchestraAttrItem::MessageChannelCapacity {
				tag: input.parse::<kw::message_capacity>()?,
				eq_token: input.parse()?,
				value: input.parse::<LitInt>()?.base10_parse::<usize>()?,
			})
		} else if lookahead.peek(kw::boxed_messages) {
			Ok(OrchestraAttrItem::BoxedMessages {
				tag: input.parse::<kw::boxed_messages>()?,
				eq_token: input.parse()?,
				value: input.parse::<LitBool>()?.value(),
			})
		} else {
			Err(lookahead.error())
		}
	}
}

/// Attribute arguments
#[derive(Clone, Debug)]
pub(crate) struct OrchestraAttrArgs {
	pub(crate) message_wrapper: Ident,
	pub(crate) extern_event_ty: Path,
	pub(crate) extern_signal_ty: Path,
	pub(crate) extern_error_ty: Path,
	pub(crate) outgoing_ty: Option<Path>,
	pub(crate) signal_channel_capacity: usize,
	pub(crate) message_channel_capacity: usize,
	pub(crate) boxed_messages: bool,
}

macro_rules! extract_variant {
	($unique:expr, $variant:ident ; default = $fallback:expr) => {
		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))
	};
	($unique:expr, $variant:ident) => {
		$unique.values().find_map(|item| {
			if let OrchestraAttrItem::$variant { value, .. } = item {
				Some(value.clone())
			} else {
				None
			}
		})
	};
}

impl Parse for OrchestraAttrArgs {
	fn parse(input: &ParseBuffer) -> Result<Self> {
		let items: Punctuated<OrchestraAttrItem, Token![,]> =
			input.parse_terminated(OrchestraAttrItem::parse)?;

		let mut unique = HashMap::<
			std::mem::Discriminant<OrchestraAttrItem>,
			OrchestraAttrItem,
			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 orchestra generation type found"),
				);
				e.combine(Error::new(first.span(), "previously defined here."));
				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 error = extract_variant!(unique, ExternErrorType; err = "Must declare the orchestra error type via `error=..`.")?;
		let event = extract_variant!(unique, ExternEventType; err = "Must declare the orchestra event type via `event=..`.")?;
		let signal = extract_variant!(unique, ExternOrchestraSignalType; err = "Must declare the orchestra signal type via `signal=..`.")?;
		let message_wrapper = extract_variant!(unique, MessageWrapperName; err = "Must declare the orchestra generated wrapping message type via `gen=..`.")?;
		let outgoing = extract_variant!(unique, OutgoingType);
		let boxed_messages = extract_variant!(unique, BoxedMessages; default = false);

		Ok(OrchestraAttrArgs {
			signal_channel_capacity,
			message_channel_capacity,
			extern_event_ty: event,
			extern_signal_ty: signal,
			extern_error_ty: error,
			outgoing_ty: outgoing,
			message_wrapper,
			boxed_messages,
		})
	}
}