Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/en/design/template-resolver.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ A step that fails — a lookup that finds nothing, a cycle, a budget exhausted
Pseudo-instantiation reads the written template and says what a dependent name could mean. The unit's actual instantiations say what it does mean for each argument list. clice treats a template like an interface and its instantiations like implementations, as a virtual function and its overrides:

- **Semantic tokens** read instantiated code too: an instantiation reuses the template's locations, so its resolution lands on the token written in the template. Instantiations agreeing on a name's kind keep it, and the modifiers they share; disagreeing ones make it a `conflict`.
- **Hover and inlay hints** inside a function template the unit instantiates exactly once show that instantiation's arguments, and an `auto` variable in a class template instantiated once deduces as there; with several, the parameters stay as written.
- **Hover and inlay hints** inside a function or class template the unit instantiates exactly once show that instantiation's arguments; with several, the parameters stay as written.
- **Navigation** reads every instantiation: the index keeps what each instantiation resolves in the template's text, so definition, references, call hierarchy and implementation on a dependent name list each resolution, in open and closed files alike.
- **Completion** parses only up to the cursor, before the code that calls the template, so a member access or a qualified name the template leaves open compiles the buffer once more and offers the names every instantiation has.

Expand Down
2 changes: 1 addition & 1 deletion docs/meta/translations/design/template-resolver.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion docs/zh/design/template-resolver.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ clice 无需具体实参即可解析依赖名。它不必知道 `T` 是 `int`
伪实例化根据写下的模板代码推断依赖名可能表示什么,而翻译单元中的实际实例化则给出了它在每组实参下确实表示什么。clice 将模板视为接口,将它的各个实例化视为实现,正如虚函数与重写它的函数之间的关系:

- **语义 Token** 也会读取实例化后的代码:实例化复用了模板的源码位置,因此其解析结果会落到模板中写下的那个 Token 上。若各实例化对该名称的种类达成一致,则保留该种类及它们共有的修饰符;若不一致,则标为 `conflict`。
- **悬停与内联提示**在当前翻译单元只实例化过一次的函数模板内会显示那次实例化的实参;只实例化过一次的类模板中的 `auto` 变量也会按该次实例化推导类型;若有多次实例化,形参则保持源码中的写法。
- **悬停与内联提示**在当前翻译单元只实例化过一次的函数模板或类模板内会显示那次实例化的实参;若有多次实例化,形参则保持源码中的写法。
- **代码导航**会读取每一个实例化:索引记录了每个实例化在模板文本中解析出的结果,因此无论文件是否打开,在依赖名上执行跳转到定义、查找引用、调用层次结构和跳转到实现,都会列出各个实例化的解析结果。
- **代码补全**只解析到光标位置,尚未读到后面调用模板的代码;因此模板本身无法确定的成员访问或限定名会再编译一次整个缓冲区,提供所有实例化共有的名称。

Expand Down
2 changes: 1 addition & 1 deletion src/index/format.cppm
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ namespace clice::index {
/// symbol-hash semantics change (stored entries keyed by old hashes would
/// silently stop matching newly computed ones), or when the meaning of
/// stored data changes.
constexpr inline std::uint32_t index_format_version = 65;
constexpr inline std::uint32_t index_format_version = 66;

/// The bytes of `blob`, the writer form of a blob layout. A blob holds less
/// than 4 GiB; index blobs stay far below it, so one past it stops the
Expand Down
26 changes: 24 additions & 2 deletions src/index/indexing/builder.cppm
Original file line number Diff line number Diff line change
Expand Up @@ -250,10 +250,21 @@ private:
/// are indexed (CompilationUnit::indexes_bodies).
bool walks(const clang::Decl* pattern, clang::FileID home);

/// The function and variable instantiations to walk; the known ones a
/// file holds go to its skipped keys.
/// The instantiations to walk: of functions and variables, and of the
/// classes but local ones whose member declarations write a type by a
/// dependent name; the known ones a file holds go to its skipped keys.
std::vector<const clang::Decl*> walked_instantiations();

/// In an instantiation, what the type at `index` names where its
/// template writes a dependent name (dependent_type_names).
void add_instantiated_type(const Semantics& semantics, std::uint32_t index);

/// Adds to dependent_type_names the places `pattern` writes a type by a
/// dependent name (`typename T::type`): a function's or a variable's
/// whole text, the types a class's members declare
/// (decls::member_types). Whether there is any.
bool note_dependent_types(const clang::Decl* pattern);

/// The top-level declarations the focus file does not own that expand a
/// macro it defines: `#define TYPE isl_space` before `#include
/// "templ.c"`, or `static` before an `#include` writing the rest of the
Expand Down Expand Up @@ -369,6 +380,9 @@ private:
/// its calls.
const clang::FunctionDecl* instantiated_function = nullptr;

/// Whether the instantiation projecting is a class's.
bool instantiated_class = false;

/// Where the expression being projected begins (in_pattern).
clang::SourceLocation expression_begin;

Expand All @@ -378,6 +392,14 @@ private:
llvm::DenseMap<std::pair<clang::SourceLocation, unsigned>, const clang::NamedDecl*>>
pattern_locals;

/// The places the walked patterns write a type by a dependent name: an
/// instantiation's type says there what the template's own entries
/// leave open, and elsewhere only what they say.
llvm::DenseSet<clang::SourceLocation> dependent_type_names;

/// Per pattern, note_dependent_types's answer.
llvm::DenseMap<const clang::Decl*, bool> scanned_patterns;

std::vector<BodyName> body_names;
};

Expand Down
31 changes: 28 additions & 3 deletions src/index/indexing/indexing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -392,9 +392,20 @@ void Builder::project_node(const Semantics& semantics, std::uint32_t i) {
enclosing_memo.resize(std::min<std::size_t>(enclosing_memo.size(), i));
top_level_memo.resize(std::min<std::size_t>(top_level_memo.size(), i));
// What an instantiation resolves are the calls and member accesses
// its body's expressions and constructor initializers make and the
// types its placeholders deduce; it declares nothing its template does
// not, and the types it substitutes are no references.
// its expressions and constructor initializers make, the types its
// dependent names come to name and the types its placeholders deduce;
// it declares nothing its template does not. A class's resolves its
// members' types alone: the expressions they hold, template arguments
// above all, resolve anew in each of the class's instantiations, an
// Eigen expression type's thousands, which doubles the index for what
// the template's own entries mostly tell.
const auto* type = semantics.node(i).node.get<clang::TypeLoc>();
if(instantiated_class) {
if(type) {
add_instantiated_type(semantics, i);
}
return;
}
const auto* stmt = semantics.node(i).node.get<clang::Stmt>();
expression_begin = stmt ? stmt->getBeginLoc() : clang::SourceLocation();
see_from(semantics, i);
Expand All @@ -406,6 +417,9 @@ void Builder::project_node(const Semantics& semantics, std::uint32_t i) {
return;
}
if(instantiation_entries && !stmt && !semantics.node(i).node.get<clang::CXXCtorInitializer>()) {
if(type) {
add_instantiated_type(semantics, i);
}
project_placeholder(semantics, i);
if(const auto* value = semantics.node(i).node.get<clang::ValueDecl>()) {
add_deduced_type(value);
Expand Down Expand Up @@ -468,6 +482,17 @@ void Builder::project_node(const Semantics& semantics, std::uint32_t i) {
project_relations(semantics, i);
}

void Builder::add_instantiated_type(const Semantics& semantics, std::uint32_t index) {
// A name the instantiation leaves dependent stays a guess, which no
// record keeps; the type a construction names gives way to the
// constructor it calls, which the construction records.
for(auto& occurrence: resolve_occurrences(semantics, index, nullptr)) {
if(!occurrence.outranked && dependent_type_names.contains(occurrence.location)) {
add_name(occurrence);
}
}
}

void Builder::project_macros() {
for(auto& [fid, directive]: unit.directives()) {
for(auto& macro: directive.macros) {
Expand Down
65 changes: 61 additions & 4 deletions src/index/indexing/instantiations.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,34 @@ const clang::NamedDecl* Builder::in_pattern(const clang::NamedDecl* decl) {
return found->second;
}

namespace {

/// The places a template writes a type by a dependent name, which each
/// instantiation names a type of its own: `typename T::type`,
/// `T::template rebind<U>`, the type a dependent using-declaration brings.
struct DependentNameFinder : clang::RecursiveASTVisitor<DependentNameFinder> {
bool VisitDependentNameTypeLoc(clang::DependentNameTypeLoc loc) {
found.insert(loc.getNameLoc());
return true;
}

bool VisitTemplateSpecializationTypeLoc(clang::TemplateSpecializationTypeLoc loc) {
if(!loc.getTypePtr()->getTemplateName().getAsTemplateDecl()) {
found.insert(loc.getTemplateNameLoc());
}
Comment thread
16bit-ykiko marked this conversation as resolved.
Resolved
return true;
}

bool VisitUnresolvedUsingTypeLoc(clang::UnresolvedUsingTypeLoc loc) {
found.insert(loc.getNameLoc());
return true;
}

llvm::DenseSet<clang::SourceLocation> found;
};

} // namespace

/// The declaration whose place is the home of `decl` (Builder::home_of).
const static clang::Decl* pattern_of(const clang::Decl* decl) {
const clang::Decl* pattern = nullptr;
Expand Down Expand Up @@ -93,12 +121,17 @@ bool Builder::walks(const clang::Decl* pattern, clang::FileID home) {
std::vector<const clang::Decl*> Builder::walked_instantiations() {
std::vector<const clang::Decl*> walked;
for(const auto* decl: unit.instantiations()) {
if(llvm::isa<clang::CXXRecordDecl>(decl)) {
continue;
}
// An instantiation runs its template's body, where the template is.
auto home = home_of(decl);
if(!walks(pattern_of(decl), home)) {
const auto* pattern = pattern_of(decl);
if(!walks(pattern, home)) {
continue;
}
bool writes = note_dependent_types(pattern);
// A class's member declarations resolve something only where they
// write a type by a dependent name; a local class is its function's.
if(const auto* record = llvm::dyn_cast<clang::CXXRecordDecl>(decl);
record && (!writes || record->isLocalClass())) {
continue;
Comment thread
16bit-ykiko marked this conversation as resolved.
Resolved
}
auto key = unit.get<EntityTable>().entity(llvm::cast<clang::NamedDecl>(decl));
Expand All @@ -111,6 +144,28 @@ std::vector<const clang::Decl*> Builder::walked_instantiations() {
return walked;
}

bool Builder::note_dependent_types(const clang::Decl* pattern) {
if(auto it = scanned_patterns.find(pattern); it != scanned_patterns.end()) {
return it->second;
}
DependentNameFinder finder;
if(const auto* record = llvm::dyn_cast<clang::CXXRecordDecl>(pattern)) {
for(auto type: decls::member_types(*record)) {
finder.TraverseTypeLoc(type);
}
} else {
// An instantiation can take its signature from a declaration before
// the definition.
for(auto* redecl: pattern->redecls()) {
finder.TraverseDecl(redecl);
}
}
bool writes = !finder.found.empty();
dependent_type_names.insert(finder.found.begin(), finder.found.end());
scanned_patterns.try_emplace(pattern, writes);
return writes;
}

std::vector<const clang::Decl*> Builder::expanding_decls() {
auto expansions = unit.focus_file().macro_invocations();
if(expansions.empty()) {
Expand Down Expand Up @@ -225,11 +280,13 @@ void Builder::project_instantiations(llvm::ArrayRef<const clang::Decl*> walked)
[&](const clang::Decl* root) {
instantiation_entries = &entries;
instantiated_function = llvm::dyn_cast<clang::FunctionDecl>(root);
instantiated_class = llvm::isa<clang::CXXRecordDecl>(root);
},
.leave =
[&](const clang::Decl* root) {
instantiation_entries = nullptr;
instantiated_function = nullptr;
instantiated_class = false;
close_instantiation(llvm::cast<clang::NamedDecl>(root), entries);
entries.clear();
},
Expand Down
50 changes: 50 additions & 0 deletions src/semantic/decls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,56 @@ const clang::CXXRecordDecl* getDeclContextForTemplateInstationPattern(const clan

} // namespace

auto member_types(const clang::CXXRecordDecl& record) -> llvm::SmallVector<clang::TypeLoc> {
llvm::SmallVector<clang::TypeLoc> types;
auto add = [&](const clang::TypeSourceInfo* written) {
if(written) {
types.push_back(written->getTypeLoc());
}
};
for(const auto* member: record.decls()) {
const clang::Decl* declared = member;
if(const auto* befriended = llvm::dyn_cast<clang::FriendDecl>(member)) {
if(!befriended->getFriendDecl()) {
add(befriended->getFriendType());
continue;
}
declared = befriended->getFriendDecl();
}
if(llvm::isa<clang::ClassTemplateDecl, clang::CXXRecordDecl>(declared)) {
continue;
}
if(const auto* templated = llvm::dyn_cast<clang::TemplateDecl>(declared)) {
for(const auto* parameter: *templated->getTemplateParameters()) {
Comment thread
16bit-ykiko marked this conversation as resolved.
Resolved
if(const auto* type = llvm::dyn_cast<clang::TemplateTypeParmDecl>(parameter)) {
if(type->hasDefaultArgument()) {
add(type->getDefaultArgument().getTypeSourceInfo());
}
} else if(const auto* value =
llvm::dyn_cast<clang::NonTypeTemplateParmDecl>(parameter)) {
add(value->getTypeSourceInfo());
}
}
declared = templated->getTemplatedDecl();
}
if(const auto* function = llvm::dyn_cast<clang::FunctionDecl>(declared)) {
if(auto written = function->getFunctionTypeLoc()) {
types.push_back(written.getReturnLoc());
}
for(const auto* parameter: function->parameters()) {
add(parameter->getTypeSourceInfo());
}
} else if(const auto* typed = llvm::dyn_cast<clang::DeclaratorDecl>(declared)) {
Comment thread
16bit-ykiko marked this conversation as resolved.
Resolved
add(typed->getTypeSourceInfo());
} else if(const auto* alias = llvm::dyn_cast<clang::TypedefNameDecl>(declared)) {
add(alias->getTypeSourceInfo());
} else if(const auto* enumeration = llvm::dyn_cast<clang::EnumDecl>(declared)) {
add(enumeration->getIntegerTypeSourceInfo());
}
}
return types;
}

auto function_pattern(const clang::FunctionDecl& function) -> const clang::FunctionDecl* {
if(const auto* pattern = function.getTemplateInstantiationPattern()) {
return pattern;
Expand Down
8 changes: 8 additions & 0 deletions src/semantic/decls.cppm
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ auto only_instantiation(clang::NamedDecl* templated_decl) -> clang::NamedDecl*;
/// parameter in the template's only instantiation.
auto only_instantiation(clang::ParmVarDecl* param) -> clang::ParmVarDecl*;

/// The types a class's member declarations write, which an instantiation
/// of the class substitutes with it: an alias's or a typedef's, a field's, a
/// static member's, an enumeration's underlying type, a member function's
/// return and parameter types, a member template's parameters' — no default
/// argument, initializer or body, which an instantiation reaches only when a
/// use needs them, and nothing of a nested class, a class of its own.
auto member_types(const clang::CXXRecordDecl& record) -> llvm::SmallVector<clang::TypeLoc>;

/// The declaration `function` was instantiated from. A member template of a
/// class template's specialization keeps no link of its own: its template
/// does.
Expand Down
8 changes: 7 additions & 1 deletion src/semantic/semantics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,13 @@ class SemanticsBuilder : public clang::RecursiveASTVisitor<SemanticsBuilder> {
}
visiting_root = decl;
options.enter(decl);
TraverseDecl(const_cast<clang::Decl*>(decl));
if(const auto* record = llvm::dyn_cast<clang::CXXRecordDecl>(decl)) {
for(auto type: decls::member_types(*record)) {
TraverseTypeLoc(type);
}
} else {
TraverseDecl(const_cast<clang::Decl*>(decl));
}
options.leave(decl);
}
instantiation_depth -= 1;
Expand Down
14 changes: 8 additions & 6 deletions src/semantic/semantics.cppm
Original file line number Diff line number Diff line change
Expand Up @@ -288,12 +288,14 @@ struct SemanticsOptions {
/// With all_files, each AST node as the traversal reaches it.
llvm::function_ref<void(const Semantics& path, std::uint32_t index)> visit;

/// With all_files, also traverse these function and variable
/// definitions the unit instantiated (CompilationUnit::instantiations),
/// each a root of its own after the written declarations, its nodes
/// flagged in_instantiation and handed to `visit` between the root's
/// `enter` and `leave`. An implicit definition (a lambda's call
/// operator) has no node of its own: its children are its first nodes.
/// With all_files, also traverse these definitions the unit
/// instantiated (CompilationUnit::instantiations), each a root of its
/// own after the written declarations, its nodes flagged
/// in_instantiation and handed to `visit` between the root's `enter`
/// and `leave`. An implicit definition (a lambda's call operator) has no
/// node of its own: its children are its first nodes. Nor has a class:
/// the types its members declare are (decls::member_types). A local
/// class is no root: its function's walk holds it.
llvm::ArrayRef<const clang::Decl*> instantiations;

llvm::function_ref<void(const clang::Decl* root)> enter;
Expand Down
Loading
Loading