beet_parse 0.0.8

Parsers for various text and token formats
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
use crate::prelude::*;
use beet_core::prelude::*;
use beet_dom::prelude::*;
use beet_rsx_combinator::prelude::*;
use std::collections::HashSet;

/// A [`String`] of rsx tokens to be parsed into a node tree, which can then
/// be extracted into a [`Bundle`] [`TokenStream`] via [`tokenize_rsx`]
/// or [`tokenize_rsx_tokens`].
#[derive(Default, Component, Deref, Reflect)]
#[reflect(Default, Component)]
#[require(SnippetRoot)]
pub struct CombinatorTokens(String);

impl CombinatorTokens {
	/// Create a new [`CombinatorTokens`] from a string.
	pub fn new(tokens: impl Into<String>) -> Self { Self(tokens.into()) }
}


pub(super) fn parse_combinator_tokens(
	_: TempNonSendMarker,
	constants: Res<HtmlConstants>,
	mut commands: Commands,
	query: Populated<
		(Entity, &CombinatorTokens, &SnippetRoot),
		Added<CombinatorTokens>,
	>,
) -> bevy::prelude::Result {
	for (entity, tokens, snippet_root) in query.iter() {
		Builder {
			raw_text_elements: &constants.raw_text_elements,
			file_path: &snippet_root.file,
			commands: &mut commands,
			expr_idx: ExprIdxBuilder::new(),
		}
		.map_to_children(entity, tokens)?;
		commands.entity(entity).remove::<CombinatorTokens>();
	}
	Ok(())
}


/// For a given string of rsx, use [`beet_rsx_combinator`] to parse.
struct Builder<'w, 's, 'a> {
	// the content of these tags will not be parsed and instead inserted
	// as a [`TextNode`]
	raw_text_elements: &'a HashSet<&'static str>,
	file_path: &'a WsPathBuf,
	expr_idx: ExprIdxBuilder,
	commands: &'a mut Commands<'w, 's>,
}

impl<'w, 's, 'a> Builder<'w, 's, 'a> {
	fn map_to_children(
		mut self,
		root: Entity,
		rsx: &CombinatorTokens,
	) -> Result {
		let children = CombinatorParser::parse(&rsx).map_err(|e| {
			bevyhow!("Failed to parse Combinator RSX: {}", e.to_string())
		})?;

		let children = self.rsx_children("fragment", children)?;
		self.commands.entity(root).add_children(&children);
		Ok(())
	}

	// not ideal but we dont have spans for beet_rsx_combinator yet
	fn default_file_span(&self) -> FileSpan {
		FileSpan::new_for_file(&self.file_path)
	}
	/// insert a [`CombinatorExpr`] into the entity,
	/// as these are eventually collected into a [`NodeExpr`] each
	/// is assigned an [`ExprIdx`]
	fn rsx_parsed_expression(
		&mut self,
		entity: Entity,
		expr: RsxParsedExpression,
	) -> Result<()> {
		let partials = expr
			.inner()
			.into_iter()
			.map(|item| self.rsx_tokens_or_element(item))
			.collect::<Result<Vec<_>>>()?;

		let file_span = self.default_file_span();
		self.commands.entity(entity).insert((
			CombinatorExpr(partials),
			FileSpanOf::<CombinatorExpr>::new(file_span),
		));
		Ok(())
	}

	fn rsx_tokens_or_element(
		&mut self,
		tokens: RsxTokensOrElement,
	) -> Result<CombinatorExprPartial> {
		match tokens {
			RsxTokensOrElement::Tokens(tokens) => {
				CombinatorExprPartial::Tokens(tokens)
			}
			RsxTokensOrElement::Element(el) => {
				CombinatorExprPartial::Element(self.rsx_element(el)?)
			}
		}
		.xok()
	}

	fn rsx_fragment(&mut self, fragment: RsxFragment) -> Result<Entity> {
		let children = self.rsx_children("fragment", fragment.0)?;
		let file_span = self.default_file_span();
		self.commands
			.spawn((FragmentNode, FileSpanOf::<FragmentNode>::new(file_span)))
			.add_children(&children)
			.id()
			.xok()
	}

	fn rsx_element(&mut self, element: RsxElement) -> Result<Entity> {
		let (element_name, attributes, children, self_closing) = match element {
			RsxElement::Fragment(fragment) => {
				return self.rsx_fragment(fragment);
			}
			RsxElement::SelfClosing(el) => {
				(el.0, el.1, RsxChildren::default(), true)
			}
			RsxElement::Normal(el) => (el.0, el.1, el.2, false),
		};
		let tag_str = element_name.to_string();

		let file_span = self.default_file_span();

		let mut entity = self.commands.spawn((
			NodeTag(tag_str.clone()),
			FileSpanOf::<NodeTag>::new(self.default_file_span()),
		));

		if tag_str.starts_with(|c: char| c.is_uppercase()) {
			entity.insert((
				self.expr_idx.next(),
				TemplateNode,
				FileSpanOf::<TemplateNode>::new(file_span),
			));
		} else {
			entity.insert((
				ElementNode { self_closing },
				FileSpanOf::<ElementNode>::new(file_span),
			));
		}
		let entity = entity.id();

		attributes
			.0
			.into_iter()
			.map(|attr| self.spawn_attribute(entity, attr))
			.collect::<Result<Vec<_>>>()?;

		let children = self.rsx_children(&tag_str, children)?;
		self.commands.entity(entity).add_children(&children);

		entity.xok()
	}

	fn rsx_children(
		&mut self,
		tag_str: &str,
		children: RsxChildren,
	) -> Result<Vec<Entity>> {
		if self.raw_text_elements.contains(&tag_str) {
			vec![
				self.commands
					.spawn((
						TextNode::new(children.to_html()),
						FileSpanOf::<TextNode>::new(self.default_file_span()),
					))
					.id(),
			]
			.xok()
		} else {
			children
				.0
				.into_iter()
				.map(|child| self.rsx_child(child))
				.collect::<Result<Vec<_>>>()?
				.xok()
		}
	}

	fn rsx_child(&mut self, child: RsxChild) -> Result<Entity> {
		match child {
			RsxChild::Element(el) => self.rsx_element(el),
			RsxChild::Text(text) => self.rsx_text(text),
			RsxChild::CodeBlock(code_block) => {
				let entity =
					self.commands.spawn((BlockNode, self.expr_idx.next())).id();
				self.rsx_parsed_expression(entity, code_block)?;
				entity.xok()
			}
		}
	}

	fn rsx_text(&mut self, text: RsxText) -> Result<Entity> {
		self.commands
			.spawn((
				TextNode::new(text.0.to_string()),
				FileSpanOf::<TextNode>::new(self.default_file_span()),
			))
			.id()
			.xok()
	}

	fn spawn_attribute(
		&mut self,
		parent: Entity,
		attribute: RsxAttribute,
	) -> Result<()> {
		match attribute {
			RsxAttribute::Spread(value) => {
				let entity = self
					.commands
					.spawn((
						AttributeOf::new(parent),
						FileSpanOf::<NodeExpr>::new(self.default_file_span()),
					))
					.id();
				self.commands.entity(parent).insert(self.expr_idx.next());
				self.rsx_parsed_expression(entity, value)?;
			}
			RsxAttribute::Named(name, value) => {
				let mut entity = self.commands.spawn((
					AttributeKey::new(name.to_string()),
					AttributeOf::new(parent),
					FileSpanOf::<AttributeOf>::new(self.default_file_span()),
				));
				match value {
					RsxAttributeValue::Default => {
						// key only attribute
					}
					RsxAttributeValue::Boolean(val) => {
						let val = val.0;
						entity.insert((
							NodeExpr::new(syn::parse_quote! {#val}),
							val.into_bundle(),
						));
					}
					RsxAttributeValue::Number(val) => {
						let val = val.0;
						entity.insert((
							NodeExpr::new(syn::parse_quote! {#val}),
							val.into_bundle(),
						));
					}
					RsxAttributeValue::Str(val) => {
						let val = val.to_string_unquoted();
						entity.insert((
							NodeExpr::new(syn::parse_quote! {#val}),
							TextNode::new(val),
						));
					}
					RsxAttributeValue::Element(value) => {
						let id = entity.id();
						// get ExprIdx before evaluating element
						let expr_id = self.expr_idx.next();
						let child = self.rsx_element(value)?;
						self.commands.entity(id).insert((
							expr_id,
							CombinatorExpr(vec![
								CombinatorExprPartial::Element(child),
							]),
						));
					}
					RsxAttributeValue::CodeBlock(value) => {
						entity.insert(self.expr_idx.next());
						let entity = entity.id();
						self.rsx_parsed_expression(entity, value)?;
					}
				}
			}
		}
		.xok()
	}
}


#[cfg(test)]
mod test {
	use crate::prelude::*;
	use beet_core::prelude::*;
	use proc_macro2::TokenStream;

	fn parse(str: &str) -> TokenStream {
		ParseRsxTokens::combinator_to_rsx(str, WsPathBuf::new(file!()))
			.unwrap()
	}

	#[test]
	fn element() { "<br/>".xmap(parse).xpect_snapshot(); }
	#[test]
	fn fragment() {
		"<br/><br/>"
			.xmap(|str| {
				ParseRsxTokens::combinator_to_rsx(
					str,
					WsPathBuf::new(file!()),
				)
				.unwrap()
			})
			.xpect_snapshot();
	}
	#[test]
	fn unclosed() { "<div align=\"center\" />".xmap(parse).xpect_snapshot(); }

	#[test]
	fn text() { "<div>hello</div>".xmap(parse).xpect_snapshot(); }

	#[test]
	fn block() { r#"{"hello"}"#.xmap(parse).xpect_snapshot(); }



	#[test]
	fn element_attributes_default() {
		"<br foo />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn element_attributes_string() {
		"<br foo=\"bar\"/>".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn element_attributes_bool() {
		"<br foo=true />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn element_attributes_number() {
		"<br foo=20 />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn element_attributes_block_value() {
		"<br foo={bar} />".xmap(parse).xpect_snapshot();
	}
	#[test]
	fn element_attributes_spread() {
		"<br {...bar} />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn element_attributes_element() {
		"<br foo={<br/>} />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn element_attributes_mixed() {
		"<br foo={
			let bar = <br/>;
			bar
		} />"
			.xmap(parse)
			.xpect_snapshot();
	}

	#[test]
	fn template_attributes_default() {
		"<MyTemplate foo />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn template_attributes_string() {
		"<MyTemplate foo=\"bar\"/>".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn template_attributes_bool() {
		"<MyTemplate foo=true />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn template_attributes_number() {
		"<MyTemplate foo=20 />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn template_attributes_ident() {
		"<MyTemplate foo={bar} />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn template_attributes_element() {
		"<MyTemplate foo={<br/>} />".xmap(parse).xpect_snapshot();
	}

	#[test]
	fn template_attributes_mixed() {
		r#"<MyTemplate foo={
			let bar = <br/>;
			bar
		} />"#
			.xmap(parse)
			.xpect_snapshot();
	}
	#[cfg(feature = "css")]
	#[test]
	fn style() {
		r#"
<div> hello world </div>
<style>
	main{
		padding-top: 2em;
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100vh;
	}
	a {
		color: #90ee90;
	}
	a:visited {
		color: #3399ff;
	}
</style>
<style scope:global>
	body{
		font-size: 1.4em;
		font-family: system-ui, sans-serif;
		background: black;
		color: white;
	}
</style>
"#
		.xmap(parse)
		.xpect_snapshot();
	}
	#[test]
	#[ignore = "todo combinator raw text"]
	fn preserves_whitespace() {
		let out = ParseRsxTokens::combinator_to_rsx(
			r#"
<pre><code class="language-rust">// A simple Rust function
fn fibonacci(n: u32) -&gt; u32 {
    match n {
        0 =&gt; 0,
        1 =&gt; 1,
        _ =&gt; fibonacci(n - 1) + fibonacci(n - 2),
    }
}

fn main() {
    let result = fibonacci(10);
    println!("The 10th Fibonacci number is: {}", result);
}
</code></pre>
		"#,
			WsPathBuf::new(file!()),
		)
		.unwrap();
		out.to_string().xpect_contains("\nfn main()");
		out.xpect_snapshot();
	}
}