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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/*!
`def_mod!` provides a familiar syntax to the standard module declarations, but with the added benefit of being able
to easily define implementation routes and to statically verify module exports.

---
```rust
extern crate def_mod;

use def_mod::def_mod;

def_mod! {
	// This has the exact same behaviour as Rust's.
	mod my_mod;

	// Much like the one above, it also has the same effect as Rust's.
	mod my_first_mod {
		// It also checks to see if a method with the type `fn(u32) -> u8` was exported.
    	// It will fail to compile if it finds none.
		fn method(_: u32) -> u8;

		// Much like the method declaration from above, this will check to see if a type was exported.
		type MyStruct;

		// This will also check to see if the type `MyOtherStruct` was export.
		type MyOtherStruct {
			// This will check if this method exists on this type. (MyOtherStruct::method)
			fn method(_: u32) -> u8;
		}
	}

	// Attributes are declared like normal.
	#[cfg(windows)]
	mod my_second_mod;

	// When declaring an attribute, you can optionally add a path.
	// This path is then used as the path attribute for the module file.
	// All attributes declared with a path are treated as _mutually exclusive_.
	// So a `mod` declaration is generated for each.
	// This makes it a lot easier to manage cross-platform code.
	// Note: attributes that don't have a path are copied to each module declaration.

	#[cfg(windows)] = "sys/win/mod.rs"
	#[cfg(not(windows))] = "sys/nix/mod.rs"
	mod sys;

	// Expands to:

	#[cfg(windows)]
	#[path = "sys/win/mod.rs"]
	mod sys;

	#[cfg(not(windows))]
	#[path = "sys/nix/mod.rs"]
	mod sys;

	// You can also declare attributes on methods or types themselves, and they will be used when verifying the type.
	// This module itself will be verified when not on a windows system.
	#[cfg(not(windows))]
	mod my_third_mod {
		// This method will only be verified when on linux.
		#[cfg(linux)]
		fn interop() -> u8;
		// Same with this type. It will only be verified when on a linux system
		#[cfg(linux)]
		type SomeStruct {
			fn interop() -> u8;
		}
	}
}

fn main() {
}
```

NOTE: that `def_mod` uses syntax tricks to assert for types.  
So that means when you use the path shorthand, it will still only check the module that is loaded, not all potential modules.    

Eg, if I've got a module that has two possible impls, one for windows and one for unix.  
If I compile on windows, `def_mod` can't check if the unix module has the correct symbols declared, because it's not the module that's compiled.  

You would need to explicitly enable compilation of the modules you'd want to check, because you can declare  
arbitrary #[cfg] attributes, there's no way in `def_mod` to do this.  
It's entirely up to you.  

---

In case you're curious as to what the macro generates:

A method assertion is transformed to something like:

```rust
const _VALUE: fn(u32) -> u8 = my_mod::method;
```

A method assertion with generics is a bit more complex, but still understandable.

```rust
fn generic<'a , T: 'a>(_: u32, _: T, _: fn(T) -> T) -> &'a T;

// will turn into into (Note: This is nested inside of the load function itself.)

#[allow(non_snake_case)]
fn _load_module_name_generic<'a, T: 'a>() {
	let _VALUE:
			fn(_: u32, _: T,
			   _: fn(T) -> T) -> &'a T =
		other::generic;
}
```

It will also transform references to self:

```rust
mod other {
	type MyStruct {
		fn new() -> Self;
		fn dupe(&self) -> Self;
		fn clear(&mut self);
	}
}

// into

const _VALUE_0: fn() -> MyStruct = MyStruct::new;
const _VALUE_1: fn(_self: &MyStruct) -> MyStruct = MyStruct::dupe;
const _VALUE_2: fn(_self: &mut MyStruct) = MyStruct::clear;
```

A type assertion is transformed into a new scope with a use decl:

```rust
{
	use self::my_mod::Test;
	// Any method assertions for the type will also be placed inside the same scope.
}
```

All of those are shoved into a function generated by the macro.

For example, given something like:

```rust
def_mod! {
	mod my_mod {
		fn plus_one(value: u8) -> u8;

		type MyStruct {
			fn new() -> Self;
			fn dupe(&self) -> Self;
			fn clear(&mut self);
		}
	}
}
```

It'll turn it into something like this:

```rust
mod my_mod;

fn _load_my_mod() {
	const _ASSERT_METHOD_0: fn(u8) -> u8 = my_mod::method;
	{
		use self::my_mod::MyStruct;
		const _ASSERT_METHOD_1: fn() -> MyStruct = MyStruct::new;
		const _ASSERT_METHOD_2: fn(_self: &MyStruct) -> MyStruct = MyStruct::dupe;
		const _ASSERT_METHOD_3: fn(_self: &mut MyStruct) -> MyStruct = MyStruct::clear;
	}
}
```
*/

#![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 proc_macro2::{TokenStream, TokenTree, Group};
use quote::{quote, quote_spanned, ToTokens, TokenStreamExt};
use syn::*;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
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 mut pathed_attrs = vec![];
		let mut custom_attrs = vec![];
		// Group the attributes that were declared with a path value.
		for attr in module.attrs {
			if let (attr, Some(path)) = attr {
				pathed_attrs.push((attr, path));
			} else {
				custom_attrs.push(attr.0);
			};
		}
		// Ghost the attr vectors, so no one can change them...
		let pathed_attrs = &pathed_attrs;
		let custom_attrs = &custom_attrs;

		let vis = &module.vis;
		let mod_token = &module.mod_token;
		let module_name = &module.ident;

		if pathed_attrs.is_empty() {
			let t = quote_spanned! { module_name.span() =>
				#(#custom_attrs)*
				#vis #mod_token #module_name;
			};
			t.to_tokens(&mut output);
		} else {
			// If there were some pathed attrs, then we need to generate an equal number of mod decls with the attrs.
			for (attr, path) in pathed_attrs {
				let t = quote_spanned! { module_name.span() =>
					#attr
					#[path=#path]
					#(#custom_attrs)*
					#vis #mod_token #module_name;
				};
				t.to_tokens(&mut output);
			}
		}

		// Generate a load function, if the module was declared with some items.
		if let ModuleBody::Content((_brace, body)) = module.body {
			let mut index: u32 = 0;
			// This is the function that transforms a method into an assertion.
			let mut tokenise_method = |type_name: Option<&Ident>, method_item: TraitItemMethod| {
				if let Some(body) = method_item.default {
					body.span()
						.unstable()
						.error("A body isn't valid here.")
						.emit();
					return TokenStream::new();
				}
				let mapping = if let Some(type_name) = type_name {
					let self_replacement = type_name.to_string();
					let func = move |ident: Ident| {
						// @FIXME Jezza - 21 Dec. 2018: Yeah, this is very... eh... yucky...
						// I can't think of a better way to do this...
						if ident.to_string() == "Self" {
							Ident::new(&self_replacement, ident.span())
						} else {
							ident
						}
					};
					Some(func)
				} else {
					None
				};
				let t = convert(module_name, type_name, index, method_item, mapping);
				index += 1;
				t
			};
			let items: Vec<TokenStream> = body.into_iter()
				.map(|item| {
					// Transform each item into the corresponding check.
					match item {
						DeclItem::Method(method_item) => tokenise_method(None, method_item),
						DeclItem::Type(type_item) => {
							let attrs = &type_item.attrs;
							let type_name = &type_item.ident;

							let method_items = if let TypeDeclBody::Content((_brace, body)) = type_item.body {
								body.into_iter()
									.map(|method_item| tokenise_method(Some(type_name), method_item))
									.collect()
							} else {
								vec![]
							};

							// We use the actual use declaration here to test for the type itself, as it'll fail if it doesn't exist or not exported.
							// It also makes the codegen easier, because we don't have to qualify the full name type.
							quote! {
								#(#attrs)*
								{
									use self::#module_name::#type_name;
									#(#method_items)*
								}
							}
						}
					}
				})
				.filter(|t| !t.is_empty())
				.collect();

			let function_name = {
				let name = format!("_load_{}", module_name);
				Ident::new(&name, module_name.span())
			};
			let t = quote! {
				#[allow(dead_code)]
				fn #function_name() {
					use self::#module_name::*;
					#(#items)*
				}
			};
			t.to_tokens(&mut output);
		}
	}
	output.into()
}

///
/// A module declaration: `mod my_mod`
/// 
/// One of the differences between this and a normal mod decl is
/// the attributes can declare a path literal:
/// ```rust
/// #[cfg(target_os = "windows")] = "my_mod/win/mod.rs"
/// mod my_mod;
/// ```
/// 
/// The other is that it can declare a body.
/// The body contains methods/types that the module needs to export.
/// If the module doesn't export those symbols, you will get a compiler error.
/// 
#[derive(Debug)]
struct ModuleDecl {
	attrs: Vec<(Attribute, Option<LitStr>)>,
	vis: Visibility,
	mod_token: Token![mod],
	ident: Ident,
	body: ModuleBody,
}

#[derive(Debug)]
enum ModuleBody {
	Content((token::Brace, Vec<DeclItem>)),
	Terminated(Token![;]),
}

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!(do_parse!(
			attr: call!(Attribute::parse_outer) >>
			eq: option!(punct!(=)) >>
			path: cond!(eq.is_some(), syn!(LitStr))>>
			(attr, path)
		)) >>
		vis: syn!(Visibility) >>
		mod_token: keyword!(mod) >>
		ident: syn!(Ident) >>
		body: alt! (
			punct!(;) => { ModuleBody::Terminated }
			|
			braces!(many0!(DeclItem::parse)) => { ModuleBody::Content }
		) >>
		(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),
}

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

#[derive(Debug)]
enum TypeDeclBody {
	Content((token::Brace, Vec<TraitItemMethod>)),
	Terminated(Token![;]),
}

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

impl Synom for TypeDecl {
	named!(parse -> Self, do_parse!(
			attrs: many0!(Attribute::parse_outer) >>
			_type: keyword!(type) >>
			ident: syn!(Ident) >>
			body: alt!(
				punct!(;) => { TypeDeclBody::Terminated }
				|
				braces!(many0!(TraitItemMethod::parse)) => { TypeDeclBody::Content }
			) >>
			(TypeDecl {
				attrs,
				ident,
				body,
			})
		)
	);
}

fn convert<F>(module_name: &Ident, type_name: Option<&Ident>, index: u32, method_item: TraitItemMethod, ident_mapping: Option<F>) -> TokenStream
		where F: Fn(Ident) -> Ident {

//	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,
	} = method_item.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(ArgSelfRef{
					and_token,
					lifetime,
					mutability,
					self_token: _
				}) => {
					let t = quote! {
						_self: #and_token #lifetime #mutability #type_name
					};
					parse2::<BareFnArg>(t).expect("Should never happen [self-ref]")
				}
				FnArg::SelfValue(ArgSelf {
					mutability,
					self_token: _,
				}) => {
					let t = quote! {
						_self: #mutability #type_name
					};
					parse2::<BareFnArg>(t).expect("Should never happen [self-value]")
				}
				FnArg::Captured(ArgCaptured {
					pat,
					colon_token,
					ty,
				}) => {
					let ts = ty.into_token_stream();
					let ty = if let Some(ref func) = ident_mapping {
						replace_idents(ts, func)
					} else {
						ts
					};
					let t: TokenStream = quote! {
						#pat #colon_token #ty
					};
					parse2::<BareFnArg>(t).expect("Should never happen [arg-captured]")
				}
				FnArg::Inferred(pat) => {
					// Technically, this shouldn't be possible, but we know the transformation that needs to take place,
					// so I just go ahead and do that.
					let t = quote! {
						#pat: _
					};
					parse2::<BareFnArg>(t).expect("Should never happen [inferred]")
				}
				FnArg::Ignored(ty) => {
					// This way of writing signatures has been deprecated, and I should probably emit a warning.
					ident.span()
						.unstable()
						.warning("Declaring parameters without a name is deprecated, and will not be supported in the future. [Hint: Just add \"_:\" to the parameter to remove this warning...]")
						.emit();
					let ts = ty.into_token_stream();
					let ts = if let Some(ref func) = ident_mapping {
						replace_idents(ts, func)
					} else {
						ts
					};
					parse2::<BareFnArg>(ts).expect("Should never happen [ignored]")
				}
			};
			values.push(bare_fn_arg);
		}
		values
	};

	let output = {
		let ts = output.into_token_stream();
		let ts = if let Some(ref func) = ident_mapping {
			replace_idents(ts, func)
		} else {
			ts
		};
		parse2::<ReturnType>(ts).expect("Should never happen [return-type]")
	};

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

//	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![_]),
//	}
	let attrs = &method_item.attrs;
	let load_ident = {
		let name = format!("_ASSERT_METHOD_{}", index);
		Ident::new(&name, ident.span())
	};
	let context = type_name.unwrap_or(module_name);

	if generics.params.is_empty() {
		quote! {
			#(#attrs)*
			const #load_ident: #type_bare_fn = #context::#ident;
		}
	} else {
		let nested_function_name = {
			let name = if let Some(type_name) = type_name {
				format!("_load_{}_{}_{}", module_name, type_name, ident)
			} else {
				format!("_load_{}_{}", module_name, ident)
			};
			Ident::new(&name, ident.span())
		};
		// Do note that we don't use ty_generics, as it's just the use-site, which for us is in the method's signature.
		let (impl_generics, _ty_generics, where_clause) = generics.split_for_impl();
		quote! {
			#(#attrs)*
			#[allow(non_snake_case)]
			fn #nested_function_name #impl_generics() #where_clause {
				let #load_ident: #type_bare_fn = #context::#ident;
			}
		}
	}
}

fn replace_idents<F>(ts: TokenStream, func: &F) -> TokenStream
		where F: Fn(Ident) -> Ident {
	let mut out = TokenStream::new();
	ts.into_iter()
		.map(move |tt| {
			match tt {
				TokenTree::Group(g) => {
					let delimiter = g.delimiter();
					let ts = g.stream();
					let out = replace_idents(ts, func);
					TokenTree::Group(Group::new(delimiter, out))
				},
				TokenTree::Ident(i) => TokenTree::Ident(func(i)),
				v => v,
			}
		})
		.for_each(|tt| out.append(tt));
	out
}