use cpp_parser::{CppSyntaxKind, CppSyntaxNode, SourceRange};
use crate::sema::resolve::{self, MemberAccess, NamePosition};
#[derive(Debug, Clone)]
pub enum CompletionContext {
Member(Box<MemberAccess>),
Designator {
of: String,
written: String,
range: SourceRange,
},
Qualified(NamePosition),
Name(NamePosition),
DirectiveName { written: String, range: SourceRange },
Include {
written: String,
delimiter: Option<char>,
closed: bool,
range: SourceRange,
},
DirectiveArgument { written: String, range: SourceRange },
ModuleName { written: String, range: SourceRange },
Condition {
written: String,
range: SourceRange,
},
MacroBody {
written: String,
range: SourceRange,
parameters: Vec<String>,
qualifier: String,
},
DocComment {
written: String,
range: SourceRange,
wants: Option<cpp_parser::DocCommandKind>,
},
Nothing,
DocLink {
written: String,
range: SourceRange,
},
DocCode {
written: String,
range: SourceRange,
},
}
pub fn context_at(root: &CppSyntaxNode, offset: usize) -> CompletionContext {
if let Some(comment) = doc_comment_at(root, offset) {
return comment;
}
if inside_a_comment_or_a_literal(root, offset) {
return CompletionContext::Nothing;
}
if let Some(directive) = directive_at(root, offset) {
return directive;
}
if let Some((written, range)) = module_name_from_the_text(&root.text().to_string(), offset) {
return CompletionContext::ModuleName { written, range };
}
if let Some(access) = resolve::member_access_at(root, offset)
.or_else(|| member_access_from_the_text(root, offset))
{
return CompletionContext::Member(Box::new(access));
}
if let Some(designator) = the_designator_at(root, offset) {
return designator;
}
match resolve::name_position_at(root, offset) {
Some(position) if position.scope.is_empty() => {
match the_qualifier_written_before(
&root.text().to_string(),
position.range.start_offset,
) {
Some(scope) => {
CompletionContext::Qualified(resolve::NamePosition { scope, ..position })
}
None => CompletionContext::Name(position),
}
}
Some(position) => CompletionContext::Qualified(position),
None => CompletionContext::Nothing,
}
}
fn the_qualifier_written_before(text: &str, at: usize) -> Option<String> {
let before = text.get(..at)?.trim_end();
if !before.ends_with("::") {
return None;
}
let mut path: Vec<&str> = Vec::new();
let mut rest = before;
while let Some(without_separator) = rest.strip_suffix("::") {
let without_separator = without_separator.trim_end();
let start = without_separator
.char_indices()
.rev()
.take_while(|(_, character)| {
character.is_alphanumeric() || *character == '_' || *character == '~'
})
.last()
.map(|(index, _)| index)?;
let segment = &without_separator[start..];
if segment.is_empty() {
break;
}
path.push(segment);
rest = without_separator[..start].trim_end();
}
if path.is_empty() {
return None;
}
path.reverse();
Some(path.join("::"))
}
pub fn doc_comment_at(root: &CppSyntaxNode, offset: usize) -> Option<CompletionContext> {
let text = root.text().to_string();
let before = text.get(..offset.min(text.len()))?;
let line_start = before.rfind('\n').map_or(0, |at| at + 1);
let line = before.get(line_start..)?;
let trimmed = line.trim_start();
let is_a_documentation_line = trimmed.starts_with("///")
|| trimmed.starts_with("//!")
|| trimmed.starts_with("/**")
|| trimmed.starts_with("/*!");
let inside_a_documentation_block = if is_a_documentation_line {
true
} else {
match (before.rfind("/*"), before.rfind("*/")) {
(Some(opened), closed) => {
let still_open = closed.is_none_or(|closed| closed < opened);
still_open
&& (before[opened..].starts_with("/**") || before[opened..].starts_with("/*!"))
}
_ => false,
}
};
if !inside_a_documentation_block {
return None;
}
if crate::doc::inside_a_code_block(&root.text().to_string(), offset) {
let line_before_cursor = &line[..line.len().min(line.len())];
let typed = line_before_cursor
.trim_end()
.rsplit(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
.next()
.unwrap_or("");
let start = line_start + line.len().saturating_sub(typed.len());
return Some(CompletionContext::DocCode {
written: typed.to_string(),
range: SourceRange::new(start, typed.len()),
});
}
if let Some(opened) = before[line_start..].rfind("[`") {
let target_start = opened + 2;
let typed = &line[target_start..];
if !typed.contains('`') && !typed.contains(']') {
let written = typed.trim();
return Some(CompletionContext::DocLink {
written: written.to_string(),
range: SourceRange::new(
line_start + target_start + typed.len() - typed.trim_start().len(),
written.len(),
),
});
}
}
let last_introducer = line.rfind(['@', '\\']);
if let Some(at) = last_introducer {
let after = line[at + 1..].to_string();
if after.chars().all(|c| c.is_ascii_alphanumeric()) {
let start = line_start + at + 1;
return Some(CompletionContext::DocComment {
written: after.to_string(),
range: SourceRange::new(start, after.len()),
wants: None,
});
}
let rest = after.trim_start();
let rest = match rest.strip_prefix('[').and_then(|_| rest.find(']')) {
Some(close) => rest[close + 1..].trim_start(),
None => rest,
};
let command = rest.split_whitespace().next().unwrap_or("");
let argument = rest[command.len()..].trim_start();
let is_a_word = |text: &str| {
text.chars()
.all(|character| character.is_ascii_alphanumeric() || character == '_')
};
if is_a_word(command)
&& cpp_parser::command_args(command) == cpp_parser::DocCommandArgs::ReferenceAndBody
{
let typed = argument.trim();
let target = typed.split_whitespace().next().unwrap_or("");
if typed.is_empty() || !typed.contains(char::is_whitespace) {
let start = line_start + line.len().saturating_sub(argument.len());
return Some(CompletionContext::DocLink {
written: target.to_string(),
range: SourceRange::new(start, target.len()),
});
}
}
if is_a_word(command)
&& is_a_word(argument)
&& let Some(kind) = cpp_parser::command_kind(command)
&& matches!(
cpp_parser::command_args(command),
cpp_parser::DocCommandArgs::NameAndBody
| cpp_parser::DocCommandArgs::DirectionalNameAndBody
)
{
let start = line_start + line.len().saturating_sub(argument.len());
let length = argument.len();
return Some(CompletionContext::DocComment {
written: argument.to_string(),
range: SourceRange::new(start, length),
wants: Some(kind),
});
}
}
None
}
pub fn module_name_from_the_text(text: &str, offset: usize) -> Option<(String, SourceRange)> {
let before = text.get(..offset.min(text.len()))?;
let line_start = before.rfind('\n').map_or(0, |at| at + 1);
let line = &before[line_start..];
let is_a_name_character =
|character: char| character.is_alphanumeric() || character == '_' || character == '.';
let (written, head) = if line.ends_with(char::is_whitespace) {
("", line.trim_end())
} else {
let word_start = line
.rfind(|character: char| !is_a_name_character(character))
.map_or(0, |at| at + 1);
(&line[word_start..], line[..word_start].trim_end())
};
if written.contains('<') || written.contains('"') {
return None;
}
let keyword = head
.rsplit(|character: char| !character.is_alphanumeric())
.next()
.unwrap_or_default();
if keyword != "import" && keyword != "module" {
return None;
}
let start = offset.checked_sub(written.len())?;
Some((written.to_string(), SourceRange::new(start, written.len())))
}
fn the_designator_at(root: &CppSyntaxNode, offset: usize) -> Option<CompletionContext> {
let operator = resolve::operator_in(root, offset).or_else(|| {
offset
.checked_sub(1)
.and_then(|before| resolve::operator_in(root, before))
})?;
if operator.text() != "." {
return None;
}
let dot = usize::from(operator.text_range().start());
if resolve::name_ending_before_an_operator(root, dot).is_some() {
return None;
}
let text = root.text().to_string();
let mut depth = 0i32;
let mut opened = None;
for (at, character) in text[..dot].char_indices().rev() {
match character {
'}' => depth += 1,
'{' if depth > 0 => depth -= 1,
'{' => {
opened = Some(at);
break;
}
';' if depth == 0 => return None,
_ => {}
}
}
let open = opened?;
let before = text[..open].trim_end().strip_suffix('=')?;
let before = before.trim_end();
let name_start = before
.rfind(|character: char| !(character.is_alphanumeric() || character == '_'))
.map_or(0, |at| at + 1);
if name_start >= before.len() {
return None;
}
let head = before[..name_start].trim_end();
let type_start = head.rfind([';', '{', '}']).map_or(0, |at| at + 1);
let of = head[type_start..].trim().to_string();
if of.is_empty() || of.contains('(') || of.contains(')') || of.contains('=') {
return None;
}
let after = usize::from(operator.text_range().end());
let written: String = text
.get(after..offset)
.unwrap_or("")
.chars()
.take_while(|character| character.is_alphanumeric() || *character == '_')
.collect();
Some(CompletionContext::Designator {
of,
range: SourceRange::new(after, written.len()),
written,
})
}
fn member_access_from_the_text(
root: &CppSyntaxNode,
offset: usize,
) -> Option<resolve::MemberAccess> {
let operator = resolve::operator_in(root, offset).or_else(|| {
offset
.checked_sub(1)
.and_then(|before| resolve::operator_in(root, before))
})?;
let at = usize::from(operator.text_range().end());
let object = resolve::name_ending_before_an_operator(root, at)?;
let arrow = operator.text().to_string().ends_with('>');
Some(resolve::MemberAccess {
object,
member: String::new(),
member_range: SourceRange::new(at, 0),
arrow,
})
}
fn directive_line(root: &CppSyntaxNode, offset: usize) -> Option<(String, usize, usize)> {
let text = root.text().to_string();
let line_start = text[..offset.min(text.len())]
.rfind('\n')
.map_or(0, |at| at + 1);
let line_end = text[line_start..]
.find('\n')
.map_or(text.len(), |at| line_start + at);
let line = &text[line_start..line_end];
let hash = line_start + line.len() - line.trim_start().len();
if text[hash..].starts_with('#') {
Some((text[line_start..line_end].to_string(), line_start, line_end))
} else {
None
}
}
fn directive_at(root: &CppSyntaxNode, offset: usize) -> Option<CompletionContext> {
let (text, start, end) =
match node_ancestor_of_kind(root, offset, CppSyntaxKind::PreprocessorDirective) {
Some(node) => {
let range = node.text_range();
(
node.text().to_string(),
usize::from(range.start()),
usize::from(range.end()),
)
}
None => directive_line(root, offset)?,
};
let cut = offset.clamp(start, end).saturating_sub(start);
let Some(before) = text.get(..cut) else {
return Some(CompletionContext::Nothing);
};
let after_hash = before.strip_prefix('#')?;
let bare = after_hash.trim_start();
let name_ends_at = bare.find(char::is_whitespace);
let (name, rest) = match name_ends_at {
Some(at) => (&bare[..at], Some(bare[at..].trim_start())),
None => (bare, None),
};
let complete = name_ends_at.is_some();
if !complete {
let written_at = start + (before.len() - name.len());
return Some(CompletionContext::DirectiveName {
written: name.to_string(),
range: SourceRange::new(written_at, name.len()),
});
}
let Some(rest) = rest else {
return Some(CompletionContext::DirectiveArgument {
written: String::new(),
range: SourceRange::new(offset, 0),
});
};
match name {
"define" => Some(define_at(rest, start, before.len(), offset)),
"if" | "elif" | "ifdef" | "ifndef" | "undef" => Some(condition_argument(
rest,
start + before.len() - rest.len(),
before.len(),
offset,
)),
"include" | "include_next" | "pragma" | "line" | "error" | "warning" | "assert"
| "unassert" => Some(header_or_name(name, rest, start, before.len(), offset)),
_ => Some(CompletionContext::Nothing),
}
}
fn define_at(
rest: &str,
directive_start: usize,
written_before_cursor: usize,
offset: usize,
) -> CompletionContext {
let argument_at = directive_start + written_before_cursor - rest.len();
let body = |from: usize, at: usize, parameters: Vec<String>| {
let (written, range) = segment_written(&rest[from..], at, offset);
let qualifier = the_qualifier_before(&rest[from..], at, range);
CompletionContext::MacroBody {
written,
range,
parameters,
qualifier,
}
};
let name_length = rest
.find(|character: char| !(character.is_alphanumeric() || character == '_'))
.unwrap_or(rest.len());
let after_the_name = &rest[name_length..];
let Some(open) = after_the_name.find('(') else {
if rest.len() <= name_length {
let (written, range) = segment_written(rest, argument_at, offset);
return CompletionContext::DirectiveArgument { written, range };
}
return body(name_length, argument_at + name_length, Vec::new());
};
let space_before_the_paren = after_the_name[..open]
.chars()
.any(|character| character.is_whitespace());
if space_before_the_paren {
return body(name_length, argument_at + name_length, Vec::new());
}
let Some(close) = after_the_name.find(')') else {
return CompletionContext::Nothing;
};
let parameters: Vec<String> = after_the_name[open + 1..close]
.split(',')
.map(|parameter| parameter.trim().to_string())
.filter(|parameter| !parameter.is_empty() && parameter != "...")
.collect();
if written_before_cursor <= name_length + close + 1 {
return CompletionContext::Nothing;
}
body(
name_length + close + 1,
argument_at + name_length + close + 1,
parameters,
)
}
fn the_qualifier_before(rest: &str, at: usize, range: SourceRange) -> String {
let is_a_name_byte = |byte: u8| byte.is_ascii_alphanumeric() || byte == b'_';
let end = range.start_offset.saturating_sub(at).min(rest.len());
let before = rest[..end].trim_end();
let mut head = before;
let mut start = before.len();
while let Some(before_the_colons) = head.strip_suffix("::") {
let trimmed = before_the_colons.trim_end();
let mut begin = trimmed.len();
while begin > 0 && is_a_name_byte(trimmed.as_bytes()[begin - 1]) {
begin -= 1;
}
if begin == trimmed.len() {
break;
}
start = begin;
head = &trimmed[..begin];
}
if start >= before.len() {
return String::new();
}
before[start..].trim_end_matches(':').to_string()
}
fn header_or_name(
directive: &str,
rest: &str,
directive_start: usize,
written_before_cursor: usize,
offset: usize,
) -> CompletionContext {
let argument_at = directive_start + written_before_cursor - rest.len();
if directive != "include" && directive != "include_next" {
let (written, range) = segment_written(rest, argument_at, offset);
return CompletionContext::DirectiveArgument { written, range };
}
let delimiter = rest
.chars()
.next()
.filter(|first| *first == '<' || *first == '"');
if delimiter.is_none() {
let (written, range) = segment_written(rest, argument_at, offset);
return CompletionContext::DirectiveArgument { written, range };
}
let inner = &rest[1..];
let closer = match delimiter {
Some('<') => Some('>'),
Some('"') => Some('"'),
_ => None,
};
let closed = closer.is_some_and(|closer| inner.contains(closer));
let (written, range) = segment_written(inner, argument_at + 1, offset);
CompletionContext::Include {
written,
delimiter,
closed,
range,
}
}
fn segment_written(rest: &str, at: usize, offset: usize) -> (String, SourceRange) {
let cursor = offset.saturating_sub(at).min(rest.len());
let bytes = rest.as_bytes();
let is_name = |byte: u8| {
byte.is_ascii_alphanumeric()
|| matches!(byte, b'_' | b'.' | b'/' | b'-')
|| byte >= 0x80
};
let mut start = cursor;
while start > 0 && is_name(bytes[start - 1]) {
start -= 1;
}
let mut end = cursor;
while end < rest.len() && is_name(bytes[end]) {
end += 1;
}
(
rest[start..cursor].to_string(),
SourceRange::new(at + start, end - start),
)
}
fn node_ancestor_of_kind(
root: &CppSyntaxNode,
offset: usize,
kind: CppSyntaxKind,
) -> Option<CppSyntaxNode> {
let token = cpp_parser::token_at(root, offset);
match token {
Some(token) => token
.parent_ancestors()
.find(|node| CppSyntaxKind::from(node.kind()) == kind),
None => root
.ancestors()
.find(|node| CppSyntaxKind::from(node.kind()) == kind),
}
}
fn inside_a_comment_or_a_literal(root: &CppSyntaxNode, offset: usize) -> bool {
let Some(token) = cpp_parser::token_at(root, offset) else {
return false;
};
if matches!(
cpp_parser::CppTokenKind::from(token.kind()),
cpp_parser::CppTokenKind::LineComment
| cpp_parser::CppTokenKind::BlockComment
| cpp_parser::CppTokenKind::StringLiteral
| cpp_parser::CppTokenKind::CharLiteral
) {
let range = cpp_parser::source_range(token.text_range());
return range.start_offset < offset && offset < range.end_offset();
}
token
.parent_ancestors()
.any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::DocComment)
}
fn condition_argument(
rest: &str,
at: usize,
written_before_cursor: usize,
offset: usize,
) -> CompletionContext {
let _ = written_before_cursor;
let trimmed = rest.trim_start();
let skipped = rest.len() - trimmed.len();
let word_start = trimmed
.rfind(|character: char| {
!(character.is_alphanumeric()
|| character == '_'
|| character == '.'
|| character == '/'
|| character == '-')
})
.map_or(0, |found| found + 1);
let (written, range) =
segment_written(&trimmed[word_start..], at + skipped + word_start, offset);
CompletionContext::Condition { written, range }
}
#[cfg(test)]
mod tests {
use super::*;
fn context_in(source: &str) -> (CompletionContext, usize, String) {
let offset = source.find('|').expect("the fixture marks the cursor");
let text = source.replace('|', "");
let root =
cpp_parser::CppParser::parse(&text, cpp_parser::ParserConfig::default()).get_red_root();
(context_at(&root, offset), offset, text)
}
#[test]
fn a_member_access_is_a_member_context() {
let (context, ..) = context_in("void f() { Widget w; w.| }\n");
assert!(
matches!(context, CompletionContext::Member(_)),
"{context:?}"
);
}
#[test]
fn a_qualified_name_is_a_qualified_context() {
let (context, ..) = context_in("void f() { ns::| }\n");
match context {
CompletionContext::Qualified(position) => assert_eq!(position.scope, "ns"),
other => panic!("a `::` names a scope: {other:?}"),
}
}
#[test]
fn a_qualifier_is_read_from_the_text_when_the_tree_misses_it() {
let source = "int main() {\n return 0;\n}\n\nvoid probe() {\n std::ve|\n}\n";
let (context, ..) = context_in(source);
match context {
CompletionContext::Qualified(position) => {
assert_eq!(position.scope, "std", "the `::` names `std`");
assert_eq!(position.written, "ve");
}
other => panic!("`std::ve` names a scope: {other:?}"),
}
}
#[test]
fn a_half_written_name_after_a_scope_is_still_qualified() {
let (context, ..) = context_in("void f() { std::s| }\n");
match context {
CompletionContext::Qualified(position) => {
assert_eq!(position.scope, "std", "the scope is written");
assert_eq!(
position.written, "s",
"and the name being typed is its tail"
);
}
other => panic!("`std::s` names a scope: {other:?}"),
}
}
#[test]
fn a_bare_cursor_is_a_name_context() {
let (context, ..) = context_in("void f() { int x = | }\n");
match context {
CompletionContext::Name(position) => {
assert!(position.scope.is_empty(), "no qualifier was written");
}
other => panic!("a cursor in an expression is a name position: {other:?}"),
}
}
#[test]
fn a_comment_is_not_code() {
let (context, ..) = context_in("// a note |here\nint x;\n");
assert!(matches!(context, CompletionContext::Nothing), "{context:?}");
}
#[test]
fn the_end_of_a_comment_is_not_inside_it() {
let (context, ..) = context_in("int a; // a note|\n");
assert!(
matches!(context, CompletionContext::Name(_)),
"the position after a comment is a name position: {context:?}"
);
}
#[test]
fn a_doc_comment_is_not_code_either() {
let (context, ..) = context_in("/// a note |here\nint x;\n");
assert!(matches!(context, CompletionContext::Nothing), "{context:?}");
}
#[test]
fn a_string_literal_is_not_code() {
let (context, ..) = context_in("const char* s = \"hello |\";\n");
assert!(matches!(context, CompletionContext::Nothing), "{context:?}");
}
#[test]
fn a_hash_is_the_directives_own_name() {
let (context, ..) = context_in("int x;\n#|\n");
match context {
CompletionContext::DirectiveName { written, .. } => assert!(written.is_empty()),
other => panic!("a lone `#` asks for a directive: {other:?}"),
}
}
#[test]
fn a_partial_directive_name_is_replaced_not_extended() {
let (context, offset, _) = context_in("int x;\n#inc|\n");
match context {
CompletionContext::DirectiveName { written, range } => {
assert_eq!(written, "inc", "what has been typed filters the list");
assert_eq!(range.start_offset, offset - 3, "and the edit replaces it");
assert_eq!(range.length, 3);
}
other => panic!("`#inc` is the directive's own name: {other:?}"),
}
}
#[test]
fn an_include_asks_for_a_header() {
let (context, ..) = context_in("#include <vec|\n");
match context {
CompletionContext::Include {
written,
delimiter,
closed,
..
} => {
assert_eq!(written, "vec");
assert_eq!(delimiter, Some('<'));
assert!(!closed);
}
other => panic!("after `#include` the answer is headers: {other:?}"),
}
}
#[test]
fn a_closed_include_has_nothing_to_complete() {
let (context, ..) = context_in("#include <vector>|\n");
match context {
CompletionContext::Include { closed, .. } => assert!(closed),
other => panic!("{other:?}"),
}
}
#[test]
fn an_include_without_a_delimiter_is_an_ordinary_name_position() {
let (context, ..) = context_in("#include vec|\n");
match context {
CompletionContext::DirectiveArgument { written, .. } => assert_eq!(written, "vec"),
other => panic!("no delimiter was written: {other:?}"),
}
}
#[test]
fn an_include_with_the_cursor_after_the_delimiter_has_an_empty_prefix() {
let (context, ..) = context_in("#include <|\n");
match context {
CompletionContext::Include {
written, delimiter, ..
} => {
assert!(written.is_empty(), "nothing is written yet");
assert_eq!(delimiter, Some('<'));
}
other => panic!("{other:?}"),
}
}
#[test]
fn an_endif_takes_no_argument() {
let (context, ..) = context_in("#endif |\n");
assert!(matches!(context, CompletionContext::Nothing), "{context:?}");
}
#[test]
fn a_define_argument_is_an_ordinary_name_position() {
let (context, ..) = context_in("#define |\n");
assert!(
matches!(context, CompletionContext::DirectiveArgument { .. }),
"{context:?}"
);
}
#[test]
fn a_member_access_with_nothing_after_the_operator_is_read_from_the_text() {
let source = "#include <string>\nint main() {\n std::string full;\n full.\n;\n}\n";
let root = cpp_parser::CppParser::parse(source, cpp_parser::ParserConfig::default())
.get_red_root();
let dot = source.find("full.").expect("the fixture") + "full".len();
assert_eq!(&source[dot..dot + 1], ".", "the fixture's operator");
for offset in [dot, dot + 1] {
let access = super::member_access_from_the_text(&root, offset).unwrap_or_else(|| {
panic!(
"the offset {offset} is on the `.` at {dot} and must read as a member access; the token there \
is {:?} and the object before the operator is {:?}",
cpp_parser::token_at(&root, offset)
.map(|token| (cpp_parser::CppTokenKind::from(token.kind()), token.text().to_string())),
resolve::name_ending_before_an_operator(&root, dot + 1)
.map(|node| node.text().to_string()),
)
});
assert_eq!(access.object.text().to_string(), "full");
assert!(access.member.is_empty(), "nothing is written after the dot");
assert_eq!(
access.member_range.start_offset,
dot + 1,
"and the name goes immediately after the operator"
);
}
}
}