module clice; import :compile.compilation; import :feature.code_actions.action; import :feature.code_actions.body; import :support.text; namespace clice::feature::action { namespace { /// Every name of `var` under `block`, those in a type (`decltype(x)`) and /// in a lambda included. struct Names : clang::RecursiveASTVisitor { explicit Names(const clang::VarDecl* var) : var(var) {} bool VisitDeclRefExpr(clang::DeclRefExpr* name) { if(name->getDecl() == var) { found.push_back(name); } return true; } const clang::VarDecl* var; std::vector found; }; /// The names declared under the statements visited, which may hide what /// a name of the initializer finds there. struct Declared : clang::RecursiveASTVisitor { bool VisitNamedDecl(clang::NamedDecl* decl) { if(auto* identifier = decl->getIdentifier()) { names.insert(identifier->getName()); } return true; } llvm::StringSet<> names; }; /// The written initializer `var` takes its value from: `= value` of the /// variable's own type, past the conversions and copies clang adds. const clang::Expr* written_value(clang::ASTContext& context, const clang::VarDecl* var) { if(var->getInitStyle() != clang::VarDecl::CInit) { return nullptr; } const auto* value = var->getInit()->IgnoreImplicit(); while(auto* construct = llvm::dyn_cast(value)) { if(llvm::isa(construct)) { break; } if(!construct->isElidable() || construct->getNumArgs() != 1) { return nullptr; } value = construct->getArg(0)->IgnoreImplicit(); } if(llvm::isa(value) || !context.hasSameUnqualifiedType(value->getType(), var->getType().getNonReferenceType())) { return nullptr; } return value; } /// Whether `value` reads as one operand wherever it is put: a primary or /// postfix expression. bool self_contained(const clang::Expr* value) { if(auto* call = llvm::dyn_cast(value)) { auto kind = call->getOperator(); return kind == clang::OO_Call || kind == clang::OO_Subscript || kind == clang::OO_Arrow; } return llvm::isa(value); } /// Whether a name at `use` takes any expression but a comma one as it /// is: a whole argument, initializer or returned value. bool takes_whole(const Body& body, const clang::Expr* use) { const clang::Stmt* node = use; while(auto* parent = body.parent(node)) { auto* construct = llvm::dyn_cast(parent); bool converts = construct && !llvm::isa(construct) && construct->getParenOrBraceRange().isInvalid(); if(!converts && !llvm::isa( parent)) { if(auto* call = llvm::dyn_cast(parent)) { return node != call->getCallee() && !llvm::isa(call); } return llvm::isa(parent); } node = parent; } return false; } /// Whether a prvalue of class type, in place of the lvalue `use`, reaches /// what the lvalue does: the object of a member function called alike on /// both, of a field whose value is read or used alike in turn, a copy the /// prvalue makes elided, or the argument of a function with no overload /// an rvalue could choose. A field of the prvalue is an xvalue, which a /// constructor moves from. bool same_function(const Body& body, const clang::DeclRefExpr* use) { const clang::Stmt* node = use; auto* parent = body.parent(node); bool field = false; while(true) { while(auto* cast = llvm::dyn_cast_or_null(parent)) { if(field && cast->getCastKind() == clang::CK_LValueToRValue) { return true; } if(cast->getCastKind() != clang::CK_NoOp) { return false; } node = cast; parent = body.parent(node); } auto* member = llvm::dyn_cast_or_null(parent); if(!member || !llvm::isa(member->getMemberDecl())) { break; } field = true; node = member; parent = body.parent(node); } if(auto* member = llvm::dyn_cast_or_null(parent)) { auto* method = llvm::dyn_cast(member->getMemberDecl()); return !method || method->getRefQualifier() == clang::RQ_None; } if(llvm::isa_and_present(parent)) { return !field; } auto* call = llvm::dyn_cast_or_null(parent); auto* callee = call ? call->getDirectCallee() : nullptr; if(!callee || llvm::isa(call) || callee->isTemplated() || call->getCallee() == node) { return false; } auto found = callee->getDeclContext()->getRedeclContext()->lookup(callee->getDeclName()); auto it = found.begin(); return it != found.end() && ++it == found.end(); } } // namespace void inline_variable(const Context& ctx, std::vector& out) { auto& unit = ctx.unit; auto& context = unit.context(); if(unit.lang_options().ObjC) { return; } const auto* var = ctx.node.get(); if(!var) { const auto* name = ctx.node.get(); var = name ? llvm::dyn_cast(name->getDecl()) : nullptr; } if(!var || !var->isLocalVarDecl() || var->getStorageDuration() != clang::SD_Automatic || llvm::isa(var) || var->isInvalidDecl() || var->getType().isVolatileQualified() || var->getType()->isRValueReferenceType() || !var->getInit() || var->getInit()->containsErrors() || var->getInit()->isInstantiationDependent()) { return; } const auto* value = written_value(context, var); const auto* function = outermost_function(var->getLexicalDeclContext()); if(!value || !function || !function->getBody()) { return; } bool recursive = false; Body::for_each_expr(value, [&](const clang::Expr* node) { auto* name = llvm::dyn_cast(node); recursive |= name && name->getDecl() == var; }); if(recursive) { return; } Body body(function->getBody()); auto* declaration = llvm::dyn_cast_or_null(body.parent(var->getInit())); auto* block = declaration ? llvm::dyn_cast_or_null(body.parent(declaration)) : nullptr; if(!block || !declaration->isSingleDecl()) { return; } bool reference = var->getType()->isReferenceType(); // A reference stands for what an lvalue of its very type designates, // not for a temporary holding its value (a bit-field's). const auto* bound = var->getInit(); if(auto* full = llvm::dyn_cast(bound)) { bound = full->getSubExpr(); } if(reference && (!value->isLValue() || llvm::isa(bound->IgnoreParens()) || value->getType().getQualifiers() != var->getType().getNonReferenceType().getQualifiers())) { return; } Names names(var); names.TraverseStmt(const_cast(block)); if(names.found.empty()) { return; } // Each name is read where the value can stand, but what a reference // designates is written through it as through the value. A copy read // through an lvalue of other qualifiers, or through a prvalue where an // overload for rvalues may be chosen, would call something else. bool same_qualifiers = value->getType().getQualifiers() == var->getType().getQualifiers(); for(const auto* use: names.found) { bool in_lambda = false; for(const auto* node = body.parent(use); node && node != block; node = body.parent(node)) { in_lambda |= llvm::isa_and_present(node); } if(in_lambda || !body.evaluated(use) || !replaceable_range(unit, body, use)) { return; } if(reference) { continue; } if(body.use(use) != Use::Read) { return; } auto* cast = llvm::dyn_cast_or_null(body.parent(use)); if(cast && cast->getCastKind() == clang::CK_LValueToRValue) { continue; } if(value->isLValue() ? !same_qualifiers : !value->getType()->getAsCXXRecordDecl() || !same_function(body, use)) { return; } } auto statement_of = [&](const clang::Stmt* node) { while(body.parent(node) != block) { node = body.parent(node); } return node; }; auto statements = block->body(); auto at = ranges::find(statements, declaration); auto last = statement_of(names.found.back()); std::vector region; for(auto it = at + 1; it != statements.end(); ++it) { region.push_back(*it); if(*it == last) { break; } } // A jump back runs a use again, after what it reads may have changed; // an object destroyed at the end of the block would be destroyed at // the end of its one use, which must end the block. auto* record = var->getType()->getAsCXXRecordDecl(); if(entered_by_jump(region) || (!reference && record && !record->hasTrivialDestructor() && (names.found.size() != 1 || at + 2 != statements.end()))) { return; } // A value computed by itself reads the same wherever it is computed, // as long as what it reads keeps its value; anything else is computed // once, at the one name in the next statement, where nothing computed // before it could change it or see what it changes. A temporary then // ends with that statement, not the block: so must the variable. auto own = effects(context, value); auto locals = own == Effects::None ? local_reads(value, reference) : std::nullopt; if(!locals || !body.unchanged(*locals, region)) { if(names.found.size() != 1 || at + 1 == statements.end()) { return; } auto hoisting = body.sinking(context, names.found.front(), value); if(!hoisting || hoisting->block != block || hoisting->statement != *(at + 1)) { return; } } auto focus = unit.focus_file(); auto content = focus.content(); auto removed = editable_range(unit, declaration->getSourceRange()); auto written = replaceable_range(unit, body, value); if(!removed || !written) { return; } // What the value names must find the same where it goes, a macro's // expansion included. Declared declared; for(const auto* statement: region) { declared.TraverseStmt(const_cast(statement)); } bool hidden = false; Body::for_each_expr(value, [&](const clang::Expr* node) { auto* name = llvm::dyn_cast(node); auto* identifier = name ? name->getDecl()->getIdentifier() : nullptr; hidden |= identifier && declared.names.contains(identifier->getName()); }); auto text = content.substr(written->begin, written->length()); for(const auto& token: focus.lexical().code_from(written->begin)) { if(token.range.begin >= written->end) { break; } hidden |= token.is_identifier() && declared.names.contains(token.text(content)); } auto furthest = replaceable_range(unit, body, names.found.back()); if(hidden || !same_macros(unit, *written, furthest->begin)) { return; } std::vector edits; auto line = line_begin(content, removed->begin); auto after = line_end(content, removed->end); if(begins_line(content, removed->begin) && content.slice(removed->end, after).trim().empty()) { edits.push_back({ {line, after}, "" }); } else { auto end = removed->end; while(end < content.size() && content[end] == ' ') { end += 1; } edits.push_back({ {removed->begin, end}, "" }); } auto comma = llvm::isa(value) && llvm::cast(value)->getOpcode() == clang::BO_Comma; for(const auto* use: names.found) { auto range = *replaceable_range(unit, body, use); bool bare = self_contained(value) || (!comma && takes_whole(body, use)); edits.push_back( {range, separated(content, range, bare ? text.str() : std::format("({})", text))}); } out.push_back(CodeAction{ .title = std::format("Inline variable '{}'", var->getName()), .kind = action_kind::inline_variable, .edits = std::move(edits), }); } } // namespace clice::feature::action