Skip to content

Commit d86cfb3

Browse files
committed
Format all patterns (well, except macros)
Fixes #18 Fixes #672
1 parent c906b65 commit d86cfb3

File tree

6 files changed

+159
-39
lines changed

6 files changed

+159
-39
lines changed

src/imports.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ impl Rewrite for ast::ViewPath {
5151
}
5252

5353
fn rewrite_single_use_list(path_str: String, vpi: &ast::PathListItem) -> String {
54-
let path_item_str = if let ast::PathListItem_::PathListIdent{ name, .. } = vpi.node {
54+
let path_item_str = if let ast::PathListItem_::PathListIdent { name, .. } = vpi.node {
5555
// A name.
5656
if path_str.is_empty() {
5757
name.to_string()
@@ -74,17 +74,17 @@ fn rewrite_single_use_list(path_str: String, vpi: &ast::PathListItem) -> String
7474

7575
fn rewrite_path_item(vpi: &&ast::PathListItem) -> Option<String> {
7676
let path_item_str = match vpi.node {
77-
ast::PathListItem_::PathListIdent{ name, .. } => name.to_string(),
78-
ast::PathListItem_::PathListMod{ .. } => "self".to_owned(),
77+
ast::PathListItem_::PathListIdent { name, .. } => name.to_string(),
78+
ast::PathListItem_::PathListMod { .. } => "self".to_owned(),
7979
};
8080

8181
Some(append_alias(path_item_str, vpi))
8282
}
8383

8484
fn append_alias(path_item_str: String, vpi: &ast::PathListItem) -> String {
8585
match vpi.node {
86-
ast::PathListItem_::PathListIdent{ rename: Some(rename), .. } |
87-
ast::PathListItem_::PathListMod{ rename: Some(rename), .. } => {
86+
ast::PathListItem_::PathListIdent { rename: Some(rename), .. } |
87+
ast::PathListItem_::PathListMod { rename: Some(rename), .. } => {
8888
format!("{} as {}", path_item_str, rename)
8989
}
9090
_ => path_item_str,

src/patterns.rs

Lines changed: 120 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,30 @@ use lists::{format_item_list, itemize_list};
1515
use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
1616
use types::rewrite_path;
1717

18-
use syntax::ast::{BindingMode, Pat, Pat_};
18+
use syntax::ast::{BindingMode, Pat, Pat_, FieldPat};
1919

20-
// FIXME(#18): implement pattern formatting.
2120
impl Rewrite for Pat {
2221
fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
2322
match self.node {
2423
Pat_::PatBox(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, width, offset),
25-
Pat_::PatIdent(binding_mode, ident, None) => {
24+
Pat_::PatIdent(binding_mode, ident, ref sub_pat) => {
2625
let (prefix, mutability) = match binding_mode {
2726
BindingMode::BindByRef(mutability) => ("ref ", mutability),
2827
BindingMode::BindByValue(mutability) => ("", mutability),
2928
};
3029
let mut_infix = format_mutability(mutability);
31-
let result = format!("{}{}{}", prefix, mut_infix, ident.node);
30+
let id_str = ident.node.to_string();
31+
32+
let sub_pat = match *sub_pat {
33+
Some(ref p) => {
34+
let width = try_opt!(width.checked_sub(prefix.len() + mut_infix.len() +
35+
id_str.len()));
36+
format!(" @ {}", try_opt!(p.rewrite(context, width, offset)))
37+
}
38+
None => "".to_owned(),
39+
};
40+
41+
let result = format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat);
3242
wrap_str(result, context.config.max_width, width, offset)
3343
}
3444
Pat_::PatWild => {
@@ -55,39 +65,105 @@ impl Rewrite for Pat {
5565
width,
5666
offset)
5767
}
58-
Pat_::PatEnum(ref path, Some(ref pat_vec)) => {
59-
let path_str = try_opt!(::types::rewrite_path(context,
60-
true,
61-
None,
62-
path,
63-
width,
64-
offset));
68+
Pat_::PatEnum(ref path, ref pat_vec) => {
69+
let path_str = try_opt!(rewrite_path(context, true, None, path, width, offset));
6570

66-
if pat_vec.is_empty() {
67-
Some(path_str)
68-
} else {
69-
// 1 = (
70-
let width = try_opt!(width.checked_sub(path_str.len() + 1));
71-
let offset = offset + path_str.len() + 1;
72-
let items = itemize_list(context.codemap,
73-
pat_vec.iter(),
74-
")",
75-
|item| item.span.lo,
76-
|item| item.span.hi,
77-
|item| item.rewrite(context, width, offset),
78-
span_after(self.span, "(", context.codemap),
79-
self.span.hi);
80-
Some(format!("{}({})",
81-
path_str,
82-
try_opt!(format_item_list(items, width, offset, context.config))))
71+
match *pat_vec {
72+
Some(ref pat_vec) => {
73+
if pat_vec.is_empty() {
74+
Some(path_str)
75+
} else {
76+
// 1 = (
77+
let width = try_opt!(width.checked_sub(path_str.len() + 1));
78+
let offset = offset + path_str.len() + 1;
79+
let items = itemize_list(context.codemap,
80+
pat_vec.iter(),
81+
")",
82+
|item| item.span.lo,
83+
|item| item.span.hi,
84+
|item| item.rewrite(context, width, offset),
85+
span_after(self.span, "(", context.codemap),
86+
self.span.hi);
87+
Some(format!("{}({})",
88+
path_str,
89+
try_opt!(format_item_list(items,
90+
width,
91+
offset,
92+
context.config))))
93+
}
94+
}
95+
None => Some(format!("{}(..)", path_str)),
8396
}
8497
}
8598
Pat_::PatLit(ref expr) => expr.rewrite(context, width, offset),
86-
// FIXME(#8): format remaining pattern variants.
87-
Pat_::PatIdent(_, _, Some(..)) |
88-
Pat_::PatEnum(_, None) |
89-
Pat_::PatStruct(..) |
90-
Pat_::PatVec(..) |
99+
Pat_::PatVec(ref prefix, ref slice_pat, ref suffix) => {
100+
// Rewrite all the sub-patterns.
101+
let prefix = prefix.iter().map(|p| p.rewrite(context, width, offset));
102+
let slice_pat = slice_pat.as_ref().map(|p| {
103+
Some(format!("{}..", try_opt!(p.rewrite(context, width, offset))))
104+
});
105+
let suffix = suffix.iter().map(|p| p.rewrite(context, width, offset));
106+
107+
// Munge them together.
108+
let pats = prefix.chain(slice_pat.into_iter()).chain(suffix);
109+
110+
// Check that all the rewrites succeeded, and if not return None.
111+
let (somes, nones) = pats.partition::<Vec<Option<String>>, _>(Option::is_some);
112+
if nones.len() > 0 {
113+
return None;
114+
}
115+
116+
// Unwrap all the sub-strings and join them with commas.
117+
let pats = somes.into_iter().map(|p| p.unwrap()).collect::<Vec<_>>().join(", ");
118+
Some(format!("[{}]", pats))
119+
}
120+
Pat_::PatStruct(ref path, ref fields, elipses) => {
121+
let path = try_opt!(rewrite_path(context, true, None, path, width, offset));
122+
123+
let (elipses_str, terminator) = if elipses {
124+
(", ..", "..")
125+
} else {
126+
("", "}")
127+
};
128+
129+
let budget = try_opt!(width.checked_sub(path.len() + 5 + elipses_str.len()));
130+
// FIXME Using visual indenting, should use block or visual to match
131+
// struct lit preference (however, in practice I think it is rare
132+
// for struct patterns to be multi-line).
133+
let offset = offset + path.len() + 3;
134+
135+
let items = itemize_list(context.codemap,
136+
fields.iter(),
137+
terminator,
138+
|f| f.span.lo,
139+
|f| f.span.hi,
140+
|f| f.node.rewrite(context, budget, offset),
141+
span_after(self.span, "{", context.codemap),
142+
self.span.hi);
143+
let mut field_string = try_opt!(format_item_list(items,
144+
budget,
145+
offset,
146+
context.config));
147+
if elipses {
148+
if field_string.contains('\n') {
149+
field_string.push_str(",\n");
150+
field_string.push_str(&offset.to_string(context.config));
151+
field_string.push_str("..");
152+
} else {
153+
if field_string.len() > 0 {
154+
field_string.push_str(", ");
155+
}
156+
field_string.push_str("..");
157+
}
158+
}
159+
160+
if field_string.len() == 0 {
161+
Some(format!("{} {{}}", path))
162+
} else {
163+
Some(format!("{} {{ {} }}", path, field_string))
164+
}
165+
}
166+
// FIXME(#819) format pattern macros.
91167
Pat_::PatMac(..) => {
92168
wrap_str(context.snippet(self.span),
93169
context.config.max_width,
@@ -97,3 +173,14 @@ impl Rewrite for Pat {
97173
}
98174
}
99175
}
176+
177+
impl Rewrite for FieldPat {
178+
fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
179+
let pat = self.pat.rewrite(context, width, offset);
180+
if self.is_shorthand {
181+
pat
182+
} else {
183+
Some(format!("{}: {}", self.ident.to_string(), try_opt!(pat)))
184+
}
185+
}
186+
}

tests/source/pattern.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,20 @@ fn main() {
1111
let Some ( ref xyz /* comment! */) = opt;
1212

1313
if let None = opt2 { panic!("oh noes"); }
14+
15+
let foo@bar (f) = 42;
16+
let a::foo ( ..) = 42;
17+
let [ ] = 42;
18+
let [a.., b,c ] = 42;
19+
let [ a,b,c.. ] = 42;
20+
let [a, b, c, d..,e,f, g] = 42;
21+
let foo { } = 42;
22+
let foo {..} = 42;
23+
let foo { x, y: ref foo, .. } = 42;
24+
let foo { x, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: ref foo, .. } = 42;
25+
let foo { x, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: ref foo, } = 42;
26+
let foo { x, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: ref foo, .. };
27+
let foo { x, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: ref foo, };
1428
}
1529

1630
impl<'a,'b> ResolveGeneratedContentFragmentMutator<'a,'b> {

tests/system.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,8 @@ fn handle_result(result: HashMap<String, String>,
287287

288288
if fmt_text != text {
289289
let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
290+
assert!(!diff.is_empty(),
291+
"Empty diff? Maybe due to a missing a newline at the end of a file?");
290292
failures.insert(file_name, diff);
291293
}
292294
}

tests/target/match.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ fn issue280() {
251251

252252
fn issue383() {
253253
match resolution.last_private {
254-
LastImport{..} => false,
254+
LastImport { .. } => false,
255255
_ => true,
256256
};
257257
}

tests/target/pattern.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,23 @@ fn main() {
1313
if let None = opt2 {
1414
panic!("oh noes");
1515
}
16+
17+
let foo @ bar(f) = 42;
18+
let a::foo(..) = 42;
19+
let [] = 42;
20+
let [a.., b, c] = 42;
21+
let [a, b, c..] = 42;
22+
let [a, b, c, d.., e, f, g] = 42;
23+
let foo {} = 42;
24+
let foo { .. } = 42;
25+
let foo { x, y: ref foo, .. } = 42;
26+
let foo { x, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: ref foo, .. } = 42;
27+
let foo { x, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: ref foo } = 42;
28+
let foo { x,
29+
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: ref foo,
30+
.. };
31+
let foo { x,
32+
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy: ref foo };
1633
}
1734

1835
impl<'a, 'b> ResolveGeneratedContentFragmentMutator<'a, 'b> {

0 commit comments

Comments
 (0)