Skip to content

Commit 5f86b73

Browse files
committed
Fix float pretty-printing.
1 parent 4b7ba73 commit 5f86b73

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/numbers.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ mod tests {
115115
Expression::Float(41.43))));
116116
assert_parse_eq(number(make_strspan("42.")), Ok((make_strspan(""),
117117
Expression::Float(42.))));
118+
assert_parse_eq(number(make_strspan("6.0")), Ok((make_strspan(""),
119+
Expression::Float(6.))));
118120

119121
assert_parse_eq(number(make_strspan(".42e10")), Ok((make_strspan(""),
120122
Expression::Float(0.42e10))));

src/visitors/printer.rs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,14 @@ fn format_comp(comp: &ComprehensionChunk) -> String {
472472
}
473473
}
474474

475+
fn format_float(n: f64) -> String {
476+
let mut s = n.to_string();
477+
if s.find('.').is_none() {
478+
s.push_str(".");
479+
}
480+
s
481+
}
482+
475483
fn format_expr(e: &Expression) -> String {
476484
match e {
477485
Expression::Ellipsis => "...".to_string(),
@@ -481,11 +489,20 @@ fn format_expr(e: &Expression) -> String {
481489
Expression::Name(ref n) => n.to_string(),
482490
Expression::Int(ref n) => n.to_string(),
483491
Expression::ImaginaryInt(ref n) => format!("{}j", n),
484-
Expression::Float(ref n) => n.to_string(),
485-
Expression::ImaginaryFloat(ref n) => format!("{}j", n),
492+
Expression::Float(ref n) => format_float(*n),
493+
Expression::ImaginaryFloat(ref n) => format!("{}j", format_float(*n)),
486494
Expression::String(ref v) => {
487495
space_join(v.iter().map(|PyString { prefix, content }|
488-
format!("{}{:?}", prefix, content) // FIXME: that's cheating
496+
format!("{}\"{}\"", prefix, content.chars().map(|c| match c {
497+
'\r' => "\\r".to_string(),
498+
'\n' => "\\n".to_string(),
499+
'\t' => "\\t".to_string(),
500+
'\\' => "\\\\".to_string(),
501+
'"' => "\\\"".to_string(),
502+
c if c.is_ascii() => c.to_string(),
503+
c if (c as u32) <= 0xffff => format!("\\u{:04}", c as u32),
504+
c => format!("\\U{:08}", c as u32),
505+
}).collect::<Vec<_>>()[..].concat())
489506
))
490507
},
491508
Expression::Bytes(ref b) => {

0 commit comments

Comments
 (0)