Tweak dumbindent.breakAfterBrace

This commit is contained in:
Nigel Tao committed 2020-06-09 22:45:40 +10:00
1 parent 63c12cad17
commit 8bd30e912c
2 files changed
+49 -18

No files matched your search

+41 -18
View File
@@ -265,16 +265,14 @@ outer:
switch c { switch c {
case '{': case '{':
nBraces++ nBraces++
if l := lastNonWhiteSpace(line[:i]); (l != '=') && (l != ':') { if breakAfterBrace(line[i+1:]) {
if breakAfterBrace(line[i+1:]) { dst = append(dst, line[:i+1]...)
dst = append(dst, line[:i+1]...) dst = append(dst, '\n')
dst = append(dst, '\n') restOfLine := line[i+1:]
restOfLine := line[i+1:] remaining = src[lineLength-len(restOfLine):]
remaining = src[lineLength-len(restOfLine):] openBrace = true
openBrace = true hanging = false
hanging = false continue outer
continue outer
}
} }
case '}': case '}':
nBraces-- nBraces--
@@ -410,19 +408,44 @@ func handleRaw(dst []byte, restOfSrc []byte, endQuote []byte) (retDst []byte, li
return dst, line, remaining return dst, line, remaining
} }
// breakAfterBrace returns whether the first non-space non-tab byte of s (if // breakAfterBrace returns whether s starts with a slash-slash comment or with
// any) does not look like a comment or another open-brace. // the rest of a "0}" or ".a=1, .b=2}" literal, including the matching "}".
//
// This implementation isn't perfect, but it's good enough in practice.
func breakAfterBrace(s []byte) bool { func breakAfterBrace(s []byte) bool {
for _, c := range s { s = trimLeadingWhiteSpace(s)
if (c != ' ') && (c != '\t') { if len(s) == 0 {
return (c != '/') && (c != '{') return false
} else if (len(s) > 1) && (s[0] == '/') && (s[1] == '/') {
return false
}
n := 1
for i, c := range s {
switch c {
case ';':
return true
case '{':
n++
case '}':
n--
if n == 0 {
return false
}
case '/':
if (i + 1) < len(s) {
switch s[i+1] {
case '/', '*':
return true
}
}
} }
} }
return false return true
} }
// breakAfterBrace returns whether the first non-space non-tab byte of s (if // breakAfterSemicolon returns whether the first non-space non-tab byte of s
// any) does not look like a comment. // (if any) does not look like a comment.
func breakAfterSemicolon(s []byte) bool { func breakAfterSemicolon(s []byte) bool {
for _, c := range s { for _, c := range s {
if (c != ' ') && (c != '\t') { if (c != ' ') && (c != '\t') {
+8
View File
@@ -79,6 +79,14 @@ func TestFormatBytes(tt *testing.T) {
// Namespaces. // Namespaces.
src: "namespace A {\nint f() {\nreturn 0;\n}\n}\n", src: "namespace A {\nint f() {\nreturn 0;\n}\n}\n",
want: "namespace A {\nint f() {\n return 0;\n}\n}\n", want: "namespace A {\nint f() {\n return 0;\n}\n}\n",
}, {
// No break between "{" and "//".
src: "if (b) { // Blah.\nreturn;\n",
want: "if (b) { // Blah.\n return;\n",
}, {
// Simple compound literal.
src: "T x = {0};",
want: "T x = {0};\n",
}} }}
for i, tc := range testCases { for i, tc := range testCases {