Skip to content

Commit c961a86

Browse files
AgentElementljedrz
andauthored
fix: printing Var(27) and beyond overflowed ASCII (#55)
* fix: printing Var(27) and beyond overflowed ASCII * fix: bad debug line, fold char conversion into loop Co-authored-by: ljedrz <[email protected]> * clippy: swap cast for byte char * refactor: shadow a variable * test: one more test for base26_encode --------- Co-authored-by: ljedrz <[email protected]>
1 parent 7a24943 commit c961a86

File tree

1 file changed

+32
-11
lines changed

1 file changed

+32
-11
lines changed

src/term.rs

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ pub use self::Notation::*;
44
pub use self::Term::*;
55
use self::TermError::*;
66
use std::borrow::Cow;
7-
use std::char::from_u32;
87
use std::error::Error;
98
use std::fmt;
109

@@ -504,6 +503,20 @@ impl fmt::Display for Term {
504503
}
505504
}
506505

506+
fn base26_encode(mut n: u32) -> String {
507+
let mut buf = Vec::<u8>::new();
508+
n += 1;
509+
while n > 0 {
510+
let m = (n % 26) as u8;
511+
let m = if m == 0 { 26 } else { m };
512+
let c = m + b'a' - 1;
513+
buf.push(c);
514+
n = (n - 1) / 26
515+
}
516+
buf.reverse();
517+
String::from_utf8(buf).expect("error while printing term")
518+
}
519+
507520
fn show_precedence_cla(
508521
term: &Term,
509522
context_precedence: usize,
@@ -513,23 +526,20 @@ fn show_precedence_cla(
513526
match term {
514527
Var(0) => "undefined".to_owned(),
515528
Var(i) => {
516-
if depth >= *i as u32 {
517-
from_u32(depth + 97 - *i as u32)
518-
.expect("error while printing term")
519-
.to_string()
529+
let i = *i as u32;
530+
let ix = if i <= depth {
531+
depth - i
520532
} else {
521-
// use a different name than bound variables
522-
from_u32(max_depth + 96 + *i as u32 - depth)
523-
.expect("error while printing term")
524-
.to_string()
525-
}
533+
max_depth + i - depth - 1
534+
};
535+
base26_encode(ix)
526536
}
527537
Abs(ref t) => {
528538
let ret = {
529539
format!(
530540
"{}{}.{}",
531541
LAMBDA,
532-
from_u32(depth + 97).expect("error while printing term"),
542+
base26_encode(depth),
533543
show_precedence_cla(t, 0, max_depth, depth + 1)
534544
)
535545
};
@@ -678,6 +688,17 @@ mod tests {
678688
&app(abs(Var(1)), app(abs(app(Var(10), Var(1))), Var(10))).to_string(),
679689
"(λa.a) ((λa.j a) k)"
680690
);
691+
692+
assert_eq!(
693+
abs!(27, app!(Var(28), Var(29), Var(30), Var(50), Var(702), Var(703))).to_string(),
694+
"λ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.λaa.ab ac ad ax zz aaa"
695+
);
696+
assert_eq!(
697+
abs!(3, app!(Var(2), Var(3), Var(4))).to_string(),
698+
"λa.λb.λc.b a d"
699+
);
700+
assert_eq!(Var(26).to_string(), "z");
701+
assert_eq!(Var(27).to_string(), "aa");
681702
}
682703

683704
#[test]

0 commit comments

Comments
 (0)