-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathheap_print.rs
2138 lines (1797 loc) · 69 KB
/
heap_print.rs
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::arena::*;
use crate::atom_table::*;
use crate::parser::ast::*;
use crate::parser::dashu::base::RemEuclid;
use crate::parser::dashu::integer::Sign;
use crate::parser::dashu::{ibig, Integer, Rational};
use crate::forms::*;
use crate::heap_iter::*;
use crate::machine::heap::*;
use crate::machine::machine_indices::*;
use crate::machine::machine_state::pstr_loc_and_offset;
use crate::machine::partial_string::*;
use crate::machine::stack::*;
use crate::machine::streams::*;
use crate::types::*;
use dashu::base::Signed;
use ordered_float::OrderedFloat;
use indexmap::IndexMap;
use std::cell::Cell;
use std::convert::TryFrom;
use std::iter::once;
use std::net::{IpAddr, TcpListener};
use std::rc::Rc;
use std::sync::Arc;
/* contains the location, name, precision and Specifier of the parent op. */
#[derive(Debug, Copy, Clone)]
pub(crate) enum DirectedOp {
Left(Atom, OpDesc),
Right(Atom, OpDesc),
}
impl DirectedOp {
#[inline]
fn as_atom(&self) -> Atom {
match self {
&DirectedOp::Left(name, _) | &DirectedOp::Right(name, _) => name,
}
}
#[inline]
fn is_prefix(&self) -> bool {
match self {
&DirectedOp::Left(_name, cell) | &DirectedOp::Right(_name, cell) => {
cell.get_spec().is_prefix()
}
}
}
#[inline]
fn is_negative_sign(&self) -> bool {
match self {
&DirectedOp::Left(name, cell) | &DirectedOp::Right(name, cell) => {
name == atom!("-") && cell.get_spec().is_prefix()
}
}
}
#[inline]
fn is_left(&self) -> bool {
matches!(self, DirectedOp::Left(..))
}
}
fn needs_bracketing(child_desc: OpDesc, op: &DirectedOp) -> bool {
match op {
DirectedOp::Left(name, cell) => {
let (priority, spec) = cell.get();
if &*name.as_str() == "-" {
let child_assoc = child_desc.get_spec();
if spec.is_prefix() && (child_assoc.is_postfix() || child_assoc.is_infix()) {
return true;
}
}
let is_strict_right = spec.is_strict_right();
child_desc.get_prec() > priority
|| (child_desc.get_prec() == priority && is_strict_right)
}
DirectedOp::Right(_, cell) => {
let (priority, spec) = cell.get();
let is_strict_left = spec.is_strict_left();
if child_desc.get_prec() > priority
|| (child_desc.get_prec() == priority && is_strict_left)
{
true
} else if (spec.is_postfix() || spec.is_infix()) && !child_desc.get_spec().is_postfix()
{
*cell != child_desc && child_desc.get_prec() == priority
} else {
false
}
}
}
}
impl<'a, ElideLists> StackfulPreOrderHeapIter<'a, ElideLists> {
/*
* descend into the subtree where the iterator is currently parked
* and check that the leftmost leaf is a number, with every node
* encountered on the way an infix or postfix operator, unblocked
* by brackets.
*/
fn leftmost_leaf_has_property<P>(&self, op_dir: &OpDir, property_check: P) -> bool
where
P: Fn(HeapCellValue) -> bool,
{
let mut h = match self.stack_last() {
Some(h) => h,
None => return false,
};
let mut parent_spec = DirectedOp::Left(atom!("-"), OpDesc::build_with(200, FY));
loop {
let cell = self.read_cell(h);
read_heap_cell!(cell,
(HeapCellValueTag::Str, s) => {
read_heap_cell!(self.heap[s],
(HeapCellValueTag::Atom, (name, _arity)) => {
if let Some(spec) = fetch_atom_op_spec(name, None, op_dir) {
if spec.get_spec().is_postfix() || spec.get_spec().is_infix() {
if needs_bracketing(spec, &parent_spec) {
return false;
} else {
h = IterStackLoc::iterable_loc(s + 1, HeapOrStackTag::Heap);
parent_spec = DirectedOp::Right(name, spec);
continue;
}
}
}
return false;
}
_ => {
return false;
}
)
}
_ => {
return property_check(cell);
}
)
}
}
fn immediate_leaf_has_property<P>(&self, property_check: P) -> bool
where
P: Fn(HeapCellValue) -> bool,
{
let cell = match self.stack_last() {
Some(h) => self.read_cell(h),
None => return false,
};
property_check(cell)
}
}
fn char_to_string(is_quoted: bool, c: char) -> String {
match c {
'\'' if is_quoted => "\\'".to_string(),
'\n' if is_quoted => "\\n".to_string(),
'\r' if is_quoted => "\\r".to_string(),
'\t' if is_quoted => "\\t".to_string(),
'\u{0b}' if is_quoted => "\\v".to_string(), // UTF-8 vertical tab
'\u{0c}' if is_quoted => "\\f".to_string(), // UTF-8 form feed
'\u{08}' if is_quoted => "\\b".to_string(), // UTF-8 backspace
'\u{07}' if is_quoted => "\\a".to_string(), // UTF-8 alert
'\\' if is_quoted => "\\\\".to_string(),
' ' | '\'' | '\n' | '\r' | '\t' | '\u{0b}' | '\u{0c}' | '\u{08}' | '\u{07}' | '"'
| '\\' => c.to_string(),
_ => {
if c.is_whitespace() || c.is_control() {
// print all other control and whitespace characters in hex.
format!("\\x{:x}\\", c as u32)
} else {
c.to_string()
}
}
}
}
#[derive(Clone, Copy, Debug)]
enum NumberFocus {
Unfocused(Number),
Denominator(TypedArenaPtr<Rational>),
Numerator(TypedArenaPtr<Rational>),
}
impl NumberFocus {
fn is_negative(&self) -> bool {
match self {
NumberFocus::Unfocused(n) => n.is_negative(),
NumberFocus::Denominator(r) | NumberFocus::Numerator(r) => **r < Rational::from(0),
}
}
}
#[derive(Debug, Clone, Copy)]
struct CommaSeparatedCharList {
pstr: PartialString,
offset: usize,
max_depth: usize,
end_cell: HeapCellValue,
end_h: Option<usize>,
}
#[derive(Debug, Clone)]
enum TokenOrRedirect {
Atom(Atom),
BarAsOp,
Char(char),
Op(Atom, OpDesc),
NumberedVar(String),
CompositeRedirect(usize, DirectedOp),
CurlyBracketRedirect(usize),
FunctorRedirect(usize),
#[allow(unused)]
IpAddr(IpAddr),
NumberFocus(usize, NumberFocus, Option<DirectedOp>),
Open,
Close,
Comma,
RawPtr(*const ArenaHeader),
Space,
LeftCurly,
RightCurly,
ChildOpenList,
ChildCloseList,
OpenList(Rc<Cell<(bool, usize)>>),
CloseList(Rc<Cell<(bool, usize)>>),
HeadTailSeparator,
StackPop,
CommaSeparatedCharList(CommaSeparatedCharList),
}
pub(crate) fn requires_space(atom: &str, op: &str) -> bool {
match atom.chars().last() {
Some(ac) => op
.chars()
.next()
.map(|oc| {
if ac == '0' {
oc == '\'' || oc == '(' || alpha_numeric_char!(oc)
} else if alpha_numeric_char!(ac) {
oc == '(' || alpha_numeric_char!(oc)
} else if graphic_token_char!(ac) {
graphic_token_char!(oc)
} else if variable_indicator_char!(ac) || capital_letter_char!(ac) {
alpha_numeric_char!(oc)
} else if sign_char!(ac) {
sign_char!(oc) || decimal_digit_char!(oc)
} else if single_quote_char!(ac) {
single_quote_char!(oc)
} else {
false
}
})
.unwrap_or(false),
_ => false,
}
}
fn non_quoted_graphic_token<Iter: Iterator<Item = char>>(mut iter: Iter, c: char) -> bool {
if c == '/' {
match iter.next() {
None => true,
Some('*') => false, // if we start with comment token, we must quote.
Some(c) => {
if graphic_token_char!(c) {
iter.all(|c| graphic_token_char!(c))
} else {
false
}
}
}
} else if c == '.' {
match iter.next() {
None => false,
Some(c) => {
if graphic_token_char!(c) {
iter.all(|c| graphic_token_char!(c))
} else {
false
}
}
}
} else {
iter.all(|c| graphic_token_char!(c))
}
}
pub(super) fn non_quoted_token<Iter: Iterator<Item = char>>(mut iter: Iter) -> bool {
if let Some(c) = iter.next() {
if small_letter_char!(c) {
iter.all(|c| alpha_numeric_char!(c))
} else if graphic_token_char!(c) {
non_quoted_graphic_token(iter, c)
} else if semicolon_char!(c) || cut_char!(c) {
iter.next().is_none()
} else if c == '[' {
iter.next() == Some(']') && iter.next().is_none()
} else if c == '{' {
iter.next() == Some('}') && iter.next().is_none()
} else if solo_char!(c) {
!(c == '(' || c == ')' || c == '}' || c == ']' || c == ',' || c == '%' || c == '|')
} else {
false
}
} else {
false
}
}
#[allow(clippy::len_without_is_empty)]
pub trait HCValueOutputter {
type Output;
fn new() -> Self;
fn push_char(&mut self, c: char);
fn append(&mut self, s: &str);
fn result(self) -> Self::Output;
fn ends_with(&self, s: &str) -> bool;
fn len(&self) -> usize;
fn truncate(&mut self, len: usize);
fn as_str(&self) -> &str;
}
#[derive(Debug)]
pub struct PrinterOutputter {
contents: String,
}
impl HCValueOutputter for PrinterOutputter {
type Output = String;
fn new() -> Self {
PrinterOutputter {
contents: String::new(),
}
}
fn append(&mut self, contents: &str) {
if requires_space(&self.contents, contents) {
self.push_char(' ');
}
self.contents += contents;
}
fn push_char(&mut self, c: char) {
self.contents.push(c);
}
fn result(self) -> Self::Output {
self.contents
}
fn ends_with(&self, s: &str) -> bool {
self.contents.ends_with(s)
}
fn len(&self) -> usize {
self.contents.len()
}
fn truncate(&mut self, len: usize) {
self.contents.truncate(len);
}
fn as_str(&self) -> &str {
&self.contents
}
}
#[inline(always)]
fn is_numbered_var(name: Atom, arity: usize) -> bool {
arity == 1 && name == atom!("$VAR")
}
#[inline]
fn negated_op_needs_bracketing(
iter: &StackfulPreOrderHeapIter<ListElider>,
op_dir: &OpDir,
op: &Option<DirectedOp>,
) -> bool {
if let Some(ref op) = op {
op.is_negative_sign()
&& iter.leftmost_leaf_has_property(op_dir, |addr| match Number::try_from(addr) {
Ok(Number::Fixnum(n)) => n.get_num() > 0,
Ok(Number::Float(OrderedFloat(f))) => f > 0f64,
Ok(Number::Integer(n)) => n.is_positive(),
Ok(Number::Rational(n)) => n.is_positive(),
_ => false,
})
} else {
false
}
}
macro_rules! push_char {
($self:ident, $c:expr) => {{
$self.outputter.push_char($c);
$self.last_item_idx = $self.outputter.len();
}};
}
macro_rules! append_str {
($self:ident, $s:expr) => {{
$self.last_item_idx = $self.outputter.len();
$self.outputter.append($s);
}};
}
macro_rules! print_char {
($self:ident, $is_quoted:expr, $c:expr) => {
if non_quoted_token(once($c)) {
let result = char_to_string(false, $c);
push_space_if_amb!($self, &result, {
append_str!($self, &result);
});
} else {
let mut result = String::new();
if $self.quoted {
result.push('\'');
result += &char_to_string($is_quoted, $c);
result.push('\'');
} else {
result += &char_to_string($is_quoted, $c);
}
push_space_if_amb!($self, &result, {
append_str!($self, result.as_str());
});
}
};
}
pub fn fmt_float(mut fl: f64) -> String {
if OrderedFloat(fl) == -0f64 {
fl = 0f64;
}
let mut buffer = ryu::Buffer::new();
let fl_str = buffer.format(fl);
/* When printing floats with zero fractional parts in scientific notation, ryu
* prints "{integer part}e{exponent}" without a ".0" preceding "e",
* which is not valid ISO Prolog syntax. Add ".0" manually in this
* case.
*/
if let Some(e_index) = fl_str.find('e') {
if !fl_str[0..e_index].contains('.') {
return fl_str[0..e_index].to_string() + ".0" + &fl_str[e_index..];
}
}
fl_str.to_string()
}
#[derive(Debug)]
pub struct HCPrinter<'a, Outputter> {
outputter: Outputter,
iter: StackfulPreOrderHeapIter<'a, ListElider>,
atom_tbl: Arc<AtomTable>,
op_dir: &'a OpDir,
state_stack: Vec<TokenOrRedirect>,
toplevel_spec: Option<DirectedOp>,
last_item_idx: usize,
parent_of_first_op: Option<(DirectedOp, usize)>,
pub var_names: IndexMap<HeapCellValue, VarPtr>,
pub numbervars_offset: Integer,
pub numbervars: bool,
pub quoted: bool,
pub ignore_ops: bool,
pub max_depth: usize,
pub double_quotes: bool,
}
macro_rules! push_space_if_amb {
($self:expr, $atom:expr, $action:block) => {
if $self.ambiguity_check($atom) {
$self.outputter.push_char(' ');
$action;
} else {
$action;
}
};
}
pub(crate) fn numbervar(offset: &Integer, addr: HeapCellValue) -> Option<String> {
fn numbervar(n: Integer) -> String {
static CHAR_CODES: [char; 26] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
let i: usize = (&n).rem_euclid(ibig!(26)).try_into().unwrap();
let j = n / ibig!(26);
if j.is_zero() {
CHAR_CODES[i].to_string()
} else {
format!("{}{}", CHAR_CODES[i], j)
}
}
match Number::try_from(addr) {
Ok(Number::Fixnum(n)) if n.get_num() >= 0 => {
Some(numbervar(offset + Integer::from(n.get_num())))
}
Ok(Number::Integer(n)) if !n.is_negative() => Some(numbervar(Integer::from(offset + &*n))),
_ => None,
}
}
impl<'a, Outputter: HCValueOutputter> HCPrinter<'a, Outputter> {
pub fn new(
heap: &'a mut Heap,
atom_tbl: Arc<AtomTable>,
stack: &'a mut Stack,
op_dir: &'a OpDir,
output: Outputter,
cell: HeapCellValue,
) -> Self {
HCPrinter {
outputter: output,
iter: stackful_preorder_iter(heap, stack, cell),
atom_tbl,
op_dir,
state_stack: vec![],
toplevel_spec: None,
last_item_idx: 0,
parent_of_first_op: None,
numbervars: false,
numbervars_offset: Integer::from(0),
quoted: false,
ignore_ops: false,
var_names: IndexMap::new(),
max_depth: 0,
double_quotes: false,
}
}
#[inline]
fn ambiguity_check(&self, atom: &str) -> bool {
let tail = &self.outputter.as_str()[self.last_item_idx..];
if atom == "," || !self.quoted || non_quoted_token(atom.chars()) {
requires_space(tail, atom)
} else {
requires_space(tail, "'")
}
}
fn set_parent_of_first_op(&mut self, parent_op: Option<DirectedOp>) {
if let Some(op) = parent_op {
if op.is_left() && op.is_prefix() {
self.parent_of_first_op = Some((op, self.last_item_idx));
}
}
}
fn enqueue_op(&mut self, mut max_depth: usize, name: Atom, spec: OpDesc) {
if spec.get_spec().is_postfix() {
if self.max_depth_exhausted(max_depth) {
self.iter.pop_stack();
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
} else if self.check_max_depth(&mut max_depth) {
self.iter.pop_stack();
self.state_stack.push(TokenOrRedirect::Op(name, spec));
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
} else {
let right_directed_op = DirectedOp::Right(name, spec);
self.state_stack.push(TokenOrRedirect::Op(name, spec));
self.state_stack.push(TokenOrRedirect::CompositeRedirect(
max_depth,
right_directed_op,
));
}
} else if spec.get_spec().is_prefix() {
if self.max_depth_exhausted(max_depth) {
self.iter.pop_stack();
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
return;
} else if self.check_max_depth(&mut max_depth) {
self.iter.pop_stack();
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
self.state_stack.push(TokenOrRedirect::Op(name, spec));
} else {
let op = DirectedOp::Left(name, spec);
self.state_stack
.push(TokenOrRedirect::CompositeRedirect(max_depth, op));
self.state_stack.push(TokenOrRedirect::Op(name, spec));
}
} else {
if let "|" = &*name.as_str() {
self.format_bar_separator_op(max_depth, name, spec);
return;
};
if self.max_depth_exhausted(max_depth) {
self.iter.pop_stack();
self.iter.pop_stack();
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
} else if self.check_max_depth(&mut max_depth) {
if matches!(spec.get_spec(), XFY) {
let left_directed_op = DirectedOp::Left(name, spec);
self.state_stack
.push(TokenOrRedirect::CompositeRedirect(0, left_directed_op));
self.state_stack.push(TokenOrRedirect::Op(name, spec));
self.state_stack.push(TokenOrRedirect::StackPop);
} else {
// is_yfx!
let right_directed_op = DirectedOp::Right(name, spec);
self.state_stack.push(TokenOrRedirect::StackPop);
self.state_stack.push(TokenOrRedirect::Op(name, spec));
self.state_stack
.push(TokenOrRedirect::CompositeRedirect(0, right_directed_op));
}
} else {
let left_directed_op = DirectedOp::Left(name, spec);
let right_directed_op = DirectedOp::Right(name, spec);
self.state_stack.push(TokenOrRedirect::CompositeRedirect(
max_depth,
left_directed_op,
));
self.state_stack.push(TokenOrRedirect::Op(name, spec));
self.state_stack.push(TokenOrRedirect::CompositeRedirect(
max_depth,
right_directed_op,
));
}
}
}
fn format_struct(&mut self, mut max_depth: usize, arity: usize, name: Atom) -> bool {
if self.check_max_depth(&mut max_depth) {
for _ in 0..arity {
self.iter.pop_stack();
}
if arity > 0 {
self.state_stack.push(TokenOrRedirect::Close);
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
self.state_stack.push(TokenOrRedirect::Open);
}
self.state_stack.push(TokenOrRedirect::Atom(name));
return false;
}
if arity > 0 {
self.state_stack.push(TokenOrRedirect::Close);
for _ in 0..arity {
self.state_stack
.push(TokenOrRedirect::FunctorRedirect(max_depth));
self.state_stack.push(TokenOrRedirect::Comma);
}
self.state_stack.pop();
self.state_stack.push(TokenOrRedirect::Open);
}
self.state_stack.push(TokenOrRedirect::Atom(name));
true
}
fn format_bar_separator_op(&mut self, mut max_depth: usize, name: Atom, spec: OpDesc) {
if self.check_max_depth(&mut max_depth) {
self.iter.pop_stack();
self.iter.pop_stack();
let ellipsis_atom = atom!("...");
self.state_stack.push(TokenOrRedirect::Atom(ellipsis_atom));
self.state_stack.push(TokenOrRedirect::BarAsOp);
self.state_stack.push(TokenOrRedirect::Atom(ellipsis_atom));
return;
}
let left_directed_op = DirectedOp::Left(name, spec);
let right_directed_op = DirectedOp::Right(name, spec);
self.state_stack.push(TokenOrRedirect::CompositeRedirect(
max_depth,
left_directed_op,
));
self.state_stack.push(TokenOrRedirect::BarAsOp);
self.state_stack.push(TokenOrRedirect::CompositeRedirect(
max_depth,
right_directed_op,
));
}
fn format_curly_braces(&mut self, mut max_depth: usize) -> bool {
if self.check_max_depth(&mut max_depth) {
self.iter.pop_stack();
let ellipsis_atom = atom!("...");
self.state_stack.push(TokenOrRedirect::RightCurly);
self.state_stack.push(TokenOrRedirect::Atom(ellipsis_atom));
self.state_stack.push(TokenOrRedirect::LeftCurly);
return false;
}
self.state_stack.push(TokenOrRedirect::RightCurly);
self.state_stack
.push(TokenOrRedirect::CurlyBracketRedirect(max_depth));
self.state_stack.push(TokenOrRedirect::LeftCurly);
true
}
fn format_numbered_vars(&mut self) -> bool {
let h = self.iter.stack_last().unwrap();
let cell = self.iter.read_cell(h);
let cell = heap_bound_store(self.iter.heap, heap_bound_deref(self.iter.heap, cell));
// 7.10.4
if let Some(var) = numbervar(&self.numbervars_offset, cell) {
self.iter.pop_stack();
self.state_stack.push(TokenOrRedirect::NumberedVar(var));
return true;
}
false
}
fn format_clause(
&mut self,
max_depth: usize,
arity: usize,
name: Atom,
op_desc: Option<OpDesc>,
) -> bool {
if self.numbervars && is_numbered_var(name, arity) && self.format_numbered_vars() {
return true;
}
let dot_atom = atom!(".");
if let Some(spec) = op_desc {
if dot_atom == name && spec.get_spec().is_infix() && !self.ignore_ops {
self.push_list(max_depth);
return true;
}
if !self.ignore_ops && spec.get_prec() > 0 {
self.enqueue_op(max_depth, name, spec);
return true;
}
}
match (name, arity) {
(atom!("{}"), 1) if !self.ignore_ops => self.format_curly_braces(max_depth),
_ => self.format_struct(max_depth, arity, name),
}
}
fn offset_as_string(&mut self, h: IterStackLoc) -> Option<String> {
let cell = self.iter.read_cell(h);
if let Some(var) = self.var_names.get(&cell) {
read_heap_cell!(cell,
(HeapCellValueTag::Var | HeapCellValueTag::AttrVar | HeapCellValueTag::StackVar) => {
return Some(var.borrow().to_string());
}
_ => {
self.iter.push_stack(h);
return None;
}
);
}
read_heap_cell!(cell,
(HeapCellValueTag::Lis | HeapCellValueTag::Str, h) => {
Some(format!("{}", h))
}
(HeapCellValueTag::Var | HeapCellValueTag::AttrVar, h) => {
Some(format!("_{}", h))
}
(HeapCellValueTag::StackVar, h) => {
Some(format!("_s_{}", h))
}
_ => {
None
}
)
}
fn check_for_seen(&mut self, max_depth: &mut usize) -> Option<HeapCellValue> {
if let Some(mut orig_cell) = self.iter.next() {
loop {
let is_cyclic = orig_cell.get_forwarding_bit();
let cell =
heap_bound_store(self.iter.heap, heap_bound_deref(self.iter.heap, orig_cell));
let cell = unmark_cell_bits!(cell);
match self.var_names.get(&cell).cloned() {
Some(var) if cell.is_var() => {
// If cell is an unbound variable and maps to
// a name via heap_locs, append the name to
// the current output, and return None. None
// short-circuits handle_heap_term.
// self.iter.pop_stack();
let var_str = var.borrow().to_string();
push_space_if_amb!(self, &var_str, {
append_str!(self, &var_str);
});
return None;
}
var_opt => {
if is_cyclic && cell.is_compound(self.iter.heap) {
// self-referential variables are marked "cyclic".
read_heap_cell!(cell,
(HeapCellValueTag::Lis, vh) => {
if self.iter.heap[vh].get_forwarding_bit() {
self.iter.pop_stack();
}
if self.iter.heap[vh+1].get_forwarding_bit() {
self.iter.pop_stack();
}
}
_ => {}
);
match var_opt {
Some(var) => {
// If the term is bound to a named variable,
// print the variable's name to output.
let var_str = var.borrow().to_string();
push_space_if_amb!(self, &var_str, {
append_str!(self, &var_str);
});
}
None => {
if self.max_depth == 0 || *max_depth == 0 {
// otherwise, contract it to an ellipsis.
push_space_if_amb!(self, "...", {
append_str!(self, "...");
});
} else {
debug_assert!(cell.is_ref());
// as usual, the WAM's
// optimization of the Lis tag
// (conflating the location of
// the list and that of its
// first element) needs
// special consideration here
// lest we find ourselves in
// an infinite loop.
if cell.get_tag() == HeapCellValueTag::Lis {
*max_depth -= 1;
}
let h = cell.get_value() as usize;
self.iter.push_stack(IterStackLoc::iterable_loc(
h,
HeapOrStackTag::Heap,
));
if let Some(cell) = self.iter.next() {
orig_cell = cell;
continue;
}
}
}
}
return None;
}
return Some(cell);
}
}
}
} else {
while self.iter.pop_stack().is_none() {}
None
}
}
fn print_impromptu_atom(&mut self, atom: Atom) {
let result = self.print_op_addendum(&atom.as_str());
push_space_if_amb!(self, result.as_str(), {
append_str!(self, &result);
});
}
fn print_op_addendum(&mut self, atom: &str) -> String {
if !self.quoted || non_quoted_token(atom.chars()) {
atom.to_string()
} else if atom == "''" {
"''".to_string()
} else {
let mut result = String::new();
if self.quoted {
result.push('\'');
}
for c in atom.chars() {
result += &char_to_string(self.quoted, c);
}
if self.quoted {
result.push('\'');
}
result
}
}
fn print_op(&mut self, atom: &str) {
let result = if atom == "," {
",".to_string()
} else {
self.print_op_addendum(atom)
};
push_space_if_amb!(self, &result, {
append_str!(self, &result);
});
}
#[inline]
fn print_ip_addr(&mut self, ip: IpAddr) {
push_char!(self, '\'');
append_str!(self, &format!("{}", ip));
push_char!(self, '\'');
}
#[inline]
fn print_raw_ptr(&mut self, ptr: *const ArenaHeader) {
append_str!(self, &format!("0x{:x}", ptr as *const u8 as usize));
}
fn print_number(&mut self, max_depth: usize, n: NumberFocus, op: &Option<DirectedOp>) {
let (add_brackets, op_is_prefix) = if let Some(op) = op {
(op.is_negative_sign() && !n.is_negative(), op.is_prefix())
} else {
(false, false)
};
if add_brackets {
if op_is_prefix && !self.outputter.ends_with(" ") {
push_char!(self, ' ');
}
push_char!(self, '(');
}
match n {
NumberFocus::Unfocused(n) => match n {
Number::Float(OrderedFloat(fl)) => {
let output_str = fmt_float(fl);
push_space_if_amb!(self, &output_str, {
append_str!(self, &output_str);
});