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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
/**
 * SMT2-lib syntax.
 */

use std::iter::Peekable;
use source_span::Span;

pub use crate::location::*;

pub mod error;
pub mod ast;
pub mod token;
pub mod lexer;
pub mod response;
pub mod display;

pub use error::*;
pub use ast::*;
pub use token::Token;
pub use lexer::Lexer;
pub use display::{Display, Formatter, PrettyPrint};

pub trait Parsable : Sized {
	/**
	 * Parse from a lexer.
	 * Separators are handled depending on the flavor parameter.
	 */
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Self>> where L: Iterator<Item=Result<Located<Token>>>;
}

/**
 * Peek the next token from a lexer.
 */
pub(crate) fn peek<L>(lexer: &mut Peekable<L>) -> Result<Located<Token>> where L: Iterator<Item=Result<Located<Token>>> {
	match lexer.peek() {
		Some(Ok(token)) => Ok(token.clone()),
		None => Ok(Token::EndOfFile.at(Span::default())),
		Some(Err(_)) => consume(lexer)
	}
}

/**
 * Consume the next token from a lexer.
 */
pub(crate) fn consume<L>(lexer: &mut Peekable<L>) -> Result<Located<Token>> where L: Iterator<Item=Result<Located<Token>>> {
	match lexer.next() {
		Some(Ok(token)) => Ok(token.clone()),
		None => Ok(Token::EndOfFile.at(Span::default())),
		Some(Err(error)) => Err(error)
	}
}

/**
 * Consume the next token and ensure it is of the given kind.
 */
pub(crate) fn consume_token<L>(lexer: &mut Peekable<L>, kind: Token) -> Result<Span> where L: Iterator<Item=Result<Located<Token>>> {
	let token = consume(lexer)?;
	if *token == kind {
		Ok(token.span())
	} else {
		Err(Error::UnexpectedToken(token.clone().into_inner(), Some(kind)).at(token.span()))
	}
}

pub(crate) fn parse_list<L, T: Parsable>(lexer: &mut Peekable<L>, loc: &mut Span) -> Result<Vec<Located<T>>> where L: Iterator<Item=Result<Located<Token>>> {
	use Token::*;
	let mut list = Vec::new();

	loop {
		let token = peek(lexer)?;
		match *token {
			End => {
				//println!("LIST end");
				consume(lexer)?;
				*loc = loc.union(token.span());
				break;
			},
			_ => {
				//println!("LIST parse");
				let t = T::parse(lexer)?;
				list.push(t);
			}
		}
	}

	Ok(list)
}

// impl Parsable for Constant {
//	 fn parse<L>(lexer: &mut Peekable<L>) -> Result<Constant> where L: Iterator<Item=Result<Located<Token>>> {
//		 use Token::*;
//		 let token = consume(lexer)?;
//		 let loc = token.span();
//		 match *token {
//			 Litteral(token::Litteral::Int(i)) => Ok(Constant::Int(i)),
//			 unexpected => Err(Error::UnexpectedToken(unexpected, None).at(loc))
//		 }
//	 }
// }

impl Parsable for Symbol {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Symbol>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let token = consume(lexer)?;
		let loc = token.span();
		match token.into_inner() {
			Ident(name) => Ok(Located::new(Symbol {
				id: name.clone()
			}, loc)),
			unexpected => Err(Error::UnexpectedToken(unexpected, None).at(loc))
		}
	}
}

impl Parsable for Index {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Index>> where L: Iterator<Item=Result<Located<Token>>> {
		let token = peek(lexer)?;
		let loc = token.span();

		use Token::*;
		let kind = match token.into_inner() {
			// Litteral(token::Litteral::Int(i)) => {
			//	 consume(lexer)?;
			//	 IndexKind::Numeral(i)
			// },
			Ident(_) => {
				let symbol = Symbol::parse(lexer)?;
				Index::Symbol(symbol.into_inner())
			}
			unexpected => return Err(Error::UnexpectedToken(unexpected, None).at(loc))
		};

		Ok(Located::new(kind, loc))
	}
}

impl Parsable for Ident {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Ident>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let token = peek(lexer)?;
		let mut loc = token.span();

		match token.into_inner() {
			Begin => {
				consume(lexer)?;
				consume_token(lexer, Ident("_".to_string()))?;
				let id = Symbol::parse(lexer)?;
				let mut indexes = Vec::new();

				loop {
					let token = peek(lexer)?;
					match token.as_ref() {
						End => {
							consume(lexer)?;
							loc = loc.union(token.span());
							break;
						},
						_ => {
							let index = Index::parse(lexer)?;
							indexes.push(index);
						}
					}
				}

				Ok(Located::new(ast::Ident {
					id: id,
					indexes: indexes
				}, loc))
			},
			Ident(_) => {
				let id = Symbol::parse(lexer)?;
				Ok(Located::new(ast::Ident {
					id: id,
					indexes: Vec::new()
				}, loc))
			},
			unexpected => return Err(Error::UnexpectedToken(unexpected, None).at(loc))
		}
	}
}

impl Parsable for Keyword {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Keyword>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let token = consume(lexer)?;
		let loc = token.span();
		match token.into_inner() {
			Ident(name) => Ok(Located::new(Keyword {
				id: name.clone()
			}, loc)),
			unexpected => Err(Error::UnexpectedToken(unexpected, None).at(loc))
		}
	}
}

impl Parsable for Attribute {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Attribute>> where L: Iterator<Item=Result<Located<Token>>> {
		let key = Keyword::parse(lexer)?;
		let token = peek(lexer)?;
		use Token::*;

		let value = match token.as_ref() {
			Ident(name) => {
				match name.chars().next() {
					Some(':') => None,
					Some(_) => Some(AttributeValue::parse(lexer)?),
					_ => None
				}
			},
			Litteral(_) => Some(AttributeValue::parse(lexer)?),
			Begin => Some(AttributeValue::parse(lexer)?),
			_ => None
		};

		let loc = match value {
			Some(ref value) => key.span().union(value.span()),
			None => key.span()
		};

		Ok(Located::new(Attribute {
			key: key,
			value: value
		}, loc))
	}
}

impl Parsable for AttributeValue {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<AttributeValue>> where L: Iterator<Item=Result<Located<Token>>> {
		let token = peek(lexer)?;
		let mut loc = token.span();

		use Token::*;
		let kind = match token.as_ref() {
			Ident(_) => {
				let id = ast::Symbol::parse(lexer)?;
				AttributeValue::Sym(id)
			},

			// Litteral(_) => {
			//	 let c = Constant::parse(lexer)?;
			//	 AttributeValueKind::Const(c)
			// },

			Begin => {
				consume(lexer)?;
				let mut exprs = Vec::new();

				loop {
					let token = peek(lexer)?;
					match token.as_ref() {
						End => {
							consume(lexer)?;
							loc = loc.union(token.span());
							break;
						},
						_ => {
							let expr = SExpr::parse(lexer)?;
							exprs.push(expr);
						}
					}
				}

				AttributeValue::List(exprs)
			},

			unexpected => {
				consume(lexer)?;
				return Err(Error::UnexpectedToken(unexpected.clone(), None).at(loc))
			}
		};

		Ok(Located::new(kind, loc))
	}
}

impl Parsable for SExpr {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<SExpr>> where L: Iterator<Item=Result<Located<Token>>> {
		let token = peek(lexer)?;
		let mut loc = token.span();

		use Token::*;
		let kind = match token.as_ref() {
			Ident(name) => {
				match name.chars().next() {
					Some(':') => {
						let key = Keyword::parse(lexer)?;
						SExpr::Keyword(key)
					},
					_ => {
						let id = ast::Symbol::parse(lexer)?;
						SExpr::Sym(id)
					}
				}
			},

			// Litteral(_) => {
			//	 let c = Constant::parse(lexer)?;
			//	 SExprKind::Const(c)
			// },

			Begin => {
				consume(lexer)?;
				let mut exprs = Vec::new();

				loop {
					let token = peek(lexer)?;
					match token.as_ref() {
						End => {
							consume(lexer)?;
							loc = loc.union(token.span());
							break;
						},
						_ => {
							let expr = SExpr::parse(lexer)?;
							exprs.push(expr);
						}
					}
				}

				SExpr::List(exprs)
			},

			unexpected => {
				consume(lexer)?;
				return Err(Error::UnexpectedToken(unexpected.clone(), None).at(loc))
			}
		};

		Ok(Located::new(kind, loc))
	}
}

impl Parsable for Sort {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Sort>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let token = peek(lexer)?;
		let mut loc = token.span();

		match token.as_ref() {
			Ident(_) => {
				let id = ast::Ident::parse(lexer)?;

				Ok(Located::new(Sort {
					id: id,
					parameters: Vec::new()
				}, loc))
			},
			Begin => {
				consume(lexer)?;
				let id = ast::Ident::parse(lexer)?;
				let mut parameters = Vec::new();

				loop {
					let token = peek(lexer)?;
					match *token {
						End => {
							consume(lexer)?;
							loc = loc.union(token.span());
							break;
						},
						_ => {
							let param = Sort::parse(lexer)?;
							parameters.push(param);
						}
					}
				}

				Ok(Located::new(Sort {
					id: id,
					parameters: parameters
				}, loc))
			}
			unexpected => Err(Error::UnexpectedToken(unexpected.clone(), None).at(loc))
		}
	}
}

impl Parsable for Term {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Term>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let token = peek(lexer)?;
		let mut loc = token.span();

		let kind = match token.as_ref() {
			Begin => {
				consume(lexer)?;
				let token = peek(lexer)?;

				match token.as_ref() {
					Ident(name) => {
						match name.as_str() {
							"let" => {
								consume(lexer)?;
								consume_token(lexer, Begin)?; // begining of the bindings list
								let bindings = parse_list(lexer, &mut loc)?;
								let body = Term::parse(lexer)?;
								consume_token(lexer, End)?; // end of the term.

								Term::Let {
									bindings: bindings,
									body: Box::new(body)
								}
							},

							"forall" => {
								consume(lexer)?;
								consume_token(lexer, Begin)?; // begining of the vars list
								let vars = parse_list(lexer, &mut loc)?;
								let body = Term::parse(lexer)?;
								consume_token(lexer, End)?; // end of the term.

								Term::Forall {
									vars: vars,
									body: Box::new(body)
								}
							},

							"exists" => {
								consume(lexer)?;
								consume_token(lexer, Begin)?; // begining of the vars list
								let vars = parse_list(lexer, &mut loc)?;
								let body = Term::parse(lexer)?;
								consume_token(lexer, End)?; // end of the term.

								Term::Exists {
									vars: vars,
									body: Box::new(body)
								}
							},

							"as" => {
								consume(lexer)?;
								let term = Term::parse(lexer)?;
								let sort = Sort::parse(lexer)?;
								consume_token(lexer, End)?; // end of the term.

								Term::Coerce {
									term: Box::new(term),
									sort: sort
								}
							},

							_ => {
								let id = ast::Ident::parse(lexer)?;
								//println!("APPLY list");
								let args = parse_list(lexer, &mut loc)?;
								//println!("APPLY done");

								Term::Apply {
									id: id,
									args: Box::new(args)
								}
							}
						}
					},

					unexpected => return Err(Error::UnexpectedToken(unexpected.clone(), None).at(loc))
				}
			},

			// Litteral(_) => {
			//	 let c = Constant::parse(lexer)?;
			//	 TermKind::Const(c)
			// },

			_ => {
				let id = ast::Ident::parse(lexer)?;
				Term::Ident(id)
			}
		};

		Ok(Located::new(kind, loc))
	}
}

impl Parsable for Binding {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Binding>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let mut loc = consume_token(lexer, Begin)?;
		let id = Symbol::parse(lexer)?;
		let term = Term::parse(lexer)?;
		loc = loc.union(consume_token(lexer, End)?);

		Ok(Located::new(Binding {
			id: id,
			value: Box::new(term)
		}, loc))
	}
}

impl Parsable for SortedVar {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<SortedVar>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let mut loc = consume_token(lexer, Begin)?;
		let id = Symbol::parse(lexer)?;
		let sort = Sort::parse(lexer)?;
		loc = loc.union(consume_token(lexer, End)?);

		Ok(Located::new(SortedVar {
			id: id,
			sort: sort
		}, loc))
	}
}

impl Parsable for DataTypeDeclaration {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<DataTypeDeclaration>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let constructors;
		let parameters;
		let mut loc = consume_token(lexer, Begin)?;

		let next_token = peek(lexer)?;
		match *next_token {
			Ident(ref id) if id == "par" => {
				consume(lexer)?;
				consume_token(lexer, Begin)?;
				parameters = parse_list(lexer, &mut loc)?;
				consume_token(lexer, Begin)?;
				constructors = parse_list(lexer, &mut loc)?;
				loc = loc.union(consume_token(lexer, End)?);
			},
			_ => {
				parameters = Vec::new();
				constructors = parse_list(lexer, &mut loc)?;
			}
		}

		Ok(Located::new(DataTypeDeclaration {
			parameters: parameters,
			constructors: constructors
		}, loc))
	}
}

impl Parsable for ConstructorDeclaration {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<ConstructorDeclaration>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let mut loc = consume_token(lexer, Begin)?;
		let id = Symbol::parse(lexer)?;
		let selectors = parse_list(lexer, &mut loc)?;

		Ok(Located::new(ConstructorDeclaration {
			id: id,
			selectors: selectors
		}, loc))
	}
}

impl Parsable for SelectorDeclaration {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<SelectorDeclaration>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let mut loc = consume_token(lexer, Begin)?;
		let id = Symbol::parse(lexer)?;
		let sort = Sort::parse(lexer)?;
		loc = loc.union(consume_token(lexer, End)?);

		Ok(Located::new(SelectorDeclaration {
			id: id,
			sort: sort
		}, loc))
	}
}

fn parse_numeral<L>(lexer: &mut Peekable<L>) -> Result<Located<i64>> where L: Iterator<Item=Result<Located<Token>>> {
	use Token::*;
	let token = consume(lexer)?;
	let loc = token.span();

	match token.as_ref() {
		Ident(id) => {
			if let Ok(i) = i64::from_str_radix(id, 10) {
				Ok(Located::new(i, loc))
			} else {
				Err(Error::UnexpectedToken(Ident(id.clone()), None).at(loc))
			}
		},
		unexpected => {
			Err(Error::UnexpectedToken(unexpected.clone(), None).at(loc))
		}
	}
}

impl Parsable for SortDeclaration {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<SortDeclaration>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let mut loc = consume_token(lexer, Begin)?;
		let id = Symbol::parse(lexer)?;
		let arity = parse_numeral(lexer)?;
		loc = loc.union(consume_token(lexer, End)?);

		Ok(Located::new(SortDeclaration {
			id: id,
			arity: arity
		}, loc))
	}
}

impl Parsable for Command {
	fn parse<L>(lexer: &mut Peekable<L>) -> Result<Located<Command>> where L: Iterator<Item=Result<Located<Token>>> {
		use Token::*;
		let mut loc = consume_token(lexer, Begin)?;

		let token = consume(lexer)?;
		let name_loc = token.span();
		let kind = match token.as_ref() {
			Ident(ref name) => {
				match name.as_str() {
					"assert" => {
						let term = Term::parse(lexer)?;
						Command::Assert(term)
					},

					"check-sat" => {
						Command::CheckSat
					},

					"declare-const" => {
						let id = Symbol::parse(lexer)?;
						let sort = Sort::parse(lexer)?;
						Command::DeclareConst(id, sort)
					},

					"declare-datatype" => {
						let id = Symbol::parse(lexer)?;
						let decl = DataTypeDeclaration::parse(lexer)?;
						Command::DeclareDatatype(id, decl)
					},

					"declare-datatypes" => {
						consume_token(lexer, Begin)?;
						let sort_decls = parse_list(lexer, &mut loc)?;
						consume_token(lexer, Begin)?;
						let decls = parse_list(lexer, &mut loc)?;
						Command::DeclareDatatypes(sort_decls, decls)
					},

					"declare-fun" => {
						let id = Symbol::parse(lexer)?;
						consume_token(lexer, Begin)?;
						let args = parse_list(lexer, &mut loc)?;
						let return_sort = Sort::parse(lexer)?;
						Command::DeclareFun(id, args, return_sort)
					},

					"exit" => {
						Command::Exit
					},

					"get-model" => {
						Command::GetModel
					},

					"set-info" => {
						let attr = Attribute::parse(lexer)?;
						Command::SetInfo(attr)
					},

					"set-logic" => {
						let logic = Symbol::parse(lexer)?;
						Command::SetLogic(logic)
					},

					_ => {
						return Err(Error::UnknownCommand(name.clone()).at(name_loc))
					}
				}
			},

			unexpected => return Err(Error::UnexpectedToken(unexpected.clone(), None).at(name_loc))
		};

		loc = loc.union(consume_token(lexer, End)?);

		Ok(Located::new(kind, loc))
	}
}