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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use std::str::FromStr;

use lazy_static::lazy_static;
use serde_derive::Deserialize;

use crate::book::{BookDeclarations, Property, Struct};
use crate::messages::{Field, Message, MessageDeclarations};
use crate::*;

pub const DATA_STR: &str = include_str!(concat!(
	env!("CARGO_MANIFEST_DIR"),
	"/declarations/BookToMessages.toml"
));

lazy_static! {
	pub static ref DATA: BookToMessagesDeclarations<'static> = {
		let rules: TomlStruct = toml::from_str(DATA_STR).unwrap();
		let book = &book::DATA;
		let messages = &messages::DATA;

		let decls: Vec<_> = rules
			.rule
			.into_iter()
			.map(|r| {
				let msg = messages.get_message(&r.to);
				let msg_fields = msg
					.attributes
					.iter()
					.map(|a| messages.get_field(a))
					.collect::<Vec<_>>();
				let book_struct = book
					.structs
					.iter()
					.find(|s| s.name == r.from)
					.unwrap_or_else(|| panic!("Cannot find struct {}", r.from));

				let find_prop = |name: &str,
								 book_struct: &'static Struct|
				 -> Option<&'static Property> {
					if let Some(prop) = book_struct
						.properties
						.iter()
						.find(|p| p.name == *name)
					{
						Some(prop)
					} else {
						None
					}
				};

				// Map RuleProperty to RuleKind
				let to_rule_kind = |p: RuleProperty| {
					assert!(p.is_valid());

					if p.function.is_some() {
						if p.type_s.is_some() {
							let rule = RuleKind::ArgumentFunction {
								type_s: p.type_s.unwrap(),
								from: p.from.unwrap(),
								name: p.function.unwrap(),
								to: p.tolist.unwrap()
									.into_iter()
									.map(|p| find_field(&p, &msg_fields))
									.collect(),
							};
							rule
						} else {
							let rule = RuleKind::Function {
								from: p.from.as_ref().map(|p|
									find_prop(p, book_struct)
									.unwrap_or_else(|| panic!("No such (nested) \
										property {} found in struct", p))),
								name: p.function.unwrap(),
								to: p.tolist.unwrap()
									.into_iter()
									.map(|p| find_field(&p, &msg_fields))
									.collect(),
							};
							rule
						}
					} else {
						if let Some(prop) = find_prop(
							p.from.as_ref().unwrap(),
							book_struct,
						) {
							RuleKind::Map {
								from: prop,
								to: find_field(&p.to.unwrap(), &msg_fields),
							}
						} else {
							RuleKind::ArgumentMap {
								from: p.from.unwrap(),
								to: find_field(&p.to.unwrap(), &msg_fields),
							}
						}
					}
				};

				let mut ev = Event {
					op: r.operation.parse().expect("Failed to parse operation"),
					ids: r.ids.into_iter().map(to_rule_kind).collect(),
					msg,
					book_struct: book_struct,
					rules: r.properties.into_iter().map(to_rule_kind).collect(),
				};

				// Add ids, which are required fields in the message.
				// The filter checks that the message is not optional.
				for field in msg_fields.iter()
					.filter(|f| msg.attributes.iter().any(|a| *a == f.map)) {
					if !ev.ids.iter().any(|i| match i {
						RuleKind::Map { to, .. } => to == field,
						RuleKind::ArgumentMap { to, .. } => to == field,
						RuleKind::Function { to, .. } |
						RuleKind::ArgumentFunction { to, .. } => to.contains(field),
					}) {
						// Try to find matching property
						if let Some(prop) = book
							.get_struct(&ev.book_struct.name)
							.properties
							.iter()
							.find(|p| !p.opt && p.name == field.pretty) {
							ev.ids.push(RuleKind::Map {
								from: prop,
								to: field,
							})
						}
						// The property may be in the properties
					}
				}

				// Add properties
				for field in msg_fields.iter()
					.filter(|f| !msg.attributes.iter().any(|a| *a == f.map)) {
					if !ev.ids.iter().chain(ev.rules.iter()).any(|i| match i {
						RuleKind::Map { to, .. } => to == field,
						RuleKind::ArgumentMap { to, .. } => to == field,
						RuleKind::Function { to, .. } |
						RuleKind::ArgumentFunction { to, .. } => to.contains(field),
					}) {
						// Try to find matching property
						if let Some(prop) = book
							.get_struct(&ev.book_struct.name)
							.properties
							.iter()
							.find(|p| !p.opt && p.name == field.pretty) {
							if !ev.ids.iter().chain(ev.rules.iter())
								.any(|i| i.from().name == prop.name) {
								ev.rules.push(RuleKind::Map {
									from: prop,
									to: field,
								})
							}
						}
					}
				}

				ev
			}).collect();

		BookToMessagesDeclarations {
			book,
			messages,
			decls,
		}
	};
}

#[derive(Debug)]
pub struct BookToMessagesDeclarations<'a> {
	pub book: &'a BookDeclarations,
	pub messages: &'a MessageDeclarations,
	pub decls: Vec<Event<'a>>,
}

#[derive(Debug)]
pub struct Event<'a> {
	pub op: RuleOp,
	pub msg: &'a Message,
	pub book_struct: &'a Struct,
	pub ids: Vec<RuleKind<'a>>,
	pub rules: Vec<RuleKind<'a>>,
}

#[derive(Debug)]
pub enum RuleKind<'a> {
	Map {
		from: &'a Property,
		to: &'a Field,
	},
	ArgumentMap {
		from: String,
		to: &'a Field,
	},
	Function {
		from: Option<&'a Property>,
		name: String,
		to: Vec<&'a Field>,
	},
	ArgumentFunction {
		from: String,
		type_s: String,
		name: String,
		to: Vec<&'a Field>,
	},
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RuleOp {
	Add,
	Remove,
	Update,
}

#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct TomlStruct {
	rule: Vec<Rule>,
}

#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct Rule {
	from: String,
	to: String,
	operation: String,
	#[serde(default = "Vec::new")]
	ids: Vec<RuleProperty>,
	#[serde(default = "Vec::new")]
	properties: Vec<RuleProperty>,
}

#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct RuleProperty {
	from: Option<String>,
	to: Option<String>,

	#[serde(rename = "type")]
	type_s: Option<String>,
	function: Option<String>,
	tolist: Option<Vec<String>>,
}

impl RuleProperty {
	fn is_valid(&self) -> bool {
		if self.to.is_some() {
			self.from.is_some()
				&& self.function.is_none()
				&& self.tolist.is_none()
				&& self.type_s.is_none()
		} else {
			self.to.is_none()
				&& self.function.is_some()
				&& self.tolist.is_some()
				// If the type is set, from must be set too
				&& (self.type_s.is_none() || self.from.is_some())
		}
	}
}

impl FromStr for RuleOp {
	type Err = String;
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		if s == "add" {
			Ok(RuleOp::Add)
		} else if s == "remove" {
			Ok(RuleOp::Remove)
		} else if s == "update" {
			Ok(RuleOp::Update)
		} else {
			Err("Cannot parse operation, needs to be add, remove or update"
				.to_string())
		}
	}
}

// the in rust callable name (in PascalCase) from the field
fn find_field<'a>(name: &str, msg_fields: &[&'a Field]) -> &'a Field {
	*msg_fields
		.iter()
		.find(|f| f.pretty == name)
		.expect(&format!("Cannot find field '{}'", name))
}

impl<'a> RuleKind<'a> {
	pub fn from_name(&'a self) -> &'a str {
		match self {
			RuleKind::Map { from, .. } => &from.name,
			RuleKind::ArgumentMap { from, .. } => &from,
			RuleKind::Function { from, name, .. } => {
				&from
					.unwrap_or_else(|| {
						panic!("From not set for function {}", name)
					})
					.name
			}
			RuleKind::ArgumentFunction { from, .. } => &from,
		}
	}

	pub fn from(&self) -> &'a Property {
		match self {
			RuleKind::Map { from, .. } => from,
			RuleKind::Function { from, name, .. } => {
				from.unwrap_or_else(|| {
					panic!("From not set for function {}", name)
				})
			}
			RuleKind::ArgumentMap { .. }
			| RuleKind::ArgumentFunction { .. } => {
				panic!("From is not a property for argument functions")
			}
		}
	}

	pub fn is_function(&self) -> bool {
		if let RuleKind::Function { .. } = *self {
			true
		} else if let RuleKind::ArgumentFunction { .. } = *self {
			true
		} else {
			false
		}
	}
}