From: Martin Probst Date: Thu, 27 Apr 2017 13:07:24 +0000 (+0000) Subject: clang-format: [JS] parse async function declarations. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=ef06b8a5db8e50c20553b0d1ac83da4c8a644e74;p=clang clang-format: [JS] parse async function declarations. Summary: Previously, clang-format would accidentally parse an async function declaration as a function expression, and thus not insert an unwrapped line for async functions, causing subsequent functions to run into the function: async function f() { x(); } function g() { ... With this change, async functions get parsed as top level function declarations and get their own unwrapped line context. Reviewers: djasper Subscribers: klimek, cfe-commits Differential Revision: https://reviews.llvm.org/D32590 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@301538 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/UnwrappedLineParser.cpp b/lib/Format/UnwrappedLineParser.cpp index 5be68ad5c6..2d788b52df 100644 --- a/lib/Format/UnwrappedLineParser.cpp +++ b/lib/Format/UnwrappedLineParser.cpp @@ -1040,13 +1040,15 @@ void UnwrappedLineParser::parseStructuralElement() { return; } - // Parse function literal unless 'function' is the first token in a line - // in which case this should be treated as a free-standing function. + // Function declarations (as opposed to function expressions) are parsed + // on their own unwrapped line by continuing this loop. Function + // expressions (functions that are not on their own line) must not create + // a new unwrapped line, so they are special cased below. + size_t TokenCount = Line->Tokens.size(); if (Style.Language == FormatStyle::LK_JavaScript && - (FormatTok->is(Keywords.kw_function) || - FormatTok->startsSequence(Keywords.kw_async, - Keywords.kw_function)) && - Line->Tokens.size() > 0) { + FormatTok->is(Keywords.kw_function) && + (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is( + Keywords.kw_async)))) { tryToParseJSFunction(); break; } diff --git a/unittests/Format/FormatTestJS.cpp b/unittests/Format/FormatTestJS.cpp index 7886c4fe27..eda9e0a31d 100644 --- a/unittests/Format/FormatTestJS.cpp +++ b/unittests/Format/FormatTestJS.cpp @@ -485,6 +485,20 @@ TEST_F(FormatTestJS, AsyncFunctions) { " let x = 1;\n" " return fetch(x);\n" "}"); + verifyFormat("async function f() {\n" + " return 1;\n" + "}\n" + "\n" + "function a() {\n" + " return 1;\n" + "}\n", + " async function f() {\n" + " return 1;\n" + "}\n" + "\n" + " function a() {\n" + " return 1;\n" + "} \n"); verifyFormat("async function* f() {\n" " yield fetch(x);\n" "}"); @@ -492,6 +506,9 @@ TEST_F(FormatTestJS, AsyncFunctions) { " return fetch(x);\n" "}"); verifyFormat("let x = async () => f();"); + verifyFormat("let x = async function() {\n" + " f();\n" + "};"); verifyFormat("let x = async();"); verifyFormat("class X {\n" " async asyncMethod() {\n"