From 63c12cad17fd41fe968cc0887f6ae6f48ef89bce Mon Sep 17 00:00:00 2001 From: Nigel Tao Date: Tue, 9 Jun 2020 22:08:39 +1000 Subject: [PATCH] Have dumbindent catch "namespace foo {". --- lib/dumbindent/dumbindent.go | 20 +++++++++++++++----- lib/dumbindent/dumbindent_test.go | 4 ++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/lib/dumbindent/dumbindent.go b/lib/dumbindent/dumbindent.go index 1f9ffa9d..37fdc595 100644 --- a/lib/dumbindent/dumbindent.go +++ b/lib/dumbindent/dumbindent.go @@ -118,7 +118,8 @@ import ( // 'Constants', but their type is []byte, not string. var ( backTick = []byte("`") - externC = []byte("extern \"C\"") + externC = []byte("extern \"C\" {") + namespace = []byte("namespace ") starSlash = []byte("*/") spaces = []byte(" ") @@ -204,12 +205,10 @@ outer: // Preprocessor lines (#ifdef, #pragma, etc) are never indented. // - // The '{' and '}' for an `extern "C"` are also special cased not to - // change indentation inside the block. This assumes that the closing - // brace is followed by a `// extern "C"` comment. + // Also catch `extern "C" {` and `namespace foo {`. if (line[0] == '#') || ((line[0] == 'e') && bytes.HasPrefix(line, externC)) || - ((line[0] == '}') && bytes.HasSuffix(line, externC)) { + ((line[0] == 'n') && bytes.HasPrefix(line, namespace)) { line = trimTrailingWhiteSpace(line) dst = append(dst, line...) dst = append(dst, '\n') @@ -224,6 +223,17 @@ outer: } nBraces -= closeBraces + // The heuristics aren't perfect, and sometimes do not catch braces or + // parentheses in #define macros. They also don't increment nBraces for + // `extern "C"` or namespace lines. We work around that here, clamping + // to zero. + if nBraces < 0 { + nBraces = 0 + } + if nParens < 0 { + nParens = 0 + } + // Output a certain number of spaces to rougly approximate the // "clang-format -style=Chromium" indentation style. indent := 0 diff --git a/lib/dumbindent/dumbindent_test.go b/lib/dumbindent/dumbindent_test.go index fadd6438..84b0730d 100644 --- a/lib/dumbindent/dumbindent_test.go +++ b/lib/dumbindent/dumbindent_test.go @@ -75,6 +75,10 @@ func TestFormatBytes(tt *testing.T) { // Leading blank lines. src: "\n\n\n x = y;", want: "x = y;\n", + }, { + // Namespaces. + src: "namespace A {\nint f() {\nreturn 0;\n}\n}\n", + want: "namespace A {\nint f() {\n return 0;\n}\n}\n", }} for i, tc := range testCases {