Skip to content

Format while loops, including labels #140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,24 @@ impl Rewrite for ast::Expr {
ast::Expr_::ExprTup(ref items) => {
rewrite_tuple_lit(context, items, self.span, width, offset)
}
ast::Expr_::ExprLoop(ref block, _) => {
ast::Expr_::ExprWhile(ref subexpr, ref block, label) => {
let label_string = rewrite_label(label);
// 6 = "while "
// 2 = " {"
let expr_width = width - 6 - 2 - label_string.len();
let expr_offset = offset + 6 + label_string.len();

subexpr.rewrite(context, expr_width, expr_offset).and_then(|expr_string| {
// FIXME: this drops any comment between "loop" and the block.
block.rewrite(context, width, offset).map(|result| {
format!("{}while {} {}", rewrite_label(label), expr_string, result)
})
})
}
ast::Expr_::ExprLoop(ref block, label) => {
// FIXME: this drops any comment between "loop" and the block.
// TODO: format label
block.rewrite(context, width, offset).map(|result| {
format!("loop {}", result)
format!("{}loop {}", rewrite_label(label), result)
})
}
_ => context.codemap.span_to_snippet(self.span).ok()
Expand Down Expand Up @@ -88,6 +101,13 @@ impl Rewrite for ast::Block {
}
}

fn rewrite_label(label: Option<ast::Ident>) -> String {
match label {
Some(ident) => format!("{}: ", ident.as_str()),
None => "".to_owned()
}
}

fn rewrite_string_lit(context: &RewriteContext,
s: &str,
span: Span,
Expand Down
7 changes: 6 additions & 1 deletion tests/source/loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ fn main() {

let x = loop { do_forever(); };

loop {
'label : loop {
// Just comments
}

'a: while loooooooooooooooooooooooooooooooooong_variable_name + another_value > some_other_value{}

while aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {
}
}
9 changes: 8 additions & 1 deletion tests/target/loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ fn main() {
do_forever();
};

loop {
'label: loop {
// Just comments
}

'a: while loooooooooooooooooooooooooooooooooong_variable_name + another_value >
some_other_value {
}

while aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {
}
}