From: Daniel Jasper Date: Tue, 31 Mar 2015 14:34:15 +0000 (+0000) Subject: clang-format: [JS] Support getters, setters and methods in object literals. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=9f3f3d9f475d7c0e90132066fd2152fb3a67deb9;p=clang clang-format: [JS] Support getters, setters and methods in object literals. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@233698 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/UnwrappedLineParser.cpp b/lib/Format/UnwrappedLineParser.cpp index a036fb29da..7e8efad26b 100644 --- a/lib/Format/UnwrappedLineParser.cpp +++ b/lib/Format/UnwrappedLineParser.cpp @@ -1036,6 +1036,17 @@ bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) { FormatTok->BlockKind = BK_BracedInit; parseBracedList(); break; + case tok::r_paren: + // JavaScript can just have free standing methods and getters/setters in + // object literals. Detect them by a "{" following ")". + if (Style.Language == FormatStyle::LK_JavaScript) { + nextToken(); + if (FormatTok->is(tok::l_brace)) + parseChildBlock(); + break; + } + nextToken(); + break; case tok::r_brace: nextToken(); return !HasError; diff --git a/unittests/Format/FormatTestJS.cpp b/unittests/Format/FormatTestJS.cpp index 4378ded5c3..00744728dd 100644 --- a/unittests/Format/FormatTestJS.cpp +++ b/unittests/Format/FormatTestJS.cpp @@ -144,6 +144,27 @@ TEST_F(FormatTestJS, ContainerLiterals) { verifyFormat("x = foo && {a: 123};"); } +TEST_F(FormatTestJS, MethodsInObjectLiterals) { + verifyFormat("var o = {\n" + " value: 'test',\n" + " get value() { // getter\n" + " return this.value;\n" + " }\n" + "};"); + verifyFormat("var o = {\n" + " value: 'test',\n" + " set value(val) { // setter\n" + " this.value = val;\n" + " }\n" + "};"); + verifyFormat("var o = {\n" + " value: 'test',\n" + " someMethod(val) { // method\n" + " doSomething(this.value + val);\n" + " }\n" + "};"); +} + TEST_F(FormatTestJS, SpacesInContainerLiterals) { verifyFormat("var arr = [1, 2, 3];"); verifyFormat("f({a: 1, b: 2, c: 3});");