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
//! # Formatting
//!
//! There are three main forms of formatting within Polar:
//!
//! 1. Debug strings: super verbose, mostly Rust-auto derived from fmt::Debug trait
//! 2. Display string: nice user-facing versions, which could be used for things like a debugger
//! 3. Polar strings: not always implemented, but is same syntax the parser accepts
//!
//! In addition, there are special cases like traces and sources that have their own
//! formatting requirements.

use crate::rules::*;
use crate::sources::*;
use crate::terms::*;
use crate::traces::*;
pub use display::*;
pub use to_polar::*;

impl Trace {
    /// Return the string representation of this `Trace`
    pub fn draw(&self, vm: &crate::vm::PolarVirtualMachine) -> String {
        let mut res = String::new();
        self.draw_trace(vm, 0, &mut res);
        res
    }

    fn draw_trace(&self, vm: &crate::vm::PolarVirtualMachine, nest: usize, res: &mut String) {
        if matches!(&self.node, Node::Term(term)
            if matches!(term.value(), Value::Expression(Operation { operator: Operator::And, ..})))
        {
            for c in &self.children {
                c.draw_trace(vm, nest + 1, res);
            }
        } else {
            let polar_str = match self.node {
                Node::Rule(ref r) => vm.rule_source(r),
                Node::Term(ref t) => vm.term_source(t, false),
            };
            let indented = polar_str
                .split('\n')
                .map(|s| "  ".repeat(nest) + s)
                .collect::<Vec<String>>()
                .join("\n");
            res.push_str(&indented);
            res.push_str(" [");
            if !self.children.is_empty() {
                res.push('\n');
                for c in &self.children {
                    c.draw_trace(vm, nest + 1, res);
                }
                for _ in 0..nest {
                    res.push_str("  ");
                }
            }
            res.push_str("]\n");
        }
    }
}

/// Traverse a [`Source`](../types/struct.Source.html) line by line until `offset` is reached,
/// and return the source line containing the `offset` character as well as `num_lines` lines
/// above and below it.
pub fn source_lines(source: &Source, offset: usize, num_lines: usize) -> String {
    // Sliding window of lines: current line + indicator + additional context above + below.
    let max_lines = num_lines * 2 + 2;
    let push_line = |lines: &mut Vec<String>, line: String| {
        if lines.len() == max_lines {
            lines.remove(0);
        }
        lines.push(line);
    };
    let mut index = 0;
    let mut lines = Vec::new();
    let mut target = None;
    let prefix_len = "123: ".len();
    for (lineno, line) in source.src.lines().enumerate() {
        push_line(&mut lines, format!("{:03}: {}", lineno + 1, line));
        let end = index + line.len() + 1; // Adding one to account for new line byte.
        if target.is_none() && end >= offset {
            target = Some(lineno);
            let spaces = " ".repeat(offset - index + prefix_len);
            push_line(&mut lines, format!("{}^", spaces));
        }
        index = end;
        if target.is_some() && lineno == target.unwrap() + num_lines {
            break;
        }
    }
    lines.join("\n")
}

/// Formats a vector of terms as a string-separated list
/// When providing an operator, parentheses are applied suitably
/// (see: to_polar_parens)
pub fn format_args(op: Operator, args: &[Term], sep: &str) -> String {
    args.iter()
        .map(|t| to_polar_parens(op, t))
        .collect::<Vec<String>>()
        .join(sep)
}

/// Formats a vector of parameters
pub fn format_params(args: &[Parameter], sep: &str) -> String {
    args.iter()
        .map(|parameter| parameter.to_polar())
        .collect::<Vec<String>>()
        .join(sep)
}

/// Formats a vector of rules as a string-separated list.
#[allow(clippy::ptr_arg)]
pub fn format_rules(rules: &Rules, sep: &str) -> String {
    rules
        .iter()
        .map(|rule| rule.to_polar())
        .collect::<Vec<String>>()
        .join(sep)
}

/// Helper method: uses the operator precedence to determine if `t`
/// has a lower precedence than `op`.
fn has_lower_pred(op: Operator, t: &Term) -> bool {
    match t.value() {
        Value::Expression(Operation {
            operator: other, ..
        }) => op.precedence() > other.precedence(),
        _ => false,
    }
}

pub fn to_polar_parens(op: Operator, t: &Term) -> String {
    if has_lower_pred(op, t) {
        format!("({})", t.to_polar())
    } else {
        t.to_polar()
    }
}

pub mod display {
    use crate::formatting::{format_args, format_params};
    use std::fmt;
    use std::sync::Arc;

    use super::ToPolarString;
    use crate::numerics::Numeric;
    use crate::rules::Rule;
    use crate::terms::{Operation, Operator, Symbol, Term, Value};
    use crate::vm::*;

    impl fmt::Display for Binding {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(fmt, "{} = {}", self.0.to_polar(), self.1.to_polar())
        }
    }

    impl fmt::Display for Symbol {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(fmt, "{}", self.0)
        }
    }

    impl fmt::Display for Term {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(fmt, "{}", self.to_polar())
        }
    }

    impl fmt::Display for Choice {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                fmt,
                "[{}] ++ [{}]",
                self.goals
                    .iter()
                    .map(|g| g.to_string())
                    .collect::<Vec<String>>()
                    .join(", "),
                self.alternatives
                    .iter()
                    .map(|alt| format!(
                        "[{}]",
                        alt.iter()
                            .map(|g| g.to_string())
                            .collect::<Vec<String>>()
                            .join(",")
                    ))
                    .collect::<Vec<String>>()
                    .join(", ")
            )
        }
    }

    impl fmt::Display for Goal {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            fn fmt_rules(rules: &[Arc<Rule>]) -> String {
                rules
                    .iter()
                    .map(|rule| rule.to_polar())
                    .collect::<Vec<String>>()
                    .join(" ")
            }

            match self {
                Goal::Isa { left, right } => {
                    write!(fmt, "Isa({}, {})", left.to_polar(), right.to_polar())
                }
                Goal::IsMoreSpecific { left, right, args } => write!(
                    fmt,
                    "IsMoreSpecific({} {} ({}))",
                    left.to_polar(),
                    right.to_polar(),
                    args.iter()
                        .map(|a| a.to_polar())
                        .collect::<Vec<String>>()
                        .join(", ")
                ),
                Goal::IsSubspecializer {
                    left, right, arg, ..
                } => write!(
                    fmt,
                    "IsSubspecializer({}, {}, {})",
                    left.to_polar(),
                    right.to_polar(),
                    arg.to_polar()
                ),
                Goal::Lookup { dict, field, value } => write!(
                    fmt,
                    "Lookup({}.{} = {})",
                    dict.to_polar(),
                    field.to_polar(),
                    value.to_polar()
                ),
                Goal::LookupExternal {
                    instance, field, ..
                } => write!(
                    fmt,
                    "LookupExternal({}.{})",
                    instance.to_polar(),
                    field.to_polar(),
                ),
                Goal::PopQuery { term } => write!(fmt, "PopQuery({})", term.to_polar()),
                Goal::Query { term } => write!(fmt, "Query({})", term.to_polar()),
                Goal::FilterRules {
                    applicable_rules,
                    unfiltered_rules,
                    ..
                } => write!(
                    fmt,
                    "FilterRules([{}], [{}])",
                    fmt_rules(applicable_rules),
                    fmt_rules(unfiltered_rules),
                ),
                Goal::SortRules {
                    rules,
                    outer,
                    inner,
                    ..
                } => write!(
                    fmt,
                    "SortRules([{}], outer={}, inner={})",
                    fmt_rules(rules),
                    outer,
                    inner,
                ),
                Goal::TraceRule { trace: _ } => write!(
                    fmt,
                    "TraceRule(...)" // FIXME: draw trace?
                ),
                Goal::Unify { left, right } => {
                    write!(fmt, "Unify({}, {})", left.to_polar(), right.to_polar())
                }
                g => write!(fmt, "{:?}", g),
            }
        }
    }

    impl fmt::Display for Rule {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
            match &self.body.value() {
                Value::Expression(Operation {
                    operator: Operator::And,
                    args,
                }) => {
                    if args.is_empty() {
                        write!(
                            fmt,
                            "{}({});",
                            self.name.to_polar(),
                            format_params(&self.params, ", ")
                        )
                    } else {
                        write!(
                            fmt,
                            "{}({}) if {};",
                            self.name.to_polar(),
                            format_params(&self.params, ", "),
                            format_args(Operator::And, &args, ",\n  "),
                        )
                    }
                }
                _ => panic!("Not any sorta rule I parsed"),
            }
        }
    }

    impl fmt::Display for Numeric {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match self {
                Self::Integer(i) => write!(f, "{}", i),
                Self::Float(float) => write!(f, "{}", float),
            }
        }
    }
}

pub mod to_polar {
    use crate::formatting::{format_args, format_params, to_polar_parens};
    use crate::rules::*;
    use crate::terms::*;

    /// Effectively works as a reverse-parser. Allows types to be turned
    /// back into polar-parseable strings.
    pub trait ToPolarString {
        fn to_polar(&self) -> String;
    }

    impl ToPolarString for Dictionary {
        fn to_polar(&self) -> String {
            let fields = self
                .fields
                .iter()
                .map(|(k, v)| format!("{}: {}", k.to_polar(), v.to_polar()))
                .collect::<Vec<String>>()
                .join(", ");
            format!("{{{}}}", fields)
        }
    }

    impl ToPolarString for ExternalInstance {
        fn to_polar(&self) -> String {
            if let Some(ref repr) = self.repr {
                repr.clone()
            } else {
                format!("^{{id: {}}}", self.instance_id)
            }
        }
    }

    impl ToPolarString for InstanceLiteral {
        fn to_polar(&self) -> String {
            format!("{}{}", self.tag.to_polar(), self.fields.to_polar())
        }
    }

    impl ToPolarString for Operator {
        fn to_polar(&self) -> String {
            use Operator::*;
            match self {
                Not => "not",
                Mul => "*",
                Div => "/",
                Add => "+",
                Sub => "-",
                Eq => "==",
                Geq => ">=",
                Leq => "<=",
                Neq => "!=",
                Gt => ">",
                Lt => "<",
                Or => "or",
                And => "and",
                New => "new",
                Dot => ".",
                Unify => "=",
                Assign => ":=",
                In => "in",
                Cut => "cut",
                ForAll => "forall",
                Debug => "debug",
                Print => "print",
                Isa => "matches",
            }
            .to_string()
        }
    }

    impl ToPolarString for Operation {
        fn to_polar(&self) -> String {
            use Operator::*;
            // Adds parentheses when sub expressions have lower precedence (which is what you would have had to have during initial parse)
            // Lets us spit out strings that would reparse to the same ast.
            match self.operator {
                Debug => "debug()".to_owned(),
                Print => format!("print({})", format_args(self.operator, &self.args, ", ")),
                Cut => "cut".to_owned(),
                ForAll => format!(
                    "forall({}, {})",
                    self.args[0].to_polar(),
                    self.args[1].to_polar()
                ),
                New => {
                    if self.args.len() == 1 {
                        format!("new {}", to_polar_parens(self.operator, &self.args[0]))
                    } else {
                        format!(
                            "new ({}, {})",
                            to_polar_parens(self.operator, &self.args[0]),
                            self.args[1].to_polar()
                        )
                    }
                }
                // `Dot` sometimes formats as a predicate
                Dot => {
                    if self.args.len() == 2 {
                        let call_term = if let Value::String(s) = self.args[1].value() {
                            s.to_string()
                        } else {
                            self.args[1].to_polar()
                        };
                        format!("{}.{}", self.args[0].to_polar(), call_term)
                    } else {
                        format!(".({})", format_args(self.operator, &self.args, ", "))
                    }
                }
                // Unary operators
                Not => format!(
                    "{} {}",
                    self.operator.to_polar(),
                    to_polar_parens(self.operator, &self.args[0])
                ),
                // Binary operators
                Mul | Div | Add | Sub | Eq | Geq | Leq | Neq | Gt | Lt | Unify | Isa | In
                | Assign => format!(
                    "{} {} {}",
                    to_polar_parens(self.operator, &self.args[0]),
                    self.operator.to_polar(),
                    to_polar_parens(self.operator, &self.args[1])
                ),
                // n-ary operators
                And => format_args(
                    self.operator,
                    &self.args,
                    &format!(" {} ", self.operator.to_polar()),
                ),
                Or => format_args(
                    self.operator,
                    &self.args,
                    &format!(" {} ", self.operator.to_polar()),
                ),
            }
        }
    }

    impl ToPolarString for Parameter {
        fn to_polar(&self) -> String {
            match &self.specializer {
                None => self.parameter.to_polar(),
                Some(specializer) => {
                    format!("{}: {}", self.parameter.to_polar(), specializer.to_polar())
                }
            }
        }
    }

    impl ToPolarString for Call {
        fn to_polar(&self) -> String {
            let args = format_args(Operator::And, &self.args, ", ");
            let combined_args = match &self.kwargs {
                Some(dict) => {
                    let kwargs = dict
                        .iter()
                        .map(|(k, v)| format!("{}: {}", k.to_polar(), v.to_polar()))
                        .collect::<Vec<String>>()
                        .join(", ");
                    if args.is_empty() {
                        kwargs
                    } else {
                        vec![args, kwargs].join(", ")
                    }
                }
                None => args,
            };
            format!("{}({})", self.name.to_polar(), combined_args)
        }
    }

    impl ToPolarString for Rule {
        fn to_polar(&self) -> String {
            match &self.body.value() {
                Value::Expression(Operation {
                    operator: Operator::And,
                    args,
                }) => {
                    if args.is_empty() {
                        format!(
                            "{}({});",
                            self.name.to_polar(),
                            format_params(&self.params, ", ")
                        )
                    } else {
                        format!(
                            "{}({}) if {};",
                            self.name.to_polar(),
                            format_params(&self.params, ", "),
                            format_args(Operator::And, &args, " and "),
                        )
                    }
                }
                _ => panic!("Not any sorta rule I parsed"),
            }
        }
    }

    impl ToPolarString for Symbol {
        fn to_polar(&self) -> String {
            self.0.to_string()
        }
    }

    impl ToPolarString for Term {
        fn to_polar(&self) -> String {
            self.value().to_polar()
        }
    }

    impl ToPolarString for Pattern {
        fn to_polar(&self) -> String {
            match self {
                Pattern::Dictionary(d) => d.to_polar(),
                Pattern::Instance(i) => i.to_polar(),
            }
        }
    }

    impl ToPolarString for Value {
        fn to_polar(&self) -> String {
            match self {
                Value::Number(i) => format!("{}", i),
                Value::String(s) => format!("\"{}\"", s),
                Value::Boolean(b) => {
                    if *b {
                        "true".to_string()
                    } else {
                        "false".to_string()
                    }
                }
                Value::InstanceLiteral(i) => i.to_polar(),
                Value::Dictionary(i) => i.to_polar(),
                Value::Pattern(i) => i.to_polar(),
                Value::ExternalInstance(i) => i.to_polar(),
                Value::Call(c) => c.to_polar(),
                Value::List(l) => format!("[{}]", format_args(Operator::And, l, ", "),),
                Value::Variable(s) => s.to_polar(),
                Value::RestVariable(s) => format!("*{}", s.to_polar()),
                Value::Expression(e) => e.to_polar(),
            }
        }
    }
}