use cpp_parser::CppAstNode;
use cpp_parser::CppSyntaxKind;
use super::CheckContext;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Origin {
Local,
StaticLocal,
ByValueParameter,
ReferenceParameter,
Member,
Global,
Temporary,
StringLiteral,
Unknown,
}
pub(crate) struct Borrowed {
pub(crate) kind: Origin,
pub(crate) description: String,
pub(crate) through: Option<&'static str>,
pub(crate) address_of: bool,
}
pub(crate) fn view_name_of(return_type: &str) -> Option<String> {
let mut head = return_type.trim().trim_end_matches('&').trim();
head = head
.trim_start_matches("const ")
.trim_start_matches("volatile ")
.trim();
let base = head.rsplit("::").next()?.trim();
let base = base.trim_end_matches('*').trim();
match base {
"string_view" | "basic_string_view" | "span" | "initializer_list" | "StringRef" => {
Some(base.to_string())
}
_ => None,
}
}
fn is_an_owner(spelling: &str) -> bool {
matches!(
spelling,
"string"
| "wstring"
| "basic_string"
| "vector"
| "deque"
| "list"
| "array"
| "map"
| "set"
| "unordered_map"
| "unordered_set"
| "optional"
| "variant"
| "tuple"
| "pair"
| "unique_ptr"
| "shared_ptr"
| "function"
)
}
pub(crate) fn origin_of(
context: &CheckContext<'_>,
expression: &cpp_parser::CppSyntaxNode,
function_body: &cpp_parser::CppSyntaxNode,
) -> Option<Borrowed> {
match kind(expression) {
CppSyntaxKind::ParenExpr => {
let inner = expression.children().next()?;
origin_of(context, &inner, function_body)
}
CppSyntaxKind::IdentifierExpr | CppSyntaxKind::NameExpr => {
let description = expression.text().to_string();
let offset = the_last_identifier_offset(expression)?;
let crate::Known::Yes(binding) =
crate::sema::resolve::definition_at(context.scopes(), context.tree(), offset)
else {
return Some(unknown(description));
};
let Some(scope) = context.scopes().scope(binding.scope) else {
return Some(unknown(description));
};
let inside_the_body = binding.name_range.start_offset
>= usize::from(function_body.text_range().start())
&& binding.name_range.end_offset() <= usize::from(function_body.text_range().end());
let before_the_body =
binding.name_range.start_offset < usize::from(function_body.text_range().start());
let origin = match scope.kind {
crate::ScopeKind::Class => Origin::Member,
crate::ScopeKind::Function if before_the_body => {
if a_parameter_is_a_reference(context, &binding) {
Origin::ReferenceParameter
} else {
Origin::ByValueParameter
}
}
_ if !inside_the_body => Origin::Global,
_ if declared_static(context, &binding) => Origin::StaticLocal,
_ => Origin::Local,
};
Some(Borrowed {
kind: origin,
description,
through: None,
address_of: false,
})
}
CppSyntaxKind::MemberExpr | CppSyntaxKind::IndexExpr => {
let base = expression.children().next()?;
let mut borrowed = origin_of(context, &base, function_body)?;
borrowed.description = expression.text().to_string();
Some(borrowed)
}
CppSyntaxKind::ThisExpr => Some(Borrowed {
kind: Origin::Member,
description: "this".to_string(),
through: None,
address_of: false,
}),
CppSyntaxKind::UnaryExpr => {
let operator = expression
.children_with_tokens()
.filter_map(|element| element.into_token())
.next()
.map(|token| cpp_parser::CppTokenKind::from(token.kind()));
if operator == Some(cpp_parser::CppTokenKind::Ampersand) {
let mut borrowed =
origin_of(context, &expression.children().next()?, function_body)?;
borrowed.address_of = true;
borrowed.description = expression.text().to_string();
return Some(borrowed);
}
if operator == Some(cpp_parser::CppTokenKind::Star) {
return Some(unknown(expression.text().to_string()));
}
Some(temporary(expression))
}
CppSyntaxKind::CallExpr => {
let callee = expression.children().next()?;
let arguments: Vec<cpp_parser::CppSyntaxNode> = expression.children().skip(1).collect();
let callee_name = the_last_identifier_of(&callee);
if is_a_member_access(&callee) {
let receiver = callee.children().next()?;
let mut borrowed = origin_of(context, &receiver, function_body)?;
borrowed.through = match callee_name.as_deref() {
Some("c_str") => Some("c_str"),
Some("data") => Some("data"),
_ => None,
};
return Some(borrowed);
}
if let Some(name) = callee_name.as_deref() {
if matches!(name, "move" | "forward") {
return origin_of(context, arguments.first()?, function_body);
}
if view_name_of(name).is_some() {
return match arguments.first() {
Some(argument) => origin_of(context, argument, function_body),
None => Some(temporary(expression)),
};
}
if is_an_owner(name) {
return Some(temporary(expression));
}
}
Some(unknown(expression.text().to_string()))
}
CppSyntaxKind::InitListExpr => {
let children: Vec<cpp_parser::CppSyntaxNode> = expression.children().collect();
match children.len() {
1 => origin_of(context, &children[0], function_body),
_ => Some(temporary(expression)),
}
}
CppSyntaxKind::LiteralExpr => {
let is_string = expression
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| {
cpp_parser::CppTokenKind::from(token.kind())
== cpp_parser::CppTokenKind::StringLiteral
});
Some(Borrowed {
kind: if is_string {
Origin::StringLiteral
} else {
Origin::Temporary
},
description: expression.text().to_string(),
through: None,
address_of: false,
})
}
_ => Some(unknown(expression.text().to_string())),
}
}
fn a_parameter_is_a_reference(context: &CheckContext<'_>, binding: &crate::Binding) -> bool {
let range = binding.range;
let Some(text) = context.source.get(range.start_offset..range.end_offset()) else {
return false;
};
let name_start = binding
.name_range
.start_offset
.saturating_sub(range.start_offset)
.min(text.len());
text[..name_start].contains('&')
}
fn unknown(description: String) -> Borrowed {
Borrowed {
kind: Origin::Unknown,
description,
through: None,
address_of: false,
}
}
fn temporary(expression: &cpp_parser::CppSyntaxNode) -> Borrowed {
Borrowed {
kind: Origin::Temporary,
description: expression.text().to_string(),
through: None,
address_of: false,
}
}
fn is_a_member_access(expression: &cpp_parser::CppSyntaxNode) -> bool {
expression
.children_with_tokens()
.filter_map(|element| element.into_token())
.any(|token| {
matches!(
cpp_parser::CppTokenKind::from(token.kind()),
cpp_parser::CppTokenKind::Dot | cpp_parser::CppTokenKind::Arrow
)
})
}
fn declared_static(context: &CheckContext<'_>, binding: &crate::Binding) -> bool {
let name_start = binding.name_range.start_offset;
let declaration = context
.own::<cpp_parser::CppDeclaration>()
.filter(|declaration| {
let range = declaration.syntax().text_range();
usize::from(range.start()) <= name_start && name_start < usize::from(range.end())
})
.max_by_key(|declaration| usize::from(declaration.syntax().text_range().start()));
let Some(declaration) = declaration else {
return false;
};
let start = usize::from(declaration.syntax().text_range().start());
let Some(text) = context.source.get(start..name_start) else {
return false;
};
text.split(|character: char| !character.is_alphanumeric() && character != '_')
.any(|word| word == "static" || word == "thread_local")
}
fn the_last_identifier_offset(expression: &cpp_parser::CppSyntaxNode) -> Option<usize> {
expression
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| {
cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::Identifier
})
.last()
.map(|token| usize::from(token.text_range().start()))
}
fn the_last_identifier_of(expression: &cpp_parser::CppSyntaxNode) -> Option<String> {
expression
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| {
cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::Identifier
})
.last()
.map(|token| token.text().to_string())
}
fn kind(node: &cpp_parser::CppSyntaxNode) -> CppSyntaxKind {
CppSyntaxKind::from(node.kind())
}