nbnf_language 0.0.1

A parser for the NBNF language itself, and the parser generator
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
use std::collections::{HashMap, HashSet};
use std::iter::Peekable;
use std::mem::discriminant;
use std::rc::Rc;

use anyhow::{Result as AResult, bail, ensure};

use crate::{Literal, Token};

/// A parsed grammar.
#[derive(Clone, Debug)]
pub struct Grammar {
	/**
		The topmost (first) rule in the grammar.

		Conventionally, this is the root rule acting as the grammar's entrypoint.
	*/
	pub top_rule: Rc<String>,

	/// The rules in this grammar.
	pub rules: HashMap<Rc<String>, Rule>,

	/**
		Rule names in the order as defined in the grammar.

		This is used by the generator to emit parser functions in the same order as their defining rules.
	*/
	pub rule_order: Vec<Rc<String>>,
}

/// A rule.
#[derive(Clone, Debug)]
pub struct Rule {
	/// A string of Rust source denoting the type of this rule's output.
	pub output_type: String,
	/// The root expression of this rule.
	pub body: Expr,
}

/// A grammar expression.
#[derive(Clone, Debug)]
pub enum Expr {
	/// Match a literal.
	Literal(Literal),
	/// Match some other parser.
	Rule(String),
	/// Match a group of expressions.
	Group(Vec<Expr>),
	/**
		Match one of a group of expressions.

		Wraps the inner expression with [alt][nom::branch::alt].
	*/
	Alternate(Vec<Expr>),
	/**
		Match an expression repeatedly.

		Wraps the inner expression with one of [many0][nom::multi::many0], [many1][nom::multi::many1], [many_m_n][nom::multi::many_m_n].
	*/
	Repeat {
		/// The inner expression to match.
		expr: Box<Expr>,
		/// The minimum number of times to repeat.
		min: usize,
		/// The maximum number of times to repeat, if any.
		max: Option<usize>,
	},
	/**
		Match an expression but discard its output from the parent expression's output.

		Wraps the inner expression with a generated map function like
		```
		map(
			inner,
			|(_, p1, _, p2)| (p1, p2),
		)
		```
	*/
	Discard(Box<Expr>),
	/**
		Match only if the inner expression does not.

		Wraps the inner expression with [not][nom::combinator::not].
	*/
	Not(Box<Expr>),
	/**
		Match an expression that should fail irrecoverably, preventing backtracking.

		Wraps the inner expression with [cut][nom::combinator::cut].
	*/
	Cut(Box<Expr>),
	/**
		Match an expression but replace its output with the string of input it matched.

		Wraps the inner expression with [recognize][nom::combinator::recognize].
	*/
	Recognize(Box<Expr>),
	/**
		Match the empty string.

		A shortcut for [success][nom::combinator::success].
	*/
	Epsilon,
	/**
		Apply a mapping function.

		Wraps the inner expression with one of [value][nom::combinator::value], [map][nom::combinator::map], [map_opt][nom::combinator::map_opt], [map_res][nom::combinator::map_res].
	*/
	Map {
		/// The inner expression to match.
		expr: Box<Expr>,
		/// The type of mapping function to apply.
		func: MapFunc,
		/// The code to apply as the mapping function.
		mapping_code: String,
	},
}

/// Mapping function applied by [Map][Expr::Map].
#[derive(Clone, Debug)]
pub enum MapFunc {
	/// Applies [value](nom::combinator::value).
	Value,
	/// Applies [map](nom::combinator::map).
	Map,
	/// Applies [map_opt](nom::combinator::map_opt).
	MapOpt,
	/// Applies [map_res](nom::combinator::map_res).
	MapRes,
}

impl From<Token> for MapFunc {
	fn from(token: Token) -> Self {
		match token {
			Token::Value => Self::Value,
			Token::Map => Self::Map,
			Token::MapOpt => Self::MapOpt,
			Token::MapRes => Self::MapRes,
			_ => panic!("no MapFunc for {token:?}"),
		}
	}
}

/// Parse a list of tokens into a grammar.
pub fn parse(tokens: Vec<Token>) -> AResult<Grammar> {
	ensure!(!tokens.is_empty());
	let mut parser = Parser(tokens.into_iter().peekable());
	parser.parse()
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Modifier {
	Discard,
	Not,
	Cut,
	Recognize,
}

impl From<Token> for Modifier {
	fn from(token: Token) -> Self {
		match token {
			Token::Discard => Self::Discard,
			Token::Not => Self::Not,
			Token::Cut => Self::Cut,
			Token::Recognize => Self::Recognize,
			_ => panic!("no Modifier for {token:?}"),
		}
	}
}

struct Parser<Iter: Iterator>(Peekable<Iter>);

impl<Iter: Iterator<Item = Token> + ExactSizeIterator> Parser<Iter> {
	fn peek(&mut self) -> Option<&Token> {
		self.0.peek()
	}

	fn pop(&mut self) -> Option<Token> {
		self.0.next()
	}

	fn expect(&mut self, expected: Token) -> AResult<Token> {
		let Some(token) = self.pop() else {
			bail!("expecting {expected:?} but found eof")
		};
		ensure!(
			discriminant(&token) == discriminant(&expected),
			"expecting {expected:?} but found {token:?}",
		);
		Ok(token)
	}

	fn parse(&mut self) -> AResult<Grammar> {
		let mut rules = HashMap::new();
		let mut top_rule = None;
		let mut rule_order = vec![];
		while let Some(token) = self.pop() {
			let Token::Rule(rule_name) = token else {
				bail!("expected identifier to start rule definition but got {token:?}")
			};
			let rule_name = Rc::new(rule_name);
			if top_rule.is_none() {
				top_rule = Some(rule_name.clone());
			}

			let output_type = match self.peek() {
				Some(Token::RustSrc(_)) => {
					let Some(Token::RustSrc(ty)) = self.pop() else {
						unreachable!()
					};
					ty
				},
				_ => "&str".into(),
			};

			self.expect(Token::Equals)?;
			let body = self.parse_expr()?;
			self.expect(Token::Semicolon)?;
			ensure!(
				rules
					.insert(rule_name.clone(), Rule { output_type, body })
					.is_none(),
				"found duplicate rule {rule_name:?}"
			);
			rule_order.push(rule_name);
		}
		let top_rule = top_rule.unwrap();
		Ok(Grammar {
			top_rule,
			rules,
			rule_order,
		})
	}

	fn parse_expr(&mut self) -> AResult<Expr> {
		let mut alts = vec![];
		let mut exprs = vec![];
		let mut pending_modifiers = HashSet::new();
		let mut last_len = usize::MAX;
		while self.peek().is_some() {
			let len = self.0.len();
			if len == last_len {
				panic!(
					"parse_rule_body stuck in infinite loop at token {:?}",
					self.0.peek()
				);
			}
			last_len = len;

			if let Ok(expr) = self.parse_operand() {
				exprs.push(expr);
				self.process_modifiers(&mut exprs, &mut pending_modifiers);
				continue;
			}

			let Some(token) = self.peek() else { break };
			match token {
				Token::GroupOpen => {
					let group = self.parse_group()?;
					exprs.push(group);
				},
				Token::Slash => {
					self.pop().unwrap_or_else(|| unreachable!());
					match exprs.len() {
						0 => bail!("found alternate with illegal leading slash"),
						1 => {
							let Some(expr) = exprs.pop() else {
								unreachable!()
							};
							alts.push(expr);
						},
						_ => {
							alts.push(Expr::Group(exprs));
							exprs = vec![];
						},
					}
				},
				Token::Repeat { .. } => {
					let Some(Token::Repeat { min, max }) = self.pop() else {
						unreachable!()
					};
					let Some(last) = exprs.pop() else {
						bail!("found repeat at start of rule body/group")
					};
					let last = last.into();
					exprs.push(Expr::Repeat {
						expr: last,
						min,
						max,
					})
				},
				Token::Discard | Token::Not | Token::Cut | Token::Recognize => {
					let token = self.pop().unwrap_or_else(|| unreachable!());
					pending_modifiers.insert(token.into());
					continue;
				},
				Token::Value | Token::Map | Token::MapOpt | Token::MapRes => {
					let Some(token) = self.pop() else {
						unreachable!()
					};
					let Token::RustSrc(mapping_code) =
						self.expect(Token::RustSrc(String::new()))?
					else {
						unreachable!()
					};
					let Some(expr) = exprs.pop() else {
						bail!("found mapping function without any expression to map")
					};
					let expr = Box::new(expr);
					let func = token.into();
					exprs.push(Expr::Map {
						func,
						mapping_code,
						expr,
					});
					continue;
				},
				Token::Semicolon | Token::GroupClose => {
					self.process_modifiers(&mut exprs, &mut pending_modifiers);
					break;
				},
				_ => bail!("got unexpected {token:?} when parsing rule body"),
			}

			self.process_modifiers(&mut exprs, &mut pending_modifiers);
		}

		ensure!(
			pending_modifiers.is_empty(),
			"unprocessed modifiers: {pending_modifiers:?}"
		);
		Ok(if !alts.is_empty() {
			ensure!(
				!exprs.is_empty(),
				"found alternate with illegal trailing slash"
			);
			match exprs.len() {
				0 => bail!("found alternate with illegal trailing slash"),
				1 => {
					let Some(expr) = exprs.pop() else {
						unreachable!()
					};
					alts.push(expr);
				},
				_ => {
					alts.push(Expr::Group(exprs));
				},
			}
			Expr::Alternate(alts)
		} else if exprs.len() != 1 {
			Expr::Group(exprs)
		} else {
			let Some(rule) = exprs.into_iter().next() else {
				unreachable!()
			};
			rule
		})
	}

	fn process_modifiers(
		&mut self,
		exprs: &mut Vec<Expr>,
		pending_modifiers: &mut HashSet<Modifier>,
	) {
		if !pending_modifiers.is_empty() {
			let Some(mut expr) = exprs.pop() else {
				panic!("trying to process modifiers but no expression to pop")
			};

			if pending_modifiers.contains(&Modifier::Not) {
				expr = Expr::Not(expr.into());
				pending_modifiers.remove(&Modifier::Not);
			}
			if pending_modifiers.contains(&Modifier::Recognize) {
				expr = Expr::Recognize(expr.into());
				pending_modifiers.remove(&Modifier::Recognize);
			}
			if pending_modifiers.contains(&Modifier::Cut) {
				expr = Expr::Cut(expr.into());
				pending_modifiers.remove(&Modifier::Cut);
			}
			if pending_modifiers.contains(&Modifier::Discard) {
				expr = Expr::Discard(expr.into());
				pending_modifiers.remove(&Modifier::Discard);
			}
			assert!(
				pending_modifiers.is_empty(),
				"unimplemented modifiers: {pending_modifiers:?}"
			);

			exprs.push(expr);
		}
	}

	fn parse_group(&mut self) -> AResult<Expr> {
		self.expect(Token::GroupOpen)?;
		let body = self.parse_expr()?;
		self.expect(Token::GroupClose)?;
		Ok(body)
	}

	fn parse_operand(&mut self) -> AResult<Expr> {
		let Some(token) = self.peek() else {
			bail!("trying to parse rule operand but got eof")
		};
		Ok(match token {
			Token::Rule(_) => {
				let Some(Token::Rule(rule_name)) = self.pop() else {
					unreachable!()
				};
				Expr::Rule(rule_name)
			},
			Token::Literal(_) => {
				let Some(Token::Literal(literal)) = self.pop() else {
					unreachable!()
				};
				Expr::Literal(literal)
			},
			Token::Epsilon => {
				self.pop().unwrap_or_else(|| unreachable!());
				Expr::Epsilon
			},
			_ => bail!("expecting rule expr but got {token:?}"),
		})
	}
}