teacat_lib 0.5.0

Tools for working with TeaCat files
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
use std::collections::HashMap;

use crate::{
	CatResult, Moo,
	parser::{
		escape_codes::proc_str,
		markup::{parse_header, parse_markup},
		tags::parse_tag,
	},
	prelude::*,
};
use grammar::{Rule, TeaCatGrammar};
use pest::{
	Parser,
	iterators::{Pair, Pairs},
};

mod escape_codes;
mod markup;
mod tags;

type TeaPair<'i> = Pair<'i, Rule>;
type TeaPairs<'i> = Pairs<'i, Rule>;

#[derive(Debug, PartialEq, Clone)]
pub struct TeaCatAst<'input> {
	pub contents: Vec<AstNode<'input>>,
	pub module: bool,
}

#[derive(Debug, PartialEq, Clone)]
pub enum AstNode<'input> {
	Space,
	Word(Moo<'input>),
	Tag(Tag<'input>),
	ContentBlock(TeaCatAst<'input>),
	Markup {
		of: MarkupType,
		inner: TeaCatAst<'input>,
	},
	Define {
		name: Moo<'input>,
		content: Box<AstNode<'input>>,
	},
	With {
		path: ModuleName,
		imports: Vec<Moo<'input>>,
	},
	Variable(Moo<'input>),
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MarkupType {
	Bold,
	Italic,
	Strikethrough,
	Underline,
	Header(u8),
}

#[derive(Debug, PartialEq, Clone, Default)]
pub struct Attributes<'input>(pub HashMap<Moo<'input>, Moo<'input>>);

#[derive(Debug, PartialEq, Clone)]
pub struct Tag<'input> {
	pub name: Moo<'input>,
	pub attrs: Attributes<'input>,
	pub content: TeaCatAst<'input>,
}

impl<'input> TryFrom<&'input str> for TeaCatAst<'input> {
	type Error = TeaCatErr;

	fn try_from(src: &'input str) -> CatResult<Self> {
		let mut pairs = TeaCatGrammar::parse(Rule::teacat, src)?
			.next()
			.expect("Parsing should output something")
			.into_inner();

		let is_module = if let Some(pair) = pairs.peek()
			&& pair.as_rule() == Rule::module
		{
			pairs.next();
			true
		} else {
			false
		};

		let pair = pairs
			.next()
			.expect("Rule teacat must contain line_sequence!");
		assert_eq!(pair.as_rule(), Rule::line_sequence);

		let mut ast = parse_line_sequence(pair);
		ast.module = is_module;
		Ok(ast)
	}
}

impl<'input> From<Vec<AstNode<'input>>> for TeaCatAst<'input> {
	fn from(contents: Vec<AstNode<'input>>) -> Self {
		Self {
			contents,
			module: false,
		}
	}
}

impl TeaCatAst<'_> {
	/// Clones the [`TeaCatAst`], converting all contained [`Cow`](std::borrow::Cow)
	/// pointers to [`Cow::Owned`](std::borrow::Cow::Owned).
	#[must_use]
	pub fn owned(&self) -> TeaCatAst<'static> {
		TeaCatAst {
			contents: self.contents.iter().map(AstNode::owned).collect(),
			module: self.module,
		}
	}
}

impl<'i> IntoIterator for TeaCatAst<'i> {
	type Item = AstNode<'i>;
	type IntoIter = std::vec::IntoIter<Self::Item>;

	fn into_iter(self) -> Self::IntoIter {
		self.contents.into_iter()
	}
}

impl AstNode<'_> {
	/// Clones the [`AstNode`], converting all contained [`Cow`](std::borrow::Cow)
	/// pointers to [`Cow::Owned`](std::borrow::Cow::Owned).
	#[must_use]
	pub fn owned(&self) -> AstNode<'static> {
		match self {
			Self::Space => AstNode::Space,
			Self::Word(moo) => AstNode::Word(Moo::Owned(moo.clone().into_owned())),
			Self::Tag(tag) => AstNode::Tag(tag.owned()),
			Self::ContentBlock(ast) => AstNode::ContentBlock(ast.owned()),
			Self::Markup { of, inner } => AstNode::Markup {
				of: *of,
				inner: inner.owned(),
			},
			Self::Define { name, content } => AstNode::Define {
				name: Moo::Owned(name.clone().into_owned()),
				content: content.owned().into(),
			},
			Self::With { path, imports } => AstNode::With {
				path: path.clone(),
				imports: imports
					.iter()
					.map(Moo::clone)
					.map(Moo::into_owned)
					.map(Moo::Owned)
					.collect(),
			},
			Self::Variable(moo) => AstNode::Variable(Moo::Owned(moo.clone().into_owned())),
		}
	}
}

impl Tag<'_> {
	/// Clones the [`Tag`], converting all contained [`Cow`](std::borrow::Cow)
	/// pointers to [`Cow::Owned`](std::borrow::Cow::Owned).
	#[must_use]
	pub fn owned(&self) -> Tag<'static> {
		Tag {
			name: self.name.clone().into_owned().into(),
			attrs: Attributes(
				self.attrs
					.0
					.iter()
					.map(|(k, v)| (k.clone().into_owned().into(), v.clone().into_owned().into()))
					.collect(),
			),
			content: self.content.owned(),
		}
	}
}

fn parse_line_sequence(pair: TeaPair) -> TeaCatAst {
	assert_eq!(pair.as_rule(), Rule::line_sequence);

	let mut inner = pair
		.into_inner()
		.map(parse_line)
		.filter(|line| !matches!(line[..], [] | [AstNode::Space]))
		.flat_map(|mut line| {
			if line.last().is_some_and(|item| *item != AstNode::Space) {
				line.push(AstNode::Space);
			}
			line
		})
		.collect::<Vec<_>>();

	// Remove trailing space
	inner.pop();

	inner.into()
}

fn parse_line(pair: TeaPair) -> Vec<AstNode> {
	assert_eq!(pair.as_rule(), Rule::line);

	let pair = pair.into_inner().next().expect("Line must contain rule!");

	match pair.as_rule() {
		Rule::def => vec![parse_def(pair)],
		Rule::with => vec![parse_with(pair)],
		Rule::tag_raw | Rule::tag_sameline | Rule::tag_multiline => {
			vec![parse_tag(pair.into_inner())]
		}
		Rule::content_block => vec![parse_content_block(pair)],
		Rule::header => vec![parse_header(pair)],
		Rule::line_content => parse_line_content(pair),
		other => panic!("Unexpected rule in line: {other:?}"),
	}
}

fn parse_line_content(pair: TeaPair) -> Vec<AstNode> {
	assert_eq!(pair.as_rule(), Rule::line_content);

	pair.into_inner()
		.map(|pair| match pair.as_rule() {
			Rule::var => AstNode::Variable(pair.as_str()[1..].into()),
			Rule::tag_inline => parse_tag(pair.into_inner()),
			Rule::content_block_inline => parse_content_block(pair),
			Rule::markup => parse_markup(pair),
			Rule::word => AstNode::Word(proc_str(pair)),
			Rule::space => AstNode::Space,
			other => panic!("Unexpected rule in line_content: {other:?}"),
		})
		.collect()
}

fn parse_def(pair: TeaPair) -> AstNode {
	assert_eq!(pair.as_rule(), Rule::def);

	let mut pairs = pair.into_inner();
	let name = pairs.next().expect("Rule def must contain ident!");
	let content = pairs
		.next()
		.expect("Rule def must contain def_content!")
		.into_inner()
		.next()
		.expect("Rule def_content must contain content!");

	let content = match content.as_rule() {
		Rule::content_block => parse_content_block(content),
		Rule::tag_multiline | Rule::tag_raw => parse_tag(content.into_inner()),
		other => panic!("Unexpected rule in def_content: {other:?}"),
	};

	AstNode::Define {
		name: name.as_str().into(),
		content: Box::new(content),
	}
}

fn parse_with(pair: TeaPair) -> AstNode {
	assert_eq!(pair.as_rule(), Rule::with);

	let mut pairs = pair.into_inner();
	let mut path = vec![];
	let mut imports = vec![];

	while let Some(pair) = pairs.peek()
		&& pair.as_rule() == Rule::ident
	{
		pairs.next();
		path.push(pair.as_str().to_owned());
	}

	let mut pairs = pairs
		.next()
		.expect("Rule with must contain with_content!")
		.into_inner();

	while let Some(pair) = pairs.peek()
		&& pair.as_rule() == Rule::ident
	{
		pairs.next();
		imports.push(pair.as_str().into());
	}

	AstNode::With {
		path: ModuleName(path),
		imports,
	}
}

fn parse_content_block(pair: TeaPair) -> AstNode {
	let fun = if let Rule::content_block_inline = pair.as_rule() {
		|pair| parse_line_content(pair).into()
	} else {
		parse_line_sequence
	};

	AstNode::ContentBlock(fun(pair
		.into_inner()
		.next()
		.expect("Rule content_block must contain content")))
}

pub(crate) mod grammar {
	use pest_derive::Parser;

	#[derive(Parser)]
	#[grammar = "teacat.pest"]
	pub struct TeaCatGrammar;
}

#[cfg(test)]
mod tests {
	use std::collections::HashMap;

	use crate::parser::{Attributes, MarkupType, Tag};

	use super::{AstNode, TeaCatAst, grammar::*};
	use pest::Parser;

	/// Shorthand for making an AST
	macro_rules! tc_ast {
		($($elem:expr),*) => { TeaCatAst { contents: vec![$($elem),*], module: false } };
	}

	/// Shorthand for making a tag
	macro_rules! tc_tag {
		($tagname:ident ( $($argname:ident $content:literal),* ) $(,$item:expr)* $(,)?) => {
			AstNode::Tag(Tag {
				name: stringify!($tagname).into(),
				attrs: Attributes(HashMap::from([
					$((
						stringify!($argname).into(),
						$content.into()
					)),*
				])),
				content: tc_ast!($($item),*),
			})
		};
	}

	#[test]
	fn text() {
		parse("hello chat").unwrap();
	}

	#[test]
	fn single_line_tag() {
		parse(":test test\n").unwrap();
	}

	#[test]
	fn inline_tag() {
		parse(":test[test]").unwrap();
	}

	#[test]
	fn multi_line_tag() {
		parse(":test [\ntest\n]\n").unwrap();
	}

	#[test]
	fn pain() {
		assert!(parse(":a :a[\n]testing").is_err());
	}

	#[test]
	fn escape_codes() {
		parse(r":test \t\n\s\:3\u[1F431]").unwrap();
	}

	#[test]
	fn markup() {
		let ast =
			TeaCatAst::try_from("+bold+ and *italic* and ~strikethrough~ and _underline_").unwrap();
		let and = AstNode::Word("and".into());
		assert_eq!(
			ast,
			tc_ast![
				AstNode::Markup {
					of: MarkupType::Bold,
					inner: tc_ast![AstNode::Word("bold".into())]
				},
				AstNode::Space,
				and.clone(),
				AstNode::Space,
				AstNode::Markup {
					of: MarkupType::Italic,
					inner: tc_ast![AstNode::Word("italic".into())]
				},
				AstNode::Space,
				and.clone(),
				AstNode::Space,
				AstNode::Markup {
					of: MarkupType::Strikethrough,
					inner: tc_ast![AstNode::Word("strikethrough".into())]
				},
				AstNode::Space,
				and.clone(),
				AstNode::Space,
				AstNode::Markup {
					of: MarkupType::Underline,
					inner: tc_ast![AstNode::Word("underline".into())]
				}
			]
		);
	}

	#[test]
	fn markup_precedence() {
		let ast = TeaCatAst::try_from("+a*b+c*").unwrap();
		assert_eq!(
			ast,
			tc_ast![
				AstNode::Word("+a".into()),
				AstNode::Markup {
					of: MarkupType::Italic,
					inner: tc_ast![AstNode::Word("b+c".into())]
				}
			]
		);
	}

	#[test]
	fn escape_codes2() {
		let ast = TeaCatAst::try_from(r"\t\[\u[1f431]").unwrap();
		assert_eq!(ast, tc_ast![AstNode::Word("\t[🐱".into())]);
	}

	#[test]
	fn args() {
		let ast = TeaCatAst::try_from(r#":t(a "haii", b "chat")[]"#).unwrap();
		assert_eq!(ast, tc_ast![tc_tag![t(a "haii", b "chat")]]);
	}

	/// Direct wrapper around `TeaCatGrammar::parse`
	fn parse(input: &str) -> Result<pest::iterators::Pairs<'_, Rule>, pest::error::Error<Rule>> {
		TeaCatGrammar::parse(Rule::teacat, input)
	}
}