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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#![feature(proc_macro_diagnostic)]

extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;
extern crate syn;

use proc_macro::TokenStream as TStream;
use std::fmt::Write;

use proc_macro2::{TokenStream, Span};
use quote::{quote, quote_spanned, ToTokens};
use syn::*;
use syn::punctuated::Punctuated;
use syn::synom::{Parser, Synom};

#[proc_macro]
pub fn def_mod(tokens: TStream) -> TStream {
	let t = ModuleDecl::parse_all;
	let declarations: Vec<ModuleDecl> = t.parse(tokens).unwrap();
	let mut output = TokenStream::new();
	for module in declarations {
		let module_name = module.ident.clone();

		if module.attrs.is_empty() {
			let vis = &module.vis;
			let t = quote_spanned! { module_name.span() =>
				#vis mod #module_name;
			};
			t.to_tokens(&mut output);
		} else {
			for attr in module.attrs {
				let meta = attr.interpret_meta()
					.expect("Invalid meta item :: must be of form #[os = \"path\"] :: not valid");
				let meta_name_value = match meta {
					Meta::NameValue(v) => v,
					_ => panic!("Invalid meta item :: mut be of form #[os = \"path\"] :: not a name value"),
				};
				let os = {
					let os_name = meta_name_value.ident;
					format!("{}", os_name)
				};

				let path = {
					let segment = match meta_name_value.lit {
						Lit::Str(v) => v.value(),
						_ => panic!("Invalid meta item :: mut be of form #[os = \"path\"] :: not a literal"),
					};

					if segment.starts_with("~") {
						let mut path = String::new();
						write!(path, "{}", module_name).unwrap();
						path.push('/');
						path.push_str(&segment[1..]);
						path.push_str("/mod.rs");
						path
					} else {
						segment
					}
				};

				let vis = &module.vis;
				let t = quote_spanned! { module_name.span() =>
					#[cfg(target_os = #os)]
					#[path=#path]
					#vis mod #module_name;
				};
				t.to_tokens(&mut output);
			}
		}

		let name = format!("__load_{}", module_name);
		let load_name = Ident::new(&name, Span::call_site());

		let mut index: u32 = 0;
		let mut tokenise_method_item = |context: &Ident, method_item: TraitItemMethod| {
			let load_name = format!("_ASSERT_METHOD_{}", index);
			index += 1;
			let load_ident = Ident::new(&load_name, Span::call_site());
			let (ty, path) = convert(context, method_item.sig);
			quote! {
				const #load_ident: #ty = #path;
			}
		};

		let mut items: Vec<TokenStream> = vec![];
		for item in module.body {
			items.push(match item {
				DeclItem::Method(method_item) => tokenise_method_item(&module_name, method_item),
				DeclItem::Type(type_item) => {
					let type_name = type_item.ident;

					let mut method_items = vec![];
					for method_item in type_item.body {
						method_items.push(tokenise_method_item(&type_name, method_item));
					}

					quote! {
						{
							use self::#module_name::#type_name;
							#(#method_items)*
						}
					}
				}
			});
		}

		let t = quote! {
			#[allow(dead_code)]
			fn #load_name() {
				#(#items)*
			}
		};
		t.to_tokens(&mut output);
	}
	output.into()
}

#[derive(Debug)]
struct ModuleDecl {
	attrs: Vec<Attribute>,
	vis: Visibility,
	mod_token: Token![mod],
	ident: Ident,
	body: Vec<DeclItem>,
}

impl ModuleDecl {
	named!(parse_all -> Vec<ModuleDecl>, do_parse!(
		decls: many0!(syn!(ModuleDecl)) >>
		(decls)
	));
}

impl Synom for ModuleDecl {
	named!(parse -> Self, do_parse!(
		attrs: many0!(Attribute::parse_outer) >>
		vis: syn!(Visibility) >>
		mod_token: keyword!(mod) >>
		ident: syn!(Ident) >>
		body: map!(braces!(many0!(DeclItem::parse)), |(_brace, vec)| vec) >>
		(ModuleDecl {
			attrs,
			vis,
			mod_token,
			ident,
			body,
		})
	));
}

impl ToTokens for ModuleDecl {
	fn to_tokens(&self, tokens: &mut TokenStream) {
		self.vis.to_tokens(tokens);
	}
}

#[derive(Debug)]
enum DeclItem {
	Method(TraitItemMethod),
	Type(TypeDecl),
}

impl DeclItem {
	named!(parse -> Self, alt!(
		syn!(TraitItemMethod) => { DeclItem::Method }
		|
		syn!(TypeDecl) => { DeclItem::Type }
	));
}

#[derive(Debug)]
struct TypeDecl {
	ident: Ident,
	body: Vec<TraitItemMethod>,
}

impl Synom for TypeDecl {
	named!(parse -> Self, do_parse!(
			_type: keyword!(type) >>
			ident: syn!(Ident) >>
			body: map!(braces!(many0!(TraitItemMethod::parse)), |(_brace, vec)| vec) >>
			(TypeDecl {
				ident,
				body,
			})
		)
	);
}

fn convert(context: &Ident, sig: MethodSig) -> (TypeBareFn, ExprPath) {
	// @TODO Jezza - 19 Dec. 2018: Generic path attributes?

//	println!("Context: {}", context);
//	println!("Sig: {:?}", sig);
//	pub struct MethodSig {
//		pub constness: Option<Token![const]>,
//		pub unsafety: Option<Token![unsafe]>,
//		pub abi: Option<Abi>,
//		pub ident: Ident,
//		pub decl: FnDecl,
//	}
//	pub struct FnDecl {
//		pub fn_token: Token![fn],
//		pub generics: Generics,
//		pub paren_token: token::Paren,
//		pub inputs: Punctuated<FnArg, Token![,]>,
//		pub variadic: Option<Token![...]>,
//		pub output: ReturnType,
//	}
//	pub enum FnArg {
//		/// Self captured by reference in a function signature: `&self` or `&mut
//		/// self`.
//		///
//		/// *This type is available if Syn is built with the `"full"` feature.*
//		pub SelfRef(ArgSelfRef {
//			pub and_token: Token![&],
//			pub lifetime: Option<Lifetime>,
//			pub mutability: Option<Token![mut]>,
//			pub self_token: Token![self],
//		}),
//	
//		/// Self captured by value in a function signature: `self` or `mut
//		/// self`.
//		///
//		/// *This type is available if Syn is built with the `"full"` feature.*
//		pub SelfValue(ArgSelf {
//			pub mutability: Option<Token![mut]>,
//			pub self_token: Token![self],
//		}),
//	
//		/// An explicitly typed pattern captured by a function signature.
//		///
//		/// *This type is available if Syn is built with the `"full"` feature.*
//		pub Captured(ArgCaptured {
//			pub pat: Pat,
//			pub colon_token: Token![:],
//			pub ty: Type,
//		}),
//	
//		/// A pattern whose type is inferred captured by a function signature.
//		pub Inferred(Pat),
//		/// A type not bound to any pattern in a function signature.
//		pub Ignored(Type),
//	}
//	pub struct Generics {
//		pub lt_token: Option<Token![<]>,
//		pub params: Punctuated<GenericParam, Token![,]>,
//		pub gt_token: Option<Token![>]>,
//		pub where_clause: Option<WhereClause>,
//	}
	let MethodSig {
		constness,
		unsafety,
		abi,
		ident,
		decl,
	} = sig;

	let FnDecl {
		fn_token,
		generics,
		paren_token,
		inputs,
		variadic,
		output,
	} = decl;

	let inputs = {
		let mut values = Punctuated::new();
		for arg in inputs {
			let bare_fn_arg = match arg {
				FnArg::SelfRef(v) => {
					continue;
				}
				FnArg::SelfValue(v) => {
					continue;
				}
				FnArg::Captured(ArgCaptured {
					pat,
					colon_token,
					ty,
				}) => {
					BareFnArg {
						name: None,
						ty
					}
				}
				FnArg::Inferred(v) => {
					continue;
				}
				FnArg::Ignored(v) => {
					continue;
				}
			};
			values.push(bare_fn_arg);
		}
		values
	};

	let type_bare_fn = TypeBareFn {
		unsafety,
		abi,
		fn_token,
		lifetimes: None,
		paren_token,
		inputs,
		variadic,
		output
	};

	let mut segments = Punctuated::new();
	segments.push(PathSegment {
		ident: (*context).clone(),
		arguments: PathArguments::None
	});
	segments.push(PathSegment {
		ident: ident.clone(),
		arguments: PathArguments::None
	});
	let path = Path {
		leading_colon: None,
		segments
	};
	let path = ExprPath {
		attrs: Vec::new(),
		qself: None,
		path
	};

//	TypeBareFn {
//		=pub unsafety: Option<Token![unsafe]>,
//		=pub abi: Option<Abi>,
//		=pub fn_token: Token![fn],
//		pub lifetimes: Option<BoundLifetimes>,
//		=pub paren_token: token::Paren,
//		pub inputs: Punctuated<BareFnArg, Token![,]>,
//		=pub variadic: Option<Token![...]>,
//		=pub output: ReturnType,
//	}
//	pub struct BareFnArg {
//		pub name: Option<(BareFnArgName, Token![:])>,
//		pub ty: Type,
//	}
//	pub enum BareFnArgName {
//		/// Argument given a name.
//		Named(Ident),
//		/// Argument not given a name, matched with `_`.
//		Wild(Token![_]),
//	}

//	ExprPath {
//		pub attrs: Vec<Attribute>,
//		pub qself: Option<QSelf>,
//		pub path: Path,
//	}
//	pub struct Path {
//		pub leading_colon: Option<Token![::]>,
//		pub segments: Punctuated<PathSegment, Token![::]>,
//	}
//	pub struct PathSegment {
//		pub ident: Ident,
//		pub arguments: PathArguments,
//	}
	(type_bare_fn, path)
}