pub mod context;
pub mod includes;
pub mod matching;
pub mod table;
mod request;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use cpp_parser::{CppSyntaxNode, SourceRange};
pub use context::{CompletionContext, context_at, doc_comment_at};
pub use includes::{Header, HeaderIndex, HeaderKind, SharedHeaders};
pub use table::{
BUILTIN_TYPES, DIRECTIVES, DirectiveName, KEYWORDS, Keyword, KeywordUse, SNIPPETS, Snippet,
};
use crate::sema::symbol::{Known, ScopeKind, ScopeTree};
use crate::summary::{DeclFact, DeclKind};
use crate::{ProjectIndex, ProjectMember};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ItemKind {
Variable,
Function,
Method,
Field,
Class,
Enum,
EnumMember,
Namespace,
Macro,
TypeParameter,
Keyword,
Snippet,
Header,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompletionItem {
pub label: String,
pub kind: ItemKind,
pub insert: String,
pub snippet: bool,
pub detail: Option<String>,
pub identity: Option<(PathBuf, usize)>,
pub filter: Option<String>,
pub fact: Option<DeclFact>,
pub replace: SourceRange,
pub inclusion: Option<Inclusion>,
pub additional_edits: Vec<(SourceRange, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unincluded {
pub file: std::path::PathBuf,
pub inclusion: Inclusion,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Inclusion {
Include(String),
Import(String),
}
impl Inclusion {
pub fn line(&self) -> String {
match self {
Inclusion::Include(spelling) => format!("#include \"{spelling}\"\n"),
Inclusion::Import(module) => format!("import {module};\n"),
}
}
}
pub fn the_include_spelling(
header: &std::path::Path,
asking: &std::path::Path,
include_paths: &[crate::include::config::IncludePath],
) -> String {
let header_normal = header.to_string_lossy().replace('\\', "/");
for path in include_paths {
let directory = path.directory.to_string_lossy().replace('\\', "/");
let directory = directory.trim_end_matches('/');
if directory.is_empty() {
continue;
}
if let Some(relative) = header_normal.strip_prefix(&format!("{directory}/")) {
return relative.to_string();
}
}
if let (Some(from), Some(to)) = (asking.parent(), header.parent()) {
let from: Vec<String> = from
.components()
.map(|part| part.as_os_str().to_string_lossy().to_string())
.collect();
let to: Vec<String> = to
.components()
.map(|part| part.as_os_str().to_string_lossy().to_string())
.collect();
let shared = from
.iter()
.zip(&to)
.take_while(|(left, right)| left.eq_ignore_ascii_case(right))
.count();
if shared > 0 {
let mut relative: Vec<String> = vec!["..".to_string(); from.len() - shared];
relative.extend(to[shared..].iter().cloned());
if let Some(file) = header.file_name() {
relative.push(file.to_string_lossy().to_string());
}
let spelled = relative.join("/");
if !spelled.is_empty() {
return spelled;
}
}
}
header_normal
}
impl CompletionItem {
fn declared(fact: &DeclFact, file: &Path) -> CompletionItem {
let identity =
(!fact.name.is_empty()).then(|| (file.to_path_buf(), fact.name_range.start_offset));
CompletionItem {
label: fact.name.to_string(),
kind: kind_of(fact.kind),
insert: match (&fact.kind, &fact.parameter_list()) {
(crate::DeclKind::MacroLike, Some(_)) => format!("{}(", fact.name),
_ => fact.name.to_string(),
},
snippet: false,
detail: detail_of(fact),
identity,
filter: None,
fact: Some(fact.clone()),
replace: SourceRange::new(0, 0),
inclusion: None,
additional_edits: Vec::new(),
}
}
pub(crate) fn word(label: &str, kind: ItemKind, detail: &str) -> CompletionItem {
CompletionItem {
label: label.to_string(),
kind,
insert: label.to_string(),
snippet: false,
detail: Some(detail.to_string()),
identity: None,
filter: None,
fact: None,
replace: SourceRange::new(0, 0),
inclusion: None,
additional_edits: Vec::new(),
}
}
fn snippet(trigger: &str, detail: &str, body: &str) -> CompletionItem {
CompletionItem {
label: trigger.to_string(),
kind: ItemKind::Snippet,
insert: body.to_string(),
snippet: true,
detail: Some(detail.to_string()),
identity: None,
filter: None,
fact: None,
replace: SourceRange::new(0, 0),
inclusion: None,
additional_edits: Vec::new(),
}
}
fn unincluded(fact: &DeclFact, file: &Path, inclusion: Inclusion) -> CompletionItem {
let mut item = CompletionItem::declared(fact, file);
let line = inclusion.line();
item.detail = Some(format!(
"not included — accepting this adds `{}`",
line.trim_end()
));
item.inclusion = Some(inclusion);
item
}
fn header(header: &Header) -> CompletionItem {
CompletionItem {
label: header.name.clone(),
kind: ItemKind::Header,
insert: header.name.clone(),
snippet: false,
detail: None,
identity: None,
filter: Some(header.name.clone()),
fact: None,
replace: SourceRange::new(0, 0),
inclusion: None,
additional_edits: Vec::new(),
}
}
}
fn kind_of(kind: DeclKind) -> ItemKind {
match kind {
DeclKind::Type => ItemKind::Class,
DeclKind::Function => ItemKind::Function,
DeclKind::Variable => ItemKind::Variable,
DeclKind::Namespace => ItemKind::Namespace,
DeclKind::MacroLike => ItemKind::Macro,
DeclKind::Other => ItemKind::Variable,
}
}
pub fn detail_of(fact: &DeclFact) -> Option<String> {
match fact.kind {
DeclKind::Function => match (&fact.returns, &fact.parameter_list()) {
(Some(returns), Some(parameters)) => Some(format!("{returns} {parameters}")),
(Some(returns), None) => Some(format!("{returns} (…)")),
(None, Some(parameters)) => Some(parameters.to_string()),
(None, None) => None,
},
DeclKind::Variable => fact.type_of.clone().map(|ty| ty.to_string()),
DeclKind::Type if !fact.bases().is_empty() => {
Some(format!(": {}", fact.bases().join(", ")))
}
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompletionSet {
pub items: Vec<CompletionItem>,
pub scope: String,
pub prefix: String,
pub replace: SourceRange,
pub truncated: bool,
pub incomplete: bool,
}
impl CompletionSet {
pub fn nothing_matched(&self) -> bool {
!self.prefix.is_empty()
&& !self.items.iter().any(|item| {
let compared = item.filter.as_deref().unwrap_or(&item.label);
crate::completion::matching::quality(compared, &self.prefix)
!= crate::completion::matching::NONE
})
}
}
impl Default for CompletionSet {
fn default() -> CompletionSet {
CompletionSet {
items: Vec::new(),
scope: String::new(),
prefix: String::new(),
replace: SourceRange::new(0, 0),
truncated: false,
incomplete: false,
}
}
}
#[derive(Debug, Clone)]
struct Scored {
score: Score,
matched: crate::completion::matching::Quality,
item: CompletionItem,
}
pub fn completion_at(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
offset: usize,
headers: &HeaderIndex,
cuda: bool,
budget: usize,
unincluded: &[Unincluded],
) -> CompletionSet {
let asked = context_at(root, offset);
completion_with(
index, scopes, root, path, offset, headers, asked, cuda, budget, unincluded,
)
}
pub fn completion_with(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
offset: usize,
headers: &HeaderIndex,
context: CompletionContext,
cuda: bool,
budget: usize,
unincluded: &[Unincluded],
) -> CompletionSet {
match context {
CompletionContext::Nothing => CompletionSet {
replace: SourceRange::new(offset, 0),
..CompletionSet::default()
},
CompletionContext::Member(access) => {
members(index, scopes, root, path, &access, offset, budget).set
}
CompletionContext::Designator { of, written, range } => {
members_of_a_written_type(
index, scopes, root, path, offset, &of, written, range, budget,
)
.set
}
CompletionContext::Qualified(position) => names(
index, scopes, root, path, &position, offset, false, cuda, budget, unincluded, None,
),
CompletionContext::Name(position) => names(
index, scopes, root, path, &position, offset, true, cuda, budget, unincluded, None,
),
CompletionContext::DirectiveName { written, range } => directives(&written, range),
CompletionContext::ModuleName { .. } => CompletionSet::default(),
CompletionContext::DirectiveArgument { written, range } => {
let position = crate::sema::resolve::NamePosition {
scope: String::new(),
written,
range,
};
names(
index, scopes, root, path, &position, offset, false, cuda, budget, unincluded, None,
)
}
CompletionContext::Include {
written,
closed,
range,
..
} => headers_for(headers, &written, closed, range),
CompletionContext::MacroBody {
written,
range,
parameters,
qualifier,
} => {
if qualifier.is_empty() {
macro_body(index, path, &written, range, ¶meters)
} else {
let position = crate::sema::resolve::NamePosition {
scope: qualifier,
written,
range,
};
names(
index, scopes, root, path, &position, offset, false, cuda, budget, unincluded,
None,
)
}
}
CompletionContext::Condition { written, range } => condition(index, path, &written, range),
CompletionContext::DocComment {
written,
range,
wants,
} => doc_comments(index, path, &written, range, wants),
CompletionContext::DocLink { written, range } => doc_link_names(
index, scopes, root, path, &written, range, cuda, budget, unincluded,
),
CompletionContext::DocCode { written, range } => {
let position = crate::sema::resolve::NamePosition {
scope: String::new(),
written,
range,
};
names(
index, scopes, root, path, &position, 0, true, cuda, budget, unincluded, None,
)
}
}
}
fn doc_link_names(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
written: &str,
range: SourceRange,
cuda: bool,
budget: usize,
unincluded: &[Unincluded],
) -> CompletionSet {
let (scope, written) = match written.rsplit_once("::") {
Some((scope, rest)) => (scope.to_string(), rest.to_string()),
None => (String::new(), written.to_string()),
};
let position = crate::sema::resolve::NamePosition {
scope: scope.clone(),
written: written.clone(),
range,
};
let listing =
crate::index::project::names_for_a_doc_comment(index, path, &scope, &written, range);
names(
index,
scopes,
root,
path,
&position,
0,
false,
cuda,
budget,
unincluded,
Some(Known::Yes(listing)),
)
}
pub fn why_no_members(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
offset: crate::file::coordinates::ReadingOffset,
) -> String {
let offset = offset.get();
match context_at(root, offset) {
CompletionContext::Member(access) => {
members(index, scopes, root, path, &access, offset, ITEM_BUDGET).why
}
other => format!("the cursor is not a member access at all: {other:?}"),
}
}
pub(crate) fn the_class_after_the_operator(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
written: &crate::sema::types::Type,
arrow: bool,
) -> Option<(String, bool)> {
let (reached, followed_a_pointer) =
the_type_after_the_operator(index, scopes, root, path, written, arrow)?;
let bare = reached.class_name().map(str::to_string)?;
let class = if bare.contains("::") {
bare
} else {
crate::index::project::qualified_from_the_index(index, path, &bare).unwrap_or(bare)
};
Some((class, followed_a_pointer))
}
pub(crate) fn the_type_after_the_operator(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
written: &crate::sema::types::Type,
arrow: bool,
) -> Option<(crate::sema::types::Type, bool)> {
let mut followed_a_pointer = false;
let mut current = written.clone();
for _ in 0..4 {
if let Some(bare) = current.class_name().map(str::to_string) {
let class = if bare.contains("::") {
bare.clone()
} else {
crate::index::project::qualified_from_the_index(index, path, &bare)
.unwrap_or_else(|| bare.clone())
};
if arrow
&& let Some(pointee) =
the_element_type_pointed_at(index, scopes, root, path, &class, ¤t)
{
current = crate::sema::types::parse_type_spelling(&pointee);
followed_a_pointer = true;
continue;
}
let returns = if arrow {
crate::index::project::operator_returns_of(
index,
&mut |_: &Path| None,
scopes,
root,
path,
¤t,
"operator->",
)
} else {
None
};
let Some(returns) = returns else {
return Some((current, followed_a_pointer));
};
current = crate::sema::types::parse_type_spelling(&returns);
if !arrow {
followed_a_pointer = true;
}
continue;
}
{
let pointee = current.pointee()?;
followed_a_pointer = true;
current = (*pointee).clone();
}
}
let names_a_class = current.class_name().is_some();
names_a_class.then_some((current, followed_a_pointer))
}
fn the_element_type_pointed_at(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
class: &str,
written: &crate::sema::types::Type,
) -> Option<String> {
let Known::Yes(members) = crate::index::project::members_of(index, scopes, root, path, class)
else {
return None;
};
let pointer_like = members.members.iter().any(|member| {
matches!(
member.fact.name.as_str(),
"element_type" | "operator->" | "operator*"
)
});
if !pointer_like {
if crate::probes::members() {
let names: Vec<&str> = members
.members
.iter()
.map(|member| member.fact.name.as_str())
.filter(|name| name.starts_with("operator"))
.collect();
eprintln!(
"element_type: {class} is not pointer-like ({} member(s), operators {names:?})",
members.members.len()
);
}
return None;
}
let arguments: Vec<String> = written
.arguments()
.iter()
.map(|argument| argument.to_string())
.collect();
let walked =
crate::index::project::element_type_of(index, scopes, root, path, class, class, &arguments);
match walked {
Some(pointee) if leads_to_members(index, scopes, root, path, &pointee) => Some(pointee),
_ => arguments
.first()
.filter(|first| leads_to_members(index, scopes, root, path, first))
.cloned(),
}
}
fn leads_to_members(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
name: &str,
) -> bool {
matches!(
crate::index::project::members_of(index, scopes, root, path, name),
Known::Yes(list) if !list.members.is_empty()
)
}
fn members_of_a_written_type(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
offset: usize,
of: &str,
prefix: String,
replace: SourceRange,
budget: usize,
) -> MemberAnswer {
let written = crate::sema::types::parse_type_spelling(of);
members_of_a_type(
index,
scopes,
root,
path,
offset,
&written,
false,
prefix,
replace,
of.to_string(),
budget,
)
}
fn members(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
access: &crate::sema::resolve::MemberAccess,
offset: usize,
budget: usize,
) -> MemberAnswer {
let replace = access.member_range;
let prefix = written_before(access, offset);
let refused = |why: String| MemberAnswer {
set: CompletionSet {
scope: String::new(),
prefix: prefix.clone(),
replace,
truncated: false,
incomplete: true,
items: Vec::new(),
},
why,
};
let written = match crate::index::project::type_of_expression(
index,
&mut |_: &Path| None,
scopes,
root,
path,
&access.object,
0,
) {
Known::Yes((written, _)) => written,
Known::Unknown(reason) => return refused(reason.describe()),
Known::No => {
return refused(format!(
"nothing says what `{}` is, so its members are not known",
access.object.text().to_string().trim()
));
}
};
members_of_a_type(
index,
scopes,
root,
path,
offset,
&written,
access.arrow,
prefix,
replace,
access.object.text().to_string().trim().to_string(),
budget,
)
}
#[allow(clippy::too_many_arguments)]
fn members_of_a_type(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
offset: usize,
written: &crate::sema::types::Type,
arrow: bool,
prefix: String,
replace: SourceRange,
subject: String,
budget: usize,
) -> MemberAnswer {
let Some((class, followed_a_pointer)) =
the_class_after_the_operator(index, scopes, root, path, written, arrow)
else {
return MemberAnswer {
set: CompletionSet {
scope: String::new(),
prefix,
replace,
truncated: false,
incomplete: false,
items: Vec::new(),
},
why: format!(
"the type of `{}` is `{written}`, which names no class to list members of",
subject
),
};
};
let found = match crate::index::project::members_of(index, scopes, root, path, &class) {
Known::Yes(found) => found,
Known::Unknown(reason) => {
return MemberAnswer {
set: CompletionSet {
scope: class.to_string(),
prefix,
replace,
truncated: false,
incomplete: true,
items: Vec::new(),
},
why: reason.describe(),
};
}
Known::No => {
return MemberAnswer {
set: CompletionSet {
scope: class.to_string(),
prefix,
replace,
truncated: false,
incomplete: true,
items: Vec::new(),
},
why: format!("`{class}` is not a class this analysis can see"),
};
}
};
let mut scored: Vec<Scored> = Vec::new();
let members = {
let mut members = found;
let hidden = crate::index::project::offerable_members(
index,
scopes,
root,
path,
offset,
&mut members,
);
(members, hidden)
};
let (members, hidden_by_access) = members;
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
for member in &members.members {
if reserved_for_the_implementation(&member.fact.name, &prefix) {
continue;
}
if !seen.insert(member.fact.name.as_str()) {
continue;
}
let mut item = CompletionItem::declared(&member.fact, &member.file);
item.kind = member_kind(member, &class);
item.replace = replace;
if member.depth > 0 {
item.detail = Some(match &item.detail {
Some(type_of) => format!("{type_of} (inherited from {})", member.declared_in),
None => format!("inherited from {}", member.declared_in),
});
}
if member.ambiguous {
item.detail = Some(match &item.detail {
Some(detail) => format!("{detail} (ambiguous)"),
None => "ambiguous: more than one base declares it".to_string(),
});
}
let matched = crate::completion::matching::quality(&item.label, &prefix);
if matched == crate::completion::matching::NONE {
continue;
}
scored.push(Scored {
score: member_score(member, &class),
matched,
item,
});
}
let (items, truncated) = ordered(scored, budget);
let offered = items.len();
let (replace, items) = if followed_a_pointer && !arrow {
let operator = replace.start_offset.saturating_sub(1);
let items: Vec<crate::completion::CompletionItem> = items
.into_iter()
.map(|mut item| {
item.insert = format!("->{}", item.insert);
item
})
.collect();
(
cpp_parser::SourceRange::new(operator, replace.length + 1),
items,
)
} else {
(replace, items)
};
let why = if offered > 0 {
format!("the member query answered, with {offered} members")
} else if hidden_by_access > 0 {
format!(
"`{class}` declares {} member(s) and {hidden_by_access} of them are `private` or `protected` where the \
cursor is",
members.members.len() + hidden_by_access
)
} else {
format!("`{class}` is declared and has no members this analysis can see")
};
let incomplete = !members.unlisted.is_empty();
MemberAnswer {
set: CompletionSet {
scope: class.to_string(),
prefix,
replace,
truncated,
incomplete,
items,
},
why,
}
}
struct MemberAnswer {
set: CompletionSet,
why: String,
}
fn reserved_for_the_implementation(name: &str, typed: &str) -> bool {
name.starts_with('_') && !typed.starts_with('_')
}
fn the_views_adaptors_a_scope_names(
scope: &str,
) -> Option<&'static [(&'static str, bool, &'static str)]> {
let is_the_views_namespace =
scope == "std::views" || scope == "ranges::views" || scope.ends_with("::views");
if !is_the_views_namespace {
return None;
}
Some(THE_VIEWS_ADAPTORS)
}
const THE_VIEWS_ADAPTORS: &[(&str, bool, &str)] = &[
("all", false, "a view of the whole range"),
("as_const", false, "a view whose elements are const"),
(
"common",
false,
"a view with a common iterator and sentinel",
),
("counted", true, "a counted view over an iterator"),
("drop", true, "skip the first n elements"),
("drop_while", true, "skip while the predicate holds"),
("elements", true, "a view over one member of each element"),
(
"filter",
true,
"a view of the elements the predicate accepts",
),
("join", false, "flatten a range of ranges"),
("keys", false, "a view over the first member of each pair"),
(
"lazy_split",
true,
"a view of the subranges between separators",
),
("owning_view", true, "a view that owns its range"),
("ref_view", true, "a view that refers to a range"),
("reverse", false, "a view of the elements in reverse order"),
("split", true, "a view of the subranges between separators"),
("take", true, "the first n elements"),
("take_while", true, "the elements while the predicate holds"),
(
"transform",
true,
"a view with the function applied to each element",
),
(
"values",
false,
"a view over the second member of each pair",
),
("iota", true, "a sequence of increasing values"),
];
fn names(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
position: &crate::sema::resolve::NamePosition,
offset: usize,
with_table: bool,
cuda: bool,
budget: usize,
unincluded: &[Unincluded],
listed_by_the_caller: Option<Known<crate::index::project::NameCompletions>>,
) -> CompletionSet {
let mut scored: Vec<Scored> = Vec::new();
let mut listed_scope = position.scope.clone();
let mut listed_prefix = position.written.clone();
let mut replace = position.range;
let mut truncated = false;
let mut inside_a_scope = !position.scope.is_empty();
let listed = if let Some(listed) = listed_by_the_caller {
listed
} else if inside_a_scope {
Known::Yes(crate::index::project::NameCompletions {
scope: position.scope.clone(),
prefix: position.written.clone(),
name_range: position.range,
names: index
.declarations_in(&position.scope, path)
.into_iter()
.map(|declaration| crate::index::project::OfferedName {
fact: declaration.fact.clone(),
file: declaration.file.clone(),
depth: 0,
from: crate::index::project::NameProvenance::Scope,
})
.collect(),
})
} else {
crate::index::project::name_completions_at(index, scopes, root, path, offset)
};
match listed {
Known::Yes(listed) => {
listed_scope = listed.scope.clone();
if listed.prefix.is_empty() {
listed_prefix = position.written.clone();
} else {
listed_prefix = listed.prefix.clone();
}
replace = if listed.name_range.length == 0 {
position.range
} else {
listed.name_range
};
inside_a_scope |= !listed_scope.is_empty();
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
for offered in &listed.names {
if reserved_for_the_implementation(&offered.fact.name, &listed_prefix) {
continue;
}
if !seen.insert(offered.fact.name.as_str()) {
continue;
}
let mut item = CompletionItem::declared(&offered.fact, &offered.file);
item.replace = replace;
if !listed.scope.is_empty() {
item.filter = Some(format!("{}::{}", listed.scope, offered.fact.name));
}
let matched = matching::quality(
item.filter.as_deref().unwrap_or(&item.label),
&listed_prefix,
);
if matched == matching::NONE {
continue;
}
scored.push(Scored {
score: name_score(offered),
matched,
item,
});
}
}
Known::Unknown(_) | Known::No => {}
}
if let Some(adaptors) = the_views_adaptors_a_scope_names(&listed_scope) {
for (name, takes_arguments, detail) in adaptors {
let matched = matching::quality(name, &listed_prefix);
if matched == matching::NONE {
continue;
}
let mut item = CompletionItem::word(
name,
if *takes_arguments {
ItemKind::Function
} else {
ItemKind::Variable
},
detail,
);
item.replace = replace;
item.filter = Some(format!("{listed_scope}::{name}"));
scored.push(Scored {
score: Score::new(Score::DIRECT_INCLUDE, 0),
matched,
item,
});
}
}
if with_table && !inside_a_scope {
let statements = true;
let in_a_class = in_a_class_body(scopes, offset);
for snippet in table::snippets_for(statements) {
let matched = matching::quality(snippet.trigger, &listed_prefix);
if matched == matching::NONE {
continue;
}
scored.push(Scored {
score: Score::new(Score::SNIPPET, 0),
matched,
item: CompletionItem::snippet(snippet.trigger, snippet.detail, snippet.body),
});
}
for keyword in table::keywords_for(statements, in_a_class) {
if table::a_snippet_writes_this(keyword.spelling) {
continue;
}
let matched = matching::quality(keyword.spelling, &listed_prefix);
if matched == matching::NONE {
continue;
}
scored.push(Scored {
score: Score::new(Score::KEYWORD, 0),
matched,
item: CompletionItem::word(keyword.spelling, ItemKind::Keyword, keyword.detail),
});
}
for (name, detail) in table::BUILTIN_TYPES {
let matched = matching::quality(name, &listed_prefix);
if matched == matching::NONE {
continue;
}
scored.push(Scored {
score: Score::new(Score::KEYWORD, 0),
matched,
item: CompletionItem::word(name, ItemKind::Class, detail),
});
}
if cuda {
for word in crate::cuda::words() {
let matched = matching::quality(word.name, &listed_prefix);
if matched == matching::NONE {
continue;
}
let kind = match word.kind {
crate::cuda::WordKind::Qualifier => ItemKind::Keyword,
crate::cuda::WordKind::Builtin => ItemKind::Variable,
crate::cuda::WordKind::VectorType => ItemKind::Class,
};
scored.push(Scored {
score: Score::new(Score::KEYWORD, 0),
matched,
item: CompletionItem::word(word.name, kind, word.detail),
});
}
}
}
if !listed_prefix.is_empty() {
scored.retain(|one| one.matched != matching::NONE);
}
if !unincluded.is_empty() && !inside_a_scope {
let labels: std::collections::HashSet<String> =
scored.iter().map(|one| one.item.label.clone()).collect();
for related in unincluded {
let Some(summary) = index.summary(&related.file) else {
continue;
};
for fact in &summary.declarations {
if fact.kind != DeclKind::Type
|| labels.iter().any(|label| label == fact.name.as_str())
{
continue;
}
let matched = matching::quality(&fact.name, &listed_prefix);
if matched == matching::NONE {
continue;
}
scored.push(Scored {
score: Score::new(Score::UNINCLUDED, Score::kind_penalty(fact.kind)),
matched,
item: CompletionItem::unincluded(
fact,
&related.file,
related.inclusion.clone(),
),
});
}
}
}
{
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
scored.retain(|one| seen.insert(one.item.label.clone()));
}
let (items, cut) = ordered(scored, budget);
truncated |= cut;
CompletionSet {
items,
scope: listed_scope,
prefix: listed_prefix,
replace,
truncated,
incomplete: false,
}
}
fn directives(written: &str, range: SourceRange) -> CompletionSet {
let items: Vec<CompletionItem> = table::DIRECTIVES
.iter()
.filter(|directive| matching::quality(directive.name, written) != matching::NONE)
.map(|directive| {
let mut item =
CompletionItem::word(directive.name, ItemKind::Keyword, directive.detail);
item.replace = range;
item
})
.collect();
CompletionSet {
scope: String::new(),
prefix: written.to_string(),
replace: range,
truncated: false,
incomplete: false,
items,
}
}
fn doc_comments(
index: &ProjectIndex,
path: &Path,
written: &str,
range: SourceRange,
wants: Option<cpp_parser::DocCommandKind>,
) -> CompletionSet {
use cpp_parser::DocCommandKind;
let mut items: Vec<CompletionItem> = Vec::new();
match wants {
Some(DocCommandKind::Parameter) => {
let Some(summary) = index.summary(path) else {
return CompletionSet {
prefix: written.to_string(),
replace: range,
..CompletionSet::default()
};
};
let documented = summary
.declarations
.iter()
.filter(|fact| fact.range.start_offset > range.start_offset)
.min_by_key(|fact| fact.range.start_offset);
if let Some(fact) = documented {
let mut names: Vec<String> = fact
.parameters()
.iter()
.filter(|name| !name.is_empty())
.cloned()
.collect();
if let Some(list) = fact.parameter_list()
&& let Some(found) = crate::sema::call_syntax::parameter_names_from_text(list)
{
names.extend(found.into_iter().flatten());
}
for name in names {
if matching::quality(&name, written) == matching::NONE {
continue;
}
let mut item = CompletionItem::word(&name, ItemKind::Variable, "a parameter");
item.replace = range;
items.push(item);
}
}
}
Some(_) => {}
None => {
for spec in cpp_parser::every_command() {
if matching::quality(spec.name, written) == matching::NONE {
continue;
}
let detail = match spec.kind {
DocCommandKind::Description => "describe",
DocCommandKind::Parameter => "a parameter",
DocCommandKind::Exception => "an exception",
DocCommandKind::Reference => "a reference",
DocCommandKind::Advisory => "a note",
DocCommandKind::Structural => "structure",
DocCommandKind::Callout => "a callout",
};
let mut item = CompletionItem::word(spec.name, ItemKind::Keyword, detail);
item.replace = range;
items.push(item);
}
}
}
CompletionSet {
scope: String::new(),
prefix: written.to_string(),
replace: range,
truncated: false,
incomplete: false,
items,
}
}
fn macro_body(
index: &ProjectIndex,
path: &Path,
written: &str,
range: SourceRange,
parameters: &[String],
) -> CompletionSet {
let mut items: Vec<CompletionItem> = Vec::new();
for parameter in parameters {
if matching::quality(parameter, written) == matching::NONE {
continue;
}
let mut item =
CompletionItem::word(parameter, ItemKind::Variable, "a parameter of this macro");
item.replace = range;
items.push(item);
}
for name in macro_names(index, path) {
if matching::quality(name, written) == matching::NONE {
continue;
}
let mut item = CompletionItem::word(name, ItemKind::Macro, "a macro");
item.replace = range;
items.push(item);
}
CompletionSet {
scope: String::new(),
prefix: written.to_string(),
replace: range,
truncated: false,
incomplete: false,
items,
}
}
fn macro_names<'a>(index: &'a ProjectIndex, path: &Path) -> Vec<&'a str> {
let Some(summary) = index.summary(path) else {
return Vec::new();
};
let mut macros: Vec<&str> = summary
.macros
.iter()
.map(|fact| fact.name.as_str())
.collect();
for include in &summary.includes {
let Some(resolved) = &include.resolved else {
continue;
};
let Some(included) = index.summary(resolved) else {
continue;
};
macros.extend(included.macros.iter().map(|fact| fact.name.as_str()));
}
macros.extend(PREDEFINED_MACROS.iter().copied());
macros.sort_unstable();
macros.dedup();
macros
}
const PREDEFINED_MACROS: &[&str] = &[
"__LINE__",
"__FILE__",
"__DATE__",
"__TIME__",
"__cplusplus",
"__STDC__",
"__STDC_HOSTED__",
"__STDC_VERSION__",
];
fn condition(
index: &ProjectIndex,
path: &Path,
written: &str,
range: SourceRange,
) -> CompletionSet {
let mut items: Vec<CompletionItem> = Vec::new();
for operator in ["defined", "__has_include", "__has_include_next"] {
if matching::quality(operator, written) == matching::NONE {
continue;
}
let mut item = CompletionItem::word(operator, ItemKind::Keyword, "a preprocessor operator");
item.replace = range;
items.push(item);
}
for name in macro_names(index, path) {
if matching::quality(name, written) == matching::NONE {
continue;
}
let mut item = CompletionItem::word(name, ItemKind::Macro, "a macro");
item.replace = range;
items.push(item);
}
CompletionSet {
scope: String::new(),
prefix: written.to_string(),
replace: range,
truncated: false,
incomplete: false,
items,
}
}
fn headers_for(
headers: &HeaderIndex,
written: &str,
closed: bool,
range: SourceRange,
) -> CompletionSet {
if closed {
return CompletionSet {
prefix: written.to_string(),
replace: range,
..CompletionSet::default()
};
}
let items: Vec<CompletionItem> = headers
.matching(written, HEADER_BUDGET)
.into_iter()
.map(|header| {
let mut item = CompletionItem::header(&header);
item.replace = range;
item.detail = Some(match header.kind {
HeaderKind::StandardLibrary => "the C++ standard library".to_string(),
HeaderKind::Project => "this project".to_string(),
HeaderKind::System => "on the include path".to_string(),
});
item
})
.collect();
CompletionSet {
scope: String::new(),
prefix: written.to_string(),
replace: range,
truncated: headers.truncated(),
incomplete: false,
items,
}
}
fn written_before(access: &crate::sema::resolve::MemberAccess, offset: usize) -> String {
let start = access.member_range.start_offset;
let end = access.member_range.end_offset().min(offset);
if end <= start {
return String::new();
}
access
.member
.get(..end - start)
.unwrap_or(&access.member)
.to_string()
}
fn member_kind(member: &ProjectMember, class: &str) -> ItemKind {
match member.fact.kind {
DeclKind::Function if member.fact.name == class => ItemKind::Function,
DeclKind::Function => ItemKind::Method,
DeclKind::Variable => ItemKind::Field,
DeclKind::Type => ItemKind::Class,
DeclKind::Namespace => ItemKind::Namespace,
DeclKind::MacroLike => ItemKind::Macro,
DeclKind::Other => ItemKind::Field,
}
}
const HEADER_BUDGET: usize = 200;
pub const ITEM_BUDGET: usize = 1000;
fn ordered(mut scored: Vec<Scored>, budget: usize) -> (Vec<CompletionItem>, bool) {
let by_rank = |one: &Scored, other: &Scored| {
other
.matched
.cmp(&one.matched)
.then_with(|| one.score.keys().cmp(&other.score.keys()))
.then_with(|| one.item.label.cmp(&other.item.label))
};
scored.sort_by(by_rank);
if scored.len() <= budget {
return (
scored.into_iter().map(|scored| scored.item).collect(),
false,
);
}
let mut buckets: Vec<Vec<Scored>> = Vec::new();
let mut which: std::collections::HashMap<Option<std::path::PathBuf>, usize> =
std::collections::HashMap::new();
for one in scored {
let key = one.item.identity.as_ref().map(|(file, _)| file.clone());
let index = *which.entry(key).or_insert_with(|| {
buckets.push(Vec::new());
buckets.len() - 1
});
buckets[index].push(one);
}
let widest = buckets.iter().map(Vec::len).max().unwrap_or(0);
let mut taken: Vec<Scored> = Vec::with_capacity(budget);
'fill: for round in 0..widest {
for bucket in &buckets {
let Some(one) = bucket.get(round) else {
continue;
};
taken.push(one.clone());
if taken.len() == budget {
break 'fill;
}
}
}
taken.sort_by(by_rank);
(taken.into_iter().map(|scored| scored.item).collect(), true)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Score {
tier: i32,
penalty: i32,
}
impl Score {
const LOCAL: i32 = 0;
const FILE: i32 = 100;
const SNIPPET: i32 = 140;
const KEYWORD: i32 = 150;
const DIRECT_INCLUDE: i32 = 200;
const INDIRECT_INCLUDE: i32 = 300;
const UNINCLUDED: i32 = 400;
fn new(tier: i32, penalty: i32) -> Score {
Score { tier, penalty }
}
fn keys(&self) -> (i32, i32) {
(self.tier, self.penalty)
}
fn kind_penalty(kind: DeclKind) -> i32 {
match kind {
DeclKind::Variable | DeclKind::Function => 0,
DeclKind::Type => 4,
DeclKind::Other => 5,
DeclKind::Namespace => 6,
DeclKind::MacroLike => 8,
}
}
}
fn name_score(offered: &crate::OfferedName) -> Score {
use crate::index::project::NameProvenance;
let tier = match offered.from {
NameProvenance::Scope => Score::LOCAL + offered.depth as i32,
NameProvenance::ThisFile => Score::FILE,
NameProvenance::DirectInclude => Score::DIRECT_INCLUDE,
NameProvenance::IndirectInclude => Score::INDIRECT_INCLUDE,
};
let penalty = Score::kind_penalty(offered.fact.kind)
+ if offered.fact.name.starts_with('~') {
20
} else {
0
};
Score::new(tier, penalty)
}
fn member_score(member: &ProjectMember, class: &str) -> Score {
let tier = Score::LOCAL + 10 * member.depth as i32;
let penalty = Score::kind_penalty(member.fact.kind)
+ if member.fact.name == class { 6 } else { 0 }
+ if member.fact.name.starts_with('~') {
20
} else {
0
};
Score::new(tier, penalty)
}
fn in_a_class_body(scopes: &ScopeTree, offset: usize) -> bool {
let Some(innermost) = scopes.scope_at(offset) else {
return false;
};
scopes.scope_chain(innermost).iter().any(|scope| {
matches!(
scopes.scope(*scope).map(|data| data.kind),
Some(ScopeKind::Class | ScopeKind::Enum)
)
})
}
pub fn header_index(
config: &crate::CompilerConfig,
root: &Path,
project_files: impl IntoIterator<Item = PathBuf>,
) -> SharedHeaders {
Arc::new(std::sync::RwLock::new(
HeaderIndex::read(includes::search_directories(config), root).with_project(project_files),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_candidate_that_does_not_answer_the_prefix_is_dropped() {
use crate::completion::matching::{NONE, PREFIX, SUBSEQUENCE, WORD_START, quality};
assert_eq!(quality("Widget", "wid"), PREFIX);
assert_eq!(
quality("Widget", ""),
quality("Widget", ""),
"the empty prefix matches everything"
);
assert!(quality("basic_string", "bsc") > NONE);
assert_eq!(quality("get_parent_id", "gpid"), WORD_START);
assert_eq!(quality("Widget", "xyz"), NONE);
assert_eq!(quality("Widget", "wz"), NONE);
assert_eq!(quality("Widget", "wdgt"), SUBSEQUENCE);
}
#[test]
fn the_tiers_are_in_the_order_a_reader_expects() {
const _: () = assert!(Score::LOCAL < Score::SNIPPET);
const _: () = assert!(Score::SNIPPET < Score::KEYWORD);
const _: () = assert!(Score::KEYWORD < Score::DIRECT_INCLUDE);
const _: () = assert!(Score::DIRECT_INCLUDE < Score::INDIRECT_INCLUDE);
}
#[test]
fn a_functions_detail_line_is_what_it_takes() {
let fact = |returns: Option<&str>, parameter_list: Option<&str>| DeclFact {
enumerator: false,
frees: 0,
name: "format".into(),
scope: Some("std".into()),
local: false,
kind: DeclKind::Function,
modifiers: crate::DeclModifiers::VIRTUAL,
type_of: None,
returns: returns.map(smol_str::SmolStr::from),
range: cpp_parser::SourceRange::new(0, 0),
name_range: cpp_parser::SourceRange::new(0, 0),
clean: true,
split_by_a_directive: false,
guard: crate::FactGuard::Unconditional,
access: None,
exported: false,
definition: true,
detail: crate::summary::DeclDetail::in_a_box(crate::summary::DeclDetail {
parameter_list: parameter_list.map(str::to_string),
..Default::default()
}),
};
assert_eq!(
detail_of(&fact(Some("string"), Some("()"))).as_deref(),
Some("string ()"),
"a function that takes nothing says so — that is an answer, not an absence"
);
assert_eq!(
detail_of(&fact(Some("string"), None)).as_deref(),
Some("string (…)"),
"and with no list recorded, the old spelling is still the honest one"
);
assert_eq!(
detail_of(&fact(None, Some("(int)"))).as_deref(),
Some("(int)"),
"a constructor has no return type, and its parameters are then the whole description"
);
assert_eq!(detail_of(&fact(None, None)), None, "nothing to say");
}
}