tidos_macro 0.6.6

Procedural macros for the Tidos component framework.
Documentation
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
extern crate proc_macro;

use proc_macro2::{Group, Ident, Span, TokenStream, TokenTree};
use quote::{format_ident, quote, ToTokens, TokenStreamExt};
use syn::parse::{Parse, ParseStream};

#[derive(Debug)]
pub enum ControlTag {
	// {#if ... } ... {:else if ... } ... {:else} ... {/if}
	IfChain {
		if_statement: Vec<TokenTree>,
		if_content: Vec<Content>,
		if_else_chain: Vec<(Vec<TokenTree>, Vec<Content>)>,
		else_content: Option<Vec<Content>>,
	},
	// {#for ... in ... } ... {/for}
	For {
		left_side: Vec<TokenTree>,
		right_side: Vec<TokenTree>,
		contents: Vec<Content>,
	},
	// {#match ... } ... {/match}
	Match {
		match_statement: Vec<TokenTree>,
		cases: Vec<(Vec<TokenTree>, Vec<Content>)>,
	},
}

impl ToTokens for ControlTag {
	fn to_tokens(&self, tokens: &mut TokenStream) {
		match self {
			ControlTag::IfChain {
				if_statement,
				if_content,
				if_else_chain,
				else_content,
			} => {
				ControlTag::to_tokens_if_chain(
					if_statement,
					if_content,
					if_else_chain,
					else_content,
					tokens,
				);
			}
			ControlTag::For {
				left_side,
				right_side,
				contents,
			} => {
				ControlTag::to_tokens_for_loop(left_side, right_side, contents, tokens);
			}
			ControlTag::Match {
				match_statement,
				cases,
			} => {
				ControlTag::to_tokens_match(match_statement, cases, tokens);
			}
		}
	}
}

impl ControlTag {
	fn to_tokens_for_loop(
		left_side: &Vec<TokenTree>,
		right_side: &Vec<TokenTree>,
		contents: &Vec<Content>,
		tokens: &mut TokenStream,
	) {
		let tokens_children = contents
			.iter()
			.fold(&mut TokenStream::new(), |acc, child| {
				child.to_tokens(acc);
				acc
			})
			.to_owned();

		let output = quote! {

			&( #( #right_side )* ).into_iter().fold(String::new(), |acc, ( #( #left_side )* )| { acc + #tokens_children })
		};

		tokens.append_all(output);
	}

	fn to_tokens_if_chain(
		if_statement: &Vec<TokenTree>,
		if_content: &Vec<Content>,
		if_else_chain: &Vec<(Vec<TokenTree>, Vec<Content>)>,
		else_content: &Option<Vec<Content>>,
		tokens: &mut TokenStream,
	) {
		let if_content_tokens = if_content
			.iter()
			.fold(&mut TokenStream::new(), |acc, child| {
				child.to_tokens(acc);
				acc
			})
			.to_owned();

		let if_else_chain_tokens = if_else_chain
			.iter()
			.fold(&mut TokenStream::new(), |acc, (statement, contents)| {
				let chain_contents_tokens = contents
					.iter()
					.fold(&mut TokenStream::new(), |acc, child| {
						child.to_tokens(acc);
						acc
					})
					.to_owned();

				let chain = quote! {
					else if #( #statement )* { String::new() + #chain_contents_tokens }
				};

				chain.to_tokens(acc);
				acc
			})
			.to_owned();

		let output = if let Some(else_content) = else_content {
			let else_content_tokens = else_content
				.iter()
				.fold(&mut TokenStream::new(), |acc, child| {
					child.to_tokens(acc);
					acc
				})
				.to_owned();

			quote! {
				&if #( #if_statement )* { String::new() + #if_content_tokens } #if_else_chain_tokens else { String::new() + #else_content_tokens }
			}
		} else {
			quote! {
				&if #( #if_statement )* { String::new() + #if_content_tokens } #if_else_chain_tokens else { String::new() }
			}
		};

		tokens.append_all(output);
	}

	fn to_tokens_match(
		match_statement: &Vec<TokenTree>,
		cases: &Vec<(Vec<TokenTree>, Vec<Content>)>,
		tokens: &mut TokenStream,
	) {
		let cases = cases
			.iter()
			.map(|(case_statement, case_content)| {
				let mut tokens_content = TokenStream::new();

				for child in case_content {
					child.to_tokens(&mut tokens_content);
				}

				// todo static islands

				quote! {
					#( #case_statement )* => {
						String::new() + #tokens_content
					}
				}
			})
			.collect::<Vec<_>>();

		let output = quote! {
			&match #( #match_statement )* {
				#( #cases )*
			}
		};

		tokens.append_all(output);
	}
}

#[derive(Debug)]
pub enum Content {
	// <p>...</p>
	Tag(HTMLTag),

	// {#if x > 10} ... {/if}
	// {#for x in numbers} ... {/for}
	// {#match x} ... {/match}
	ControlTag(ControlTag),

	// // <Custom></Custom>
	// Custom,

	// // <tidos:self></tidos:self>
	// Instruction,

	// text
	Literal(String),

	// expression <p>{ format!("Hello {}", name) }</p>
	Expression(Group),

	// <p>@html{"<p>potential danger"}</p>
	RawHTMLExpression(Group),
}

impl Content {
	fn is_static(&self) -> bool {
		match self {
			Content::Tag(element) => {
				let tag = element.tag.as_str();
				let is_component = tag.chars().next().unwrap().is_ascii_uppercase();

				if is_component {
					return false;
				}
				let has_only_static_attributes = element
					.attributes
					.iter()
					.all(|attribute| attribute.is_static());
				let has_only_static_children =
					element.children.iter().all(|child| child.is_static());

				has_only_static_attributes && has_only_static_children
			}
			Content::ControlTag(_) => false,
			Content::Literal(_) => true,
			Content::Expression(_) => false,
			Content::RawHTMLExpression(_) => false,
		}
	}
}

impl ToTokens for Content {
	fn to_tokens(&self, tokens: &mut TokenStream) {
		match self {
			Content::Tag(html_tag) => {
				let tag = html_tag.tag.as_str();
				let is_component = tag.chars().next().unwrap().is_ascii_uppercase();
				let is_self_closing = html_tag.is_self_closing;
				let has_attributes = html_tag.attributes.len() > 0;

				if is_component {
					let mut attributes = vec![];
					for attribute in &html_tag.attributes {
						let name = format_ident!("{}", &attribute.name);
						let value = &attribute.value;
						attributes.push(quote! { #name: #value })
					}

					let component_name = Ident::new(tag, Span::call_site()).to_token_stream();

					let tag_tokens =
						quote! { &#component_name { #( #attributes ),* }.to_render(page) };
					tokens.append_all(tag_tokens);
				} else {
					let mut static_attributes = vec![];
					let mut dynamic_attributes = vec![];
					for attribute in &html_tag.attributes {
						if attribute.is_static() {
							static_attributes.push(attribute.to_token_stream());
						} else {
							dynamic_attributes.push(attribute.to_token_stream());
						}
					}
					let has_only_static_attributes = dynamic_attributes.is_empty();

					if is_self_closing {
						if has_only_static_attributes {
							tokens.append_all(
								quote! { concat!("<", #tag #(, " ", #static_attributes)* , " />") },
							);
						} else {
							tokens.append_all(
								quote! { concat!("<", #tag #(, " ", #static_attributes)* ) #(+ " " + #dynamic_attributes)* + " />"},
							);
						}
					} else {
						let mut islands = vec![];
						let mut island = vec![];
						let mut unclean = false;
						for element in &html_tag.children {
							if element.is_static() {
								island.push(element);
								unclean = true;
							} else if unclean {
								islands.push((true, island.clone()));
								unclean = false;
								island = vec![];
								islands.push((false, vec![element]))
							} else {
								islands.push((false, vec![element]))
							}
						}

						if unclean {
							islands.push((true, island.clone()));
						}

						let has_only_static_children = islands.iter().all(|&(x, _)| x);
						let children = islands
							.iter()
							.map(|(is_static, island)| {
								if *is_static {
									quote! { concat!( #( #island ),*) }
								} else {
									quote! { #( #island )* }
								}
							})
							.collect::<Vec<_>>();

						let x = match (has_only_static_attributes, has_only_static_children) {
							(true, true) => {
								quote! {
									concat!("<", #tag #(, " ", #static_attributes)*
										, ">"
										#(, #children)*
										, "</", #tag, ">")
								}
							}
							(true, false) => {
								quote! {
									concat!("<", #tag #(, " ", #static_attributes)* , ">")
									#( + #children )*
									+ concat!("</", #tag, ">")
								}
							}
							(false, true) => {
								quote! {
									concat!("<", #tag #(, " ", #static_attributes)* )
									#( + " " + #dynamic_attributes )*
									+ concat!(">" #(, #children)* , "</", #tag, ">")
								}
							}
							(false, false) => {
								quote! {
									concat!("<", #tag #(, " ", #static_attributes)* )
									#( + " " + #dynamic_attributes )*
									+ ">"
									#( + #children )*
									+ concat!("</", #tag, ">")
								}
							}
						};

						tokens.append_all(x);
					}

					// if has_attributes {
					//     let mut static_attributes = vec![];
					//     let mut dynamic_attributes = vec![];
					//     for attribute in &html_tag.attributes {
					//         if attribute.is_static() {
					//             static_attributes.push(attribute.to_token_stream());
					//         } else {
					//             dynamic_attributes.push(attribute.to_token_stream());
					//         }
					//     }
					//     // let &(static_attributes, dynamic_attributes) = &html_tag.attributes.iter().partition(|e| e.is_static());
					//
					//     let children = &html_tag.children;
					//
					//     // let format_string = format!("<{tag}{}>{}</{tag}>", (" {}".repeat(attributes.len()).as_str()), ("{}".repeat(children.len()).as_str()));
					//
					//     let tag_tokens = quote! {
					//         concat!("<", #tag #(, " ", #static_attributes)*)
					//         #(
					//             + " " + #dynamic_attributes
					//         )*
					//         + ">"
					//         #(
					//             + #children
					//         )*
					//         + concat!("</", #tag, ">")
					//
					//         //format!( #format_string, #( #attributes ),*, #( #children ),* )
					//     };
					//
					//     tokens.append_all(tag_tokens);
					// } else {
					//     let children = &html_tag.children;
					//
					//     let tag_tokens = quote! {
					//         concat!("<", #tag, ">")
					//         #(
					//             + #children
					//         )*
					//         + concat!("</", #tag, ">")
					//
					//         //format!( #format_string, #( #children ),* )
					//     };
					//
					//     tokens.append_all(tag_tokens);
					// }
				};
			}
			Content::ControlTag(control_tag) => {
				control_tag.to_tokens(tokens);
			}
			Content::Literal(literal) => {
				literal.to_tokens(tokens);
			}
			Content::Expression(expr) => quote!(tidos::sanitize!(#expr)).to_tokens(tokens),
			Content::RawHTMLExpression(expr) => quote!(&#expr).to_tokens(tokens),
		}
	}
}

fn custom_element_to_tokens(
	tag: &str,
	html_tag: &HTMLTag,
	tokens: &mut TokenStream,
) -> TokenStream {
	let attributes = html_tag.attributes.iter().map(|attribute| {
		let name = &attribute.name;
		let value = &attribute.value;
		quote! { #name: #value }
	});

	let component_name = Ident::new(tag, Span::call_site()).to_token_stream();

	quote! { &#component_name { #( #attributes ),* }.to_render(page) }
}

#[derive(Debug)]
pub struct HTMLTag {
	pub tag: String,
	pub attributes: Vec<Attribute>,
	pub children: Vec<Content>,
	pub is_self_closing: bool,
}

#[derive(Debug)]
pub struct Attribute {
	pub is_toggle_attribute: bool,
	pub name: String,
	pub value: Option<TokenTree>,
}

impl Attribute {
	fn is_static(&self) -> bool {
		if self.is_toggle_attribute {
			return false;
		}
		match &self.value {
			None => true,
			Some(token) => {
				match token {
					TokenTree::Group(_) => false,
					// todo identifier of scoped css is static
					TokenTree::Literal(_) => true,
					_ => {
						panic!("Tidos macro error: expected group or ident")
					}
				}
			}
		}
	}
}

impl ToTokens for Attribute {
	fn to_tokens(&self, tokens: &mut TokenStream) {
		match (&self.value, &self.is_toggle_attribute) {
			// :disabled
			(None, true) => {
				let ident = format_ident!("{}", &self.name);
				let attribute_name = &self.name.to_string();

				tokens.append_all(quote! {
					if #ident { #attribute_name } else { "" }
				});
			}
			// disabled
			(None, false) => {
				let attribute_name = &self.name.to_string();
				tokens.append_all(quote! {
					#attribute_name
				});
			}
			// :disabled={ true }
			(Some(value), true) => {
				let attribute_name = &self.name.to_string();
				tokens.append_all(quote! {
					if #value { #attribute_name } else { "" }
				});
			}
			// class="wrapper" or value={ person.name }
			(Some(value), false) => {
				let attribute_name = &(&self.name)
					.clone()
					.to_string()
					.trim_start_matches("r#")
					.to_string();

				match value {
					TokenTree::Group(group) => {
						tokens.append_all(quote! {
							concat!(#attribute_name, "=\"") + &tidos::sanitize!(#group) + "\""

							//format!("{}=\"{}\"", #attribute_name, tidos::sanitize!(#value.to_string()) )
						});
					}
					TokenTree::Literal(literal) => {
						tokens.append_all(quote! {
							concat!(#attribute_name, "=\"", #literal, "\"")

							//format!("{}=\"{}\"", #attribute_name, tidos::sanitize!(#value.to_string()) )
						});
					}
					_ => {
						panic!("Tidos macro error: expected group or ident")
					}
				}
			}
		}
	}
}

#[derive(Debug)]
pub struct Component {
	pub children: Vec<Content>,
}

impl ToTokens for Component {
	fn to_tokens(&self, tokens: &mut TokenStream) {
		let children = &self.children;
		let binding = "{}".repeat(children.len());
		let format_string = binding.as_str();
		let x = { String::from(String::new()) + &String::from("Hello") };
		tokens.append_all(quote! {
			String::new()
				#(
					+ #children
				)*

		});
	}
}

pub struct PageWrapper {
	component: Component,
}

impl Parse for PageWrapper {
	fn parse(input: ParseStream) -> syn::Result<Self> {
		let component = Component::parse(input)?;
		Ok(PageWrapper { component })
	}
}

impl ToTokens for PageWrapper {
	fn to_tokens(&self, tokens: &mut TokenStream) {
		let input = self.component.to_token_stream();
		tokens.append_all(quote! {
			{
				let mut page_output = Page::new();
				page_output.template = {
					let page = &mut page_output;
					#input
				};
				page_output
			}

		});
	}
}