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
#![recursion_limit = "256"]

extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2;
use quote::quote;
use regex::Regex;
use std::collections::HashSet;
use syn::{parse_macro_input, DeriveInput};

#[derive(Debug, PartialEq)]
enum RouteToRegexError {
	MissingLeadingForwardSlash,
	NonAsciiChars,
	InvalidIdentifier(String),
	InvalidTrailingSlash,
	CharactersAfterWildcard,
}

fn route_to_regex(route: &str) -> Result<(String, String), RouteToRegexError> {
	enum ParseState {
		Initial,
		Static,
		VarName(String),
		WildcardFound,
	};

	if !route.is_ascii() {
		return Err(RouteToRegexError::NonAsciiChars);
	}

	let ident_regex = Regex::new(r"^[a-zA-Z][a-zA-Z0-9_]*$").unwrap();

	let mut regex = "".to_string();
	let mut format_str = "".to_string();
	let mut parse_state = ParseState::Initial;

	for byte in route.chars() {
		match parse_state {
			ParseState::Initial => {
				if byte != '/' {
					return Err(RouteToRegexError::MissingLeadingForwardSlash);
				}

				regex += "^/";
				format_str += "/";

				parse_state = ParseState::Static;
			}
			ParseState::Static => {
				if byte == ':' {
					format_str.push('{');
					parse_state = ParseState::VarName("".to_string());
				} else {
					regex.push(byte);
					format_str.push(byte);
					parse_state = ParseState::Static;
				}
			}
			ParseState::VarName(mut name) => {
				if byte == '/' {
					// Validate 'name' as a Rust identifier
					if !ident_regex.is_match(&name) {
						return Err(RouteToRegexError::InvalidIdentifier(name));
					}

					regex += &format!("(?P<{}>[^/]+)/", name);
					format_str += &format!("{}}}/", name);
					parse_state = ParseState::Static;
				} else if byte == '*' {
					// Found a wildcard - add the var name to the regex

					// Validate 'name' as a Rust identifier
					if !ident_regex.is_match(&name) {
						return Err(RouteToRegexError::InvalidIdentifier(name));
					}

					regex += &format!("(?P<{}>.*)", name);
					format_str += &format!("{}}}", name);
					parse_state = ParseState::WildcardFound;
				} else {
					name.push(byte);
					parse_state = ParseState::VarName(name);
				}
			}
			ParseState::WildcardFound => {
				return Err(RouteToRegexError::CharactersAfterWildcard);
			}
		};
	}

	if let ParseState::VarName(name) = parse_state {
		regex += &format!("(?P<{}>[^/]+)", name);
		format_str += &format!("{}}}", name);
	}

	if regex.ends_with('/') {
		return Err(RouteToRegexError::InvalidTrailingSlash);
	}

	regex += "$";

	Ok((regex, format_str))
}

#[test]
fn test_route_to_regex() {
	let (regex, _) = route_to_regex("/p/:project_id/exams/:exam_id/submissions_expired").unwrap();
	assert_eq!(
		regex,
		r"^/p/(?P<project_id>[^/]+)/exams/(?P<exam_id>[^/]+)/submissions_expired$"
	);
}

#[test]
fn test_route_to_regex_no_path_params() {
	let (regex, _) = route_to_regex("/p/exams/submissions_expired").unwrap();
	assert_eq!(regex, r"^/p/exams/submissions_expired$");
}

#[test]
fn test_route_to_regex_no_leading_slash() {
	let regex = route_to_regex("p/exams/submissions_expired");
	assert_eq!(regex, Err(RouteToRegexError::MissingLeadingForwardSlash));
}

#[test]
fn test_route_to_regex_non_ascii_chars() {
	let regex = route_to_regex("🥖p🥖:project_id🥖exams🥖:exam_id🥖submissions_expired");
	assert_eq!(regex, Err(RouteToRegexError::NonAsciiChars));
}

#[test]
fn test_route_to_regex_invalid_ident() {
	let regex = route_to_regex("/p/:project_id/exams/:_exam_id/submissions_expired");
	assert_eq!(
		regex,
		Err(RouteToRegexError::InvalidIdentifier("_exam_id".to_string()))
	);
}

#[test]
fn test_route_to_regex_characters_after_wildcard() {
	let regex = route_to_regex("/p/:project_id/exams/:exam*ID/submissions_expired");
	assert_eq!(
		regex,
		Err(RouteToRegexError::CharactersAfterWildcard)
	);
}

#[test]
fn test_route_to_regex_invalid_ending() {
	let regex = route_to_regex("/p/:project_id/exams/:exam_id/submissions_expired/");
	assert_eq!(regex, Err(RouteToRegexError::InvalidTrailingSlash));
}

fn get_string_attr(name: &str, attrs: &[syn::Attribute]) -> Option<String> {
	for attr in attrs {
		let attr = attr.parse_meta();

		if let Ok(syn::Meta::List(ref list)) = attr {
			if list.ident == name {
				for thing in &list.nested {
					if let syn::NestedMeta::Literal(syn::Lit::Str(str_lit)) = thing {
						return Some(str_lit.value());
					}
				}
			}
		}
	}

	None
}

fn has_flag_attr(name: &str, attrs: &[syn::Attribute]) -> bool {
	for attr in attrs {
		let attr = attr.parse_meta();

		if let Ok(syn::Meta::Word(ref ident)) = attr {
			if ident == name {
				return true;
			}
		}
	}

	false
}

fn get_struct_fields(data: &syn::Data) -> Vec<syn::Field> {
	match data {
		syn::Data::Struct(data_struct) => match data_struct.fields {
			syn::Fields::Named(ref named_fields) => named_fields.named.iter().cloned().collect(),
			_ => panic!("Struct fields must be named"),
		},
		_ => panic!("AppRoute derive is only supported for structs"),
	}
}

fn field_is_option(field: &syn::Field) -> bool {
	match field.ty {
		syn::Type::Path(ref type_path) => type_path
			.path
			.segments
			.iter()
			.last()
			.map(|segment| segment.ident == "Option")
			.unwrap_or(false),
		_ => false,
	}
}

#[proc_macro_derive(AppRoute, attributes(route, query))]
pub fn app_route_derive(input: TokenStream) -> TokenStream {
	let input = parse_macro_input!(input as DeriveInput);

	let struct_fields = get_struct_fields(&input.data);

	let (route_fields, query_fields): (Vec<_>, Vec<_>) = struct_fields
		.into_iter()
		.partition(|f| !has_flag_attr("query", &f.attrs));

	let name = &input.ident;
	let generics = input.generics;
	let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

	let route_string = get_string_attr("route", &input.attrs);

	let url_route = route_string.expect(
		"derive(AppRoute) requires a #[route(\"/your/route/here\")] attribute on the struct",
	);

	let (route_regex_str, format_str) =
		route_to_regex(&url_route).expect("Could not convert route attribute to a valid regex");

	// Validate route_regex and make sure struct and route have matching fields
	let route_regex =
		Regex::new(&route_regex_str).expect("route attribute was not compiled into a valid regex");

	let regex_capture_names_set: HashSet<String> = route_regex
		.capture_names()
		.filter_map(|c_opt| c_opt.map(|c| c.to_string()))
		.collect();
	let field_names_set: HashSet<String> = route_fields
		.clone()
		.into_iter()
		.map(|f| f.ident.unwrap().to_string())
		.collect();

	if regex_capture_names_set != field_names_set {
		let missing_from_route = field_names_set.difference(&regex_capture_names_set);
		let missing_from_struct = regex_capture_names_set.difference(&field_names_set);

		let error_msg = format!("\nFields in struct missing from route pattern: {:?}\nFields in route missing from struct: {:?}", missing_from_route, missing_from_struct);
		panic!(error_msg);
	}

	let route_field_assignments = route_fields.clone().into_iter().map(|f| {
		let f_ident = f.ident.unwrap();
		let f_ident_str = f_ident.to_string();

		quote! {
			#f_ident: captures[#f_ident_str].parse().map_err(|e| {
				RouteParseErr::ParamParseErr(std::string::ToString::to_string(&e))
			})?
		}
	});

	let query_field_assignments = query_fields.clone().into_iter().map(|f| {
        let is_option = field_is_option(&f);
        let f_ident = f.ident.unwrap();

        if is_option {
            quote! {
                #f_ident: query_string.and_then(|q| qs::from_str(q).ok())
            }
        } else {
            quote! {
                #f_ident: qs::from_str(query_string.ok_or(RouteParseErr::NoQueryString)?).map_err(|e| RouteParseErr::QueryParseErr(e.description().to_string()))?
            }
        }
    });

	let route_field_parsers = quote! {
		#(
			#route_field_assignments
		),*
	};

	let query_field_parsers = quote! {
		#(
			#query_field_assignments
		),*
	};

	let format_args = route_fields.clone().into_iter().map(|f| {
		let f_ident = f.ident.unwrap();

		quote! {
			#f_ident = self.#f_ident
		}
	});

	let format_args = quote! {
		#(
			#format_args
		),*
	};

	let query_field_to_string_statements = query_fields.into_iter().map(|f| {
		let is_option = field_is_option(&f);
		let f_ident = f.ident.unwrap();

		if is_option {
			quote! {
				self.#f_ident.as_ref().and_then(|q| qs::to_string(&q).ok())
			}
		} else {
			quote! {
				qs::to_string(&self.#f_ident).ok()
			}
		}
	});

	let encoded_query_fields = quote! {
		#(
			#query_field_to_string_statements
		),*
	};

	let struct_constructor = match (
		route_field_parsers.is_empty(),
		query_field_parsers.is_empty(),
	) {
		(true, true) => quote! {
			#name {}
		},
		(true, false) => quote! {
			#name {
				#query_field_parsers
			}
		},
		(false, true) => quote! {
			#name {
				#route_field_parsers
			}
		},
		(false, false) => quote! {
			#name {
				#route_field_parsers,
				#query_field_parsers
			}
		},
	};

	let app_route_impl = quote! {
		impl #impl_generics app_route::AppRoute for #name #ty_generics #where_clause {

			fn path_pattern() -> String {
				#route_regex_str.to_string()
			}

			fn query_string(&self) -> Option<String> {
				use app_route::serde_qs as qs;

				// TODO - Remove duplicates because
				//        there could be multiple fields with
				//        a #[query] attribute that have common fields

				// TODO - can this be done with an on-stack array?
				let encoded_queries: Vec<Option<String>> = vec![#encoded_query_fields];
				let filtered: Vec<_> = encoded_queries.into_iter().filter_map(std::convert::identity).collect();

				if !filtered.is_empty() {
					Some(filtered.join("&"))
				} else {
					None
				}
			}
		}

		impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause {
			fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
				if let Some(query) = self.query_string() {
					let path = format!(
						#format_str,
						#format_args
					);

					write!(f, "{}?{}", path, query)
				} else {
					write!(
						f,
						#format_str,
						#format_args
					)
				}
			}
		}

		impl #impl_generics std::str::FromStr for #name #ty_generics #where_clause {
			type Err = app_route::RouteParseErr;

			fn from_str(app_path: &str) -> Result<Self, Self::Err> {
				use app_route::serde_qs as qs;
				use app_route::RouteParseErr;

				app_route::lazy_static! {
					static ref ROUTE_REGEX: app_route::Regex = app_route::Regex::new(#route_regex_str).expect("Failed to compile regex");
				}

				let question_pos = app_path.find('?');
				let just_path = &app_path[..(question_pos.unwrap_or_else(|| app_path.len()))];

				let captures = (*ROUTE_REGEX).captures(just_path).ok_or(RouteParseErr::NoMatches)?;

				let query_string = question_pos.map(|question_pos| {
					let mut query_string = &app_path[question_pos..];

					if query_string.starts_with('?') {
						query_string = &query_string[1..];
					}

					query_string
				});

				Ok(#struct_constructor)
			}
		}
	};

	let impl_wrapper = syn::Ident::new(
		&format!("_IMPL_APPROUTE_FOR_{}", name.to_string()),
		proc_macro2::Span::call_site(),
	);

	let out = quote! {
		const #impl_wrapper: () = {
			extern crate app_route;
			#app_route_impl
		};
	};

	out.into()
}