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
//! A simple example
//!
//! This example uses the types defined in this module, they will systematically be imported in the
//! code samples.
//!
//!
//! We first need to define the expression type, and make it implement the
//! [`Expr2Smt`](crate::print::Expr2Smt) trait that writes it as an SMT-LIB 2 expression in a
//! writer.
//!
//! ## Print functions
//!
//! Since the structure for S-expressions is provided by users, they also need to provide functions
//! to print it in SMT-LIB 2.
//!
//! To use all SMT-LIB 2 commands in a type-safe manner, the library requires printers over
//!
//! - sorts: [`Sort2Smt`](crate::print::Sort2Smt) trait, *e.g.* for
//! [`Solver::declare_fun`](crate::Solver::declare_fun),
//! - symbols: [`Sym2Smt`](crate::print::Sym2Smt) trait, *e.g.* for
//! [`Solver::declare_fun`](crate::Solver::declare_fun),
//! - expressions: [`Expr2Smt`](crate::print::Expr2Smt) trait, *e.g.* for
//! [`Solver::assert`](crate::Solver::assert).
//!
//! All user-provided printing functions take some *information*. That way, users can pass some
//! information to, say, `assert` that can modify printing. This is typically used when dealing with
//! transition systems to perform "print-time unrolling". See the
//! [`examples::print_time`](crate::examples::print_time) module if you're interested; the example
//! below will not use print-time information.
//!
//! ```rust
//! extern crate rsmt2;
//!
//! use rsmt2::print::Expr2Smt;
//! use rsmt2::SmtRes;
//! use rsmt2::examples::simple::{ Op, Cst };
//!
//! /// An example of expression.
//! pub enum Expr {
//! /// A constant.
//! C(Cst),
//! /// Variable.
//! V(String),
//! /// Operator application.
//! O( Op, Vec<Expr> ),
//! }
//! impl Expr {
//! pub fn cst<C: Into<Cst>>(c: C) -> Self {
//! Expr::C( c.into() )
//! }
//! }
//! impl Expr2Smt<()> for Expr {
//! fn expr_to_smt2<Writer>(
//! & self, w: & mut Writer, _: ()
//! ) -> SmtRes<()>
//! where Writer: ::std::io::Write {
//! let mut stack = vec![ (false, vec![self], false) ];
//! while let Some((space, mut to_write, closing_paren)) = stack.pop() {
//! if let Some(next) = to_write.pop() {
//! if space {
//! write!(w, " ") ?
//! }
//! // We have something to print, push the rest back.
//! stack.push((space, to_write, closing_paren));
//! match * next {
//! Expr::C(cst) => write!(w, "{}", cst) ?,
//! Expr::V(ref var) => write!(w, "{}", var) ?,
//! Expr::O(op, ref sub_terms) => {
//! write!(w, "({}", op) ?;
//! stack.push((true, sub_terms.iter().rev().collect(), true))
//! },
//! }
//! } else {
//! // No more things to write at this level.
//! if closing_paren {
//! write!(w, ")") ?
//! }
//! }
//! }
//! Ok(())
//! }
//! }
//!
//! # fn main() {}
//! ```
//!
//! For convenience, all the `...2Smt` traits are implemented for `& str`. This is useful for
//! testing and maybe *very* simple application. Here, we won't implement
//! [`Sym2Smt`](crate::print::Sym2Smt) or [`Sort2Smt`](crate::print::Sort2Smt) and rely on `& str`
//! for symbols and sorts. Using a solver then boils down to creating a [`Solver`](crate::Solver)
//! which wraps a z3 process and provides most of the SMT-LIB 2.5 commands.
//!
//! ```rust
//! extern crate rsmt2;
//!
//! use rsmt2::Solver;
//! use rsmt2::examples::simple::{ Op, Cst, Expr };
//! # fn main() {
//!
//! let mut solver = Solver::default_z3(()).expect(
//! "could not spawn solver kid"
//! );
//!
//! let v_1 = "v_1".to_string();
//! let v_2 = "v_2".to_string();
//!
//! solver.declare_const( & v_1, & "Bool" ).expect(
//! "while declaring v_1"
//! );
//! solver.declare_const( & v_2, & "Int" ).expect(
//! "while declaring v_2"
//! );
//!
//! let expr = Expr::O(
//! Op::Disj, vec![
//! Expr::O(
//! Op::Ge, vec![ Expr::cst(-7), Expr::V( v_2.clone() ) ]
//! ),
//! Expr::V( v_1.clone() )
//! ]
//! );
//!
//! solver.assert( & expr ).expect(
//! "while asserting an expression"
//! );
//!
//! if solver.check_sat().expect("during check sat") {
//! ()
//! } else {
//! panic!("expected sat, got unsat")
//! }
//!
//! solver.kill().unwrap()
//! # }
//! ```
//!
//! Note the `unit` parameter that we passed to the `solver` function: `solver(& mut kid, ())`. This
//! is actually the parser the solver should use when it needs to parse values, symbols, types... In
//! the example above, we only asked for the satisfiability of the assertions. If we had asked for a
//! model, the compiler would have complained by saying that our parser `()` does not implement the
//! right parsing traits.
//!
//! ## The parser
//!
//! This example will only use [`Solver::get_model`](crate::Solver::get_model), which only requires
//! [`IdentParser`](crate::parse::IdentParser) and [`ModelParser`](crate::parse::ModelParser). In
//! most cases, an empty parser `struct` with the right implementations should be enough.
//!
//! ```rust
//! # #[macro_use]
//! # extern crate error_chain;
//! extern crate rsmt2;
//!
//! use rsmt2::SmtRes;
//! use rsmt2::parse::{ IdentParser, ModelParser };
//! use rsmt2::examples::simple::Cst;
//!
//! /// Empty parser structure, we will not maintain any context.
//! #[derive(Clone, Copy)]
//! pub struct Parser;
//! impl<'a> IdentParser<String, String, & 'a str> for Parser {
//! fn parse_ident(self, input: & 'a str) -> SmtRes<String> {
//! Ok( input.to_string() )
//! }
//! fn parse_type(self, input: & 'a str) -> SmtRes<String> {
//! match input {
//! "Int" => Ok( "Int".into() ),
//! "Bool" => Ok( "Bool".into() ),
//! sort => bail!("unexpected sort `{}`", sort),
//! }
//! }
//! }
//! impl<'a> ModelParser<String, String, Cst, & 'a str> for Parser {
//! fn parse_value(
//! self, input: & 'a str,
//! _ident: & String, _signature: & [ (String, String) ], _type: & String,
//! ) -> SmtRes<Cst> {
//! match input.trim() {
//! "true" => Ok( Cst::B(true) ),
//! "false" => Ok( Cst::B(false) ),
//! int => {
//! use std::str::FromStr;
//! let s = int.trim();
//! if let Ok(res) = isize::from_str(s) {
//! return Ok( Cst::I(res) )
//! } else if s.len() >= 4 {
//! if & s[0 .. 1] == "("
//! && & s[s.len() - 1 ..] == ")" {
//! let s = & s[1 .. s.len() - 1].trim();
//! if & s[0 .. 1] == "-" {
//! let s = & s[1..].trim();
//! if let Ok(res) = isize::from_str(s) {
//! return Ok( Cst::I(- res) )
//! }
//! }
//! }
//! }
//! bail!("unexpected value `{}`", int)
//! },
//! }
//! }
//! }
//! # fn main() {}
//! ```
//!
//! As a side note, it would have been simpler to implement
//! [`ModelParser`](crate::parse::ModelParser) with a [`& mut SmtParser`](crate::parse::SmtParser),
//! as it provides the parsers we needed.
//!
//! ```rust
//!
//! use rsmt2::SmtRes;
//! use rsmt2::parse::{ SmtParser, IdentParser, ModelParser };
//! use rsmt2::examples::simple::Cst;
//!
//!
//! #[derive(Clone, Copy)]
//! struct Parser;
//! impl<'a, Br> ModelParser<
//! String, String, Cst, & 'a mut SmtParser<Br>
//! > for Parser
//! where Br: ::std::io::BufRead {
//! fn parse_value(
//! self, input: & 'a mut SmtParser<Br>,
//! _ident: & String, _signature: & [ (String, String) ], _type: & String
//! ) -> SmtRes<Cst> {
//! use std::str::FromStr;
//! if let Some(b) = input.try_bool() ? {
//! Ok( Cst::B(b) )
//! } else if let Some(int) = input.try_int(
//! |int, pos| match isize::from_str(int) {
//! Ok(int) => if pos { Ok(int) } else { Ok(- int) },
//! Err(e) => Err(e),
//! }
//! ) ? {
//! Ok( Cst::I(int) )
//! } else {
//! input.fail_with("unexpected value")
//! }
//! }
//! }
//! ```
//!
//! Anyway, once we pass `Parser` to the solver creation function, and all conditions are met to ask
//! the solver for a model.
//!
//! ```rust
//! # #[macro_use]
//! # extern crate error_chain;
//! extern crate rsmt2;
//!
//! use rsmt2::{ SmtRes, Solver };
//! use rsmt2::examples::simple::{
//! Cst, Op, Expr, Parser
//! };
//!
//! # fn main() {
//!
//! let mut solver = Solver::default_z3(Parser).expect(
//! "could not spawn solver kid"
//! );
//!
//! let v_1 = "v_1".to_string();
//! let v_2 = "v_2".to_string();
//!
//! solver.declare_const( & v_1, & "Bool" ).expect(
//! "while declaring v_1"
//! );
//! solver.declare_const( & v_2, & "Int" ).expect(
//! "while declaring v_2"
//! );
//!
//! let expr = Expr::O(
//! Op::Disj, vec![
//! Expr::O(
//! Op::Ge, vec![ Expr::cst(-7), Expr::V( v_2.clone() ) ]
//! ),
//! Expr::V( v_1.clone() )
//! ]
//! );
//!
//! solver.assert( & expr ).expect(
//! "while asserting an expression"
//! );
//!
//! if solver.check_sat().expect("during check sat") {
//!
//! let model = solver.get_model_const().expect(
//! "while getting model"
//! );
//!
//! let mut okay = false;
//! for (ident, typ, value) in model {
//! if ident == v_1 {
//! assert_eq!( typ, "Bool" );
//! match value {
//! Cst::B(true) => okay = true,
//! Cst::B(false) => (),
//! Cst::I(int) => panic!(
//! "value for v_1 is `{}`, expected boolean", int
//! ),
//! }
//! } else if ident == v_2 {
//! assert_eq!( typ, "Int" );
//! match value {
//! Cst::I(i) if -7 >= i => okay = true,
//! Cst::I(_) => (),
//! Cst::B(b) => panic!(
//! "value for v_2 is `{}`, expected isize", b
//! ),
//! }
//! }
//! }
//!
//! if ! okay {
//! panic!("got sat, but model is spurious")
//! }
//!
//! } else {
//! panic!("expected sat, got unsat")
//! }
//!
//! solver.kill().unwrap()
//! # }
//! ```
use crate::;
use crateget_solver;
/// Operators. Just implements `Display`, never manipulated directly by the solver.
/// A constant.
/// An example of expression.
/// Empty parser structure, we will not maintain any context.
;