module clice; import :compile.compilation; import :feature.code_actions.action; import :feature.code_actions.body; import :support.text; namespace clice::feature::action { namespace { /// Whether a variable holding `expr` says more than `expr`: a name, an /// assignment, a braced list or what a variable or a statement takes /// whole stays as written. bool worth_extracting(const Body& body, const clang::Expr* expr) { if(expr->getType().isNull() || expr->getType()->isVoidType() || expr->hasPlaceholderType() || expr->isInstantiationDependent() || expr->containsErrors() || expr->isXValue()) { return false; } const auto* bare = expr->IgnoreParens(); if(llvm::isa(bare)) { return false; } if(auto* member = llvm::dyn_cast(bare); member && member->isImplicitAccess()) { return false; } if(auto* op = llvm::dyn_cast(bare); op && op->isAssignmentOp()) { return false; } if(auto* call = llvm::dyn_cast(bare); call && clang::CXXOperatorCallExpr::isAssignmentOp(call->getOperator())) { return false; } const auto* parent = body.parent(body.outer_implicit(expr)); return parent && !llvm::isa(parent); } /// How the variable stands in for the expression: the declaration, /// before ` = `, and whether a use moves from it. struct Declaration { std::string head; bool moves = false; }; /// Whether a variable in place of the prvalue `expr` must be moved from to /// be consumed as `expr` was: a prvalue bound to an rvalue reference, a /// class prvalue initializing an object, whose field is accessed or which /// calls a member function only an rvalue calls. A named variable is an /// lvalue, which would bind elsewhere or be copied. bool consumed_as_rvalue(const Body& body, const clang::Expr* expr) { bool record = expr->getType()->getAsCXXRecordDecl() != nullptr; for(const clang::Stmt* node = expr;;) { const auto* parent = body.parent(node); if(auto* temporary = llvm::dyn_cast_or_null(parent)) { if(temporary->isBoundToLvalueReference()) { return false; } auto* member = llvm::dyn_cast_or_null( body.parent(body.outer_implicit(temporary))); if(!member || llvm::isa(member->getMemberDecl())) { return true; } auto* method = llvm::dyn_cast(member->getMemberDecl()); return method && method->getRefQualifier() == clang::RQ_RValue; } if(!llvm::isa_and_present(parent)) { return record; } node = parent; } } /// The declaration of a variable `name` holding `expr` that each use of /// it can replace `expr` with: in C++, a reference to what an lvalue /// designates and a copy of a prvalue, moved from where the prvalue was /// consumed as an rvalue; in C, which has no references, a copy of what /// is only read. `caller` is the class whose code it is, null for none. std::optional declaration(CompilationUnit& unit, const Body& body, const clang::Expr* expr, const clang::DeclContext* from, const clang::CXXRecordDecl* caller, clang::SourceLocation at, llvm::StringRef name) { auto& context = unit.context(); const auto& options = unit.lang_options(); auto* cast = llvm::dyn_cast_or_null(body.parent(expr)); bool read = cast && (cast->getCastKind() == clang::CK_LValueToRValue || cast->getCastKind() == clang::CK_ArrayToPointerDecay || cast->getCastKind() == clang::CK_FunctionToPointerDecay); // A bit-field's value is promoted where it is read: so is the copy. auto promoted = expr->refersToBitField() ? context.isPromotableBitField(const_cast(expr)) : clang::QualType(); if(!options.CPlusPlus) { if(expr->isGLValue() && !read) { return std::nullopt; } auto type = !promoted.isNull() ? promoted : expr->isGLValue() ? cast->getType() : expr->getType(); auto head = type_name(context, type.getUnqualifiedType(), from, at, name); if(!head) { return std::nullopt; } return Declaration{.head = std::move(*head)}; } if(expr->isLValue()) { // A reference cannot bind a bit-field: only its value can be kept. if(expr->refersToBitField()) { if(!read) { return std::nullopt; } if(promoted.isNull()) { return Declaration{.head = std::format("auto {}", name)}; } auto head = type_name(context, promoted, from, at, name); if(!head) { return std::nullopt; } return Declaration{.head = std::move(*head)}; } if(body.dangles(expr, context.getLValueReferenceType(expr->getType()))) { return std::nullopt; } return Declaration{.head = std::format("auto& {}", name)}; } auto type = expr->getType(); if(type->isArrayType() || body.dangles(expr, type)) { return std::nullopt; } // LIMITATION: the variable lives to the end of its block, where the // temporary ended with its statement, and the temporaries it is // computed from end with its declaration: a destructor with effects of // its own (a lock's) runs later, or earlier. bool moves = consumed_as_rvalue(body, expr); if(auto* record = type->getAsCXXRecordDecl()) { // Before C++17 the copy into the variable needs a constructor, and // a move out of it always does. record = record->getDefinition(); bool constructs = record && (move_constructible(record, caller) || copy_constructible(record, caller)); if(!constructs && (moves || !options.CPlusPlus17)) { return std::nullopt; } } return Declaration{.head = std::format("auto {}", name), .moves = moves}; } /// Whether a declaration placed right before `statement` of `block` is /// reached by whatever runs the code after it. bool reached(const clang::CompoundStmt* block, const clang::Stmt* statement) { auto statements = block->body(); auto at = ranges::find(statements, statement); llvm::SmallVector after(at, statements.end()); return !entered_by_jump(after); } /// The declarations an expression names: its variables and functions, /// and the types it spells. struct NamedDecls : clang::RecursiveASTVisitor { bool VisitDeclRefExpr(clang::DeclRefExpr* name) { found.push_back(name->getDecl()); return true; } bool VisitTagTypeLoc(clang::TagTypeLoc loc) { found.push_back(loc.getDecl()); return true; } bool VisitTypedefTypeLoc(clang::TypedefTypeLoc loc) { found.push_back(loc.getDecl()); return true; } std::vector found; }; /// Whether what `expr` names is declared before `statement`, or within /// `expr` itself. bool declared_before(CompilationUnit& unit, const clang::Expr* expr, const clang::Stmt* statement) { auto inside = [&](clang::SourceLocation location, clang::SourceRange outer) { return !unit.before(location, outer.getBegin()) && !unit.before(outer.getEnd(), location); }; NamedDecls named; named.TraverseStmt(const_cast(expr)); return ranges::all_of(named.found, [&](const clang::NamedDecl* decl) { auto location = decl->getLocation(); return !inside(location, statement->getSourceRange()) || inside(location, expr->getSourceRange()); }); } /// Where the declaration goes: right before the statement, on its own /// line with the statement's indentation when the statement begins its /// line. Nullopt when the block or the statement is not written in the /// focus file, or a macro writing the statement writes the one before it /// too. std::optional placed_before(CompilationUnit& unit, const clang::CompoundStmt* block, const clang::Stmt* statement, llvm::StringRef declaration) { auto focus = unit.focus_file(); auto brace = editable_range(unit, block->getLBracLoc()); auto range = focus.produced_range(statement->getSourceRange()); if(!brace || !range || range->begin < brace->end) { return std::nullopt; } const clang::Stmt* previous = nullptr; for(const auto* child: block->body()) { if(child == statement) { break; } previous = child; } if(previous) { auto end = focus.produced_range(previous->getSourceRange()); if(!end || end->end > range->begin) { return std::nullopt; } } auto content = focus.content(); if(begins_line(content, range->begin)) { auto offset = line_begin(content, range->begin); return TextReplacement{ {offset, offset}, std::format("{}{}\n", line_indent(content, range->begin), declaration) }; } return TextReplacement{ {range->begin, range->begin}, std::format("{} ", declaration) }; } /// Each expression under `block` equal to `expr`, in source order, outside /// the lambdas there; nullopt when one lies where a variable cannot stand /// in for it: in an operand that is not evaluated or a constant one, or /// in text a macro writes. std::optional> occurrences(CompilationUnit& unit, const Body& body, const clang::CompoundStmt* block, const clang::Expr* expr) { auto& context = unit.context(); llvm::FoldingSetNodeID profile; expr->Profile(profile, context, true); std::vector found; auto search = [&](this auto& self, const clang::Stmt* stmt) -> void { if(llvm::isa(stmt)) { return; } if(auto* other = llvm::dyn_cast(stmt); other && other->getStmtClass() == expr->getStmtClass()) { llvm::FoldingSetNodeID id; other->Profile(id, context, true); if(id == profile) { found.push_back(other); return; } } for(const auto* child: stmt->children()) { if(child) { self(child); } } }; search(block); if(!ranges::all_of(found, [&](const clang::Expr* other) { return body.evaluated(other) && !body.constant_needed(other) && replaceable_range(unit, body, other); })) { return std::nullopt; } return found; } } // namespace void extract_variable(const Context& ctx, std::vector& out) { auto& unit = ctx.unit; const auto& options = unit.lang_options(); const auto* expr = ctx.node.get(); // A cursor tells no extent; Objective-C has the reading features alone. if(!expr || ctx.selection.length() == 0 || options.ObjC || (options.CPlusPlus && !options.CPlusPlus11)) { return; } const auto* context_decl = &ctx.node.decl_context(); const auto* function = outermost_function(context_decl); if(!function || !function->getBody()) { return; } Body body(function->getBody()); if(!worth_extracting(body, expr) || body.constant_needed(expr)) { return; } auto hoisting = body.hoisting(unit.context(), expr); if(!hoisting || !reached(hoisting->block, hoisting->statement) || !declared_before(unit, expr, hoisting->statement)) { return; } auto range = replaceable_range(unit, body, expr); if(!range || !ctx.selection.contains(*range)) { return; } auto focus = unit.focus_file(); auto content = focus.content(); auto scope = focus.written_range(function->getSourceRange()); if(!scope) { return; } auto name = fresh_name(unit, "extracted", *scope); auto at = hoisting->statement->getBeginLoc(); auto declared = declaration(unit, body, expr, context_decl, llvm::dyn_cast(function->getDeclContext()), at, name); if(!declared) { return; } auto text = content.substr(range->begin, range->length()); auto* op = llvm::dyn_cast(expr); auto* call = llvm::dyn_cast(expr); bool comma = (op && op->isCommaOp()) || (call && call->getOperator() == clang::OO_Comma); auto line = std::format("{} = {};", declared->head, comma ? std::format("({})", text) : text.str()); auto single = [&](llvm::ArrayRef replaced, const clang::Stmt* first) -> std::optional> { auto insertion = placed_before(unit, hoisting->block, first, line); if(!insertion) { return std::nullopt; } std::vector edits; if(declared->moves && !declares_std_move(unit, at)) { auto include = include_insertion(unit); edits.push_back({ .range = {include.offset, include.offset}, .text = include.text("") }); } edits.push_back(std::move(*insertion)); auto use = declared->moves ? std::format("std::move({})", name) : name; for(const auto* occurrence: replaced) { auto written = replaceable_range(unit, body, occurrence); edits.push_back({*written, separated(content, *written, use)}); } return edits; }; if(auto edits = single(llvm::ArrayRef(expr), hoisting->statement)) { out.push_back(CodeAction{ .title = std::format("Extract into variable '{}'", name), .kind = action_kind::extract_variable, .edits = std::move(*edits), }); } // Every occurrence takes the value the first computes when nothing it // reads changes in between; an lvalue's names then designate one object. if(effects(unit.context(), expr) != Effects::None || (!expr->isLValue() && expr->getType()->getAsCXXRecordDecl())) { return; } auto locals = local_reads(expr, options.CPlusPlus && expr->isLValue() && !expr->refersToBitField()); auto found = locals ? occurrences(unit, body, hoisting->block, expr) : std::nullopt; if(!found || found->size() < 2) { return; } auto first = body.hoisting(unit.context(), found->front()); if(!first || first->block != hoisting->block) { return; } if(!options.CPlusPlus && expr->isGLValue() && ranges::any_of(*found, [&](const clang::Expr* occurrence) { auto* cast = llvm::dyn_cast_or_null(body.parent(occurrence)); return !cast || cast->getCastKind() != clang::CK_LValueToRValue; })) { return; } auto statement_of = [&](const clang::Expr* occurrence) { const clang::Stmt* node = occurrence; while(body.parent(node) != hoisting->block) { node = body.parent(node); } return node; }; std::vector region; bool inside = false; auto last = statement_of(found->back()); for(const auto* child: hoisting->block->body()) { inside |= child == first->statement; if(inside) { region.push_back(child); } if(child == last) { break; } } if(!body.unchanged(*locals, region) || !reached(hoisting->block, first->statement) || !declared_before(unit, found->front(), first->statement)) { return; } if(auto edits = single(*found, first->statement)) { out.push_back(CodeAction{ .title = std::format("Extract {} occurrences into variable '{}'", found->size(), name), .kind = action_kind::extract_variable, .edits = std::move(*edits), }); } } } // namespace clice::feature::action