[clang-tools-extra] [clangd] Consider expression statements in ExtractVariable tweak (PR #112525)

Nathan Ridge via cfe-commits cfe-commits at lists.llvm.org
Tue Dec 10 00:18:35 PST 2024


================
@@ -599,10 +607,22 @@ Expected<Tweak::Effect> ExtractVariable::apply(const Selection &Inputs) {
   // FIXME: get variable name from user or suggest based on type
   std::string VarName = "placeholder";
   SourceRange Range = Target->getExtractionChars();
+
+  const SelectionTree::Node &OuterImplicit =
+      Target->getExprNode()->outerImplicit();
+  assert(OuterImplicit.Parent);
+  bool IsStmtExpr = llvm::isa_and_nonnull<CompoundStmt>(
+      OuterImplicit.Parent->ASTNode.get<Stmt>());
+
   // insert new variable declaration
-  if (auto Err = Result.add(Target->insertDeclaration(VarName, Range)))
+  if (auto Err =
+          Result.add(Target->insertDeclaration(VarName, Range, !IsStmtExpr)))
----------------
HighCommander4 wrote:

The reason for needing `AddSemicolon: false` here for expression statements is a bit subtle:

 * The source range of an expression statement does not include the semicolon, so the text we're **inserting** as the initializer will not include the semicolon
 * However, the text we're **removing** below does not include the semicolon either (i.e. it's left behind), so we don't want to add another one

Could you add a comment clarifying this a bit?

https://github.com/llvm/llvm-project/pull/112525


More information about the cfe-commits mailing list