pub mod context;
pub mod includes;
pub mod matching;
pub mod table;
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,
}
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.clone(),
kind: kind_of(fact.kind),
insert: match (&fact.kind, &fact.parameter_list) {
(crate::DeclKind::MacroLike, Some(_)) => format!("{}(", fact.name),
_ => fact.name.clone(),
},
snippet: false,
detail: detail_of(fact),
identity,
filter: None,
fact: Some(fact.clone()),
replace: SourceRange::new(0, 0),
}
}
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),
}
}
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),
}
}
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),
}
}
}
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.clone()),
(None, None) => None,
},
DeclKind::Variable => fact.type_of.clone(),
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 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,
) -> CompletionSet {
let asked = context_at(root, offset);
completion_with(index, scopes, root, path, offset, headers, asked, cuda)
}
pub fn completion_with(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
offset: usize,
headers: &HeaderIndex,
context: CompletionContext,
cuda: bool,
) -> CompletionSet {
match context {
CompletionContext::Nothing => CompletionSet {
replace: SourceRange::new(offset, 0),
..CompletionSet::default()
},
CompletionContext::Member(access) => {
members(index, scopes, root, path, &access, offset).set
}
CompletionContext::Qualified(position) => {
names(index, scopes, root, path, &position, offset, false, cuda)
}
CompletionContext::Name(position) => {
names(index, scopes, root, path, &position, offset, true, cuda)
}
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)
}
CompletionContext::Include {
written,
closed,
range,
..
} => headers_for(headers, &written, closed, range),
CompletionContext::MacroBody {
written,
range,
parameters,
} => macro_body(index, path, &written, range, ¶meters),
CompletionContext::Condition { written, range } => condition(index, path, &written, range),
CompletionContext::DocComment {
written,
range,
wants,
} => doc_comments(index, path, &written, range, wants),
}
}
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).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 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 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 = crate::index::project::operator_returns_of(
index,
&mut |_: &Path| None,
scopes,
root,
path,
¤t,
"operator->",
);
let Some(returns) = returns else {
return Some((class, 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();
}
}
current.class_name().map(str::to_string).map(|bare| {
let class = if bare.contains("::") {
bare.clone()
} else {
crate::index::project::qualified_from_the_index(index, path, &bare)
.unwrap_or_else(|| bare.clone())
};
(class, 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;
};
if !members
.members
.iter()
.any(|member| matches!(member.fact.name.as_str(), "operator->" | "operator*"))
{
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(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
access: &crate::sema::resolve::MemberAccess,
offset: 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()
));
}
};
let Some((class, followed_a_pointer)) =
the_class_after_the_operator(index, scopes, root, path, &written, access.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",
access.object.text().to_string().trim()
),
};
};
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 !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);
let offered = items.len();
let (replace, items) = if followed_a_pointer && !access.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 names(
index: &ProjectIndex,
scopes: &ScopeTree,
root: &CppSyntaxNode,
path: &Path,
position: &crate::sema::resolve::NamePosition,
offset: usize,
with_table: bool,
cuda: bool,
) -> 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;
match crate::index::project::name_completions_at(index, scopes, root, path, offset) {
Known::Yes(listed) => {
listed_scope = listed.scope.clone();
listed_prefix = listed.prefix.clone();
replace = listed.name_range;
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
for offered in &listed.names {
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 with_table {
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),
});
}
}
}
let (items, cut) = ordered(scored);
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::inlay::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.sort_unstable();
macros.dedup();
macros
}
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;
const ITEM_BUDGET: usize = 200;
fn ordered(mut scored: Vec<Scored>) -> (Vec<CompletionItem>, bool) {
scored.sort_by(|one, other| {
one.score
.keys()
.cmp(&other.score.keys())
.then_with(|| other.matched.cmp(&one.matched))
.then_with(|| one.item.label.cmp(&other.item.label))
});
let truncated = scored.len() > ITEM_BUDGET;
scored.truncate(ITEM_BUDGET);
(
scored.into_iter().map(|scored| scored.item).collect(),
truncated,
)
}
#[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;
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 {
name: "format".to_string(),
scope: Some("std".to_string()),
local: false,
in_namespace: None,
kind: DeclKind::Function,
modifiers: crate::DeclModifiers::VIRTUAL,
type_of: None,
returns: returns.map(str::to_string),
bases: Vec::new(),
parameters: Vec::new(),
constraints: Vec::new(),
parameter_defaults: Vec::new(),
pattern: None,
parameter_list: parameter_list.map(str::to_string),
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,
};
assert_eq!(
detail_of(&fact(Some("string"), Some("(_Fmt, _Args...)"))).as_deref(),
Some("string (_Fmt, _Args...)"),
"the return type and the parameters, as the file spells them"
);
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");
}
}