use super::*;
pub(crate) fn substituted_at_the_use(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
expression: &cpp_parser::CppSyntaxNode,
named: &NamedDeclaration,
type_of: Type,
) -> Type {
let arguments = written_template_arguments(expression);
if arguments.is_empty() {
return type_of;
}
let (names, _) = named.parameters_of(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
);
if names.is_empty() {
return type_of;
}
let written_defaults = named.parameter_defaults_of(index, root);
let written_arguments: Vec<Type> = arguments.clone();
let mut defaults: Vec<Type> = Vec::with_capacity(written_defaults.len());
for default in &written_defaults {
if default.trim().is_empty() {
defaults.push(Type::builtin(""));
continue;
}
let parsed = parse_type_spelling(default);
defaults.push(
parsed.substituted(&crate::sema::types::TypeSubstitutions::new(
&names,
&written_arguments,
)),
);
}
let substitutions =
crate::sema::types::TypeSubstitutions::with_defaults(&names, &written_arguments, &defaults);
type_of.substituted(&substitutions)
}
pub(crate) fn folded_for_matching(argument: &str) -> String {
crate::sema::builtins::folded(argument)
}
pub(crate) fn the_alias_behind(
index: &ProjectIndex,
declaring: &Path,
written: &str,
) -> Option<(String, String)> {
let (head, rest) = written.split_once('<')?;
let inside = rest.trim_end().strip_suffix('>')?;
let Known::Yes(found) = index.definition(head.trim(), declaring) else {
return None;
};
if found.fact.kind != crate::DeclKind::Type {
return None;
}
let target = found.fact.type_of.as_deref()?;
let arguments = crate::sema::builtins::split_arguments(inside);
let substituted =
crate::sema::types::substituted_spelling(target, found.fact.parameters(), &arguments);
let substituted = substituted
.trim()
.trim_start_matches("typename ")
.trim()
.trim_start_matches("class ")
.trim();
let (named, member) = substituted.rsplit_once("::")?;
Some((named.trim().to_string(), member.trim().to_string()))
}
pub fn substituted_members(
index: &ProjectIndex,
from: &Path,
class: &str,
listed: Known<MemberList>,
) -> Known<MemberList> {
let Known::Yes(mut list) = listed else {
return listed;
};
let Some((base, arguments)) = split_template_arguments(class).or_else(|| {
let target = index
.files_declaring(class, from)
.into_iter()
.find(|declared| {
declared.fact.kind == crate::DeclKind::Type && declared.fact.type_of.is_some()
})
.and_then(|declared| declared.fact.type_of.clone())?;
split_template_arguments(&target)
}) else {
return Known::Yes(list);
};
let Some(declared) = index
.files_declaring(&base, from)
.into_iter()
.find(|declared| declared.fact.kind == crate::DeclKind::Type)
else {
return Known::Yes(list);
};
let names = declared.fact.parameters().to_vec();
if names.is_empty() {
return Known::Yes(list);
}
let defaults = index.template_parameter_defaults_for(&base, from, &arguments);
if names.is_empty() {
return Known::Yes(list);
}
let mut alias_names: Vec<String> = Vec::new();
let mut alias_targets: Vec<String> = Vec::new();
for member in list
.members
.iter()
.filter(|member| member.depth == 0 && member.fact.kind == crate::DeclKind::Type)
{
let Some(target) = member.fact.type_of.clone() else {
continue;
};
if target == member.fact.name {
continue;
}
alias_names.push(member.fact.name.to_string());
alias_targets.push(target.to_string());
}
let declares_an_alias = |member: &ProjectMember| {
member.fact.kind == crate::DeclKind::Type
&& alias_names
.iter()
.any(|name| name == member.fact.name.as_str())
};
let through_the_aliases = |spelling: &str| -> String {
let mut spelling = spelling.to_string();
for _ in 0..MAX_ALIAS_PASSES {
if !alias_names
.iter()
.any(|name| spelling.contains(name.as_str()))
{
break;
}
let next =
crate::sema::types::substituted_spelling(&spelling, &alias_names, &alias_targets);
if next == spelling {
break;
}
spelling = next;
}
spelling
};
for member in list
.members
.iter_mut()
.filter(|member| !declares_an_alias(member))
{
if !alias_names.is_empty() {
if let Some(spelling) = member.fact.detail_mut().parameter_list.as_mut() {
*spelling = through_the_aliases(spelling);
}
if let Some(spelling) = member.fact.returns.as_mut() {
*spelling = through_the_aliases(spelling).into();
}
}
if !alias_names.is_empty()
&& let Some(spelling) = member.fact.type_of.as_mut()
{
*spelling = through_the_aliases(spelling).into();
}
}
for member in &mut list.members {
if let Some(spelling) = member.fact.detail_mut().parameter_list.as_mut() {
*spelling = crate::sema::types::substituted_spelling_with_defaults(
spelling, &names, &defaults, &arguments,
);
}
if let Some(spelling) = member.fact.returns.as_mut() {
*spelling = crate::sema::types::substituted_spelling_with_defaults(
spelling, &names, &defaults, &arguments,
)
.into();
}
if let Some(spelling) = member.fact.type_of.as_mut() {
*spelling = crate::sema::types::substituted_spelling_with_defaults(
spelling, &names, &defaults, &arguments,
)
.into();
}
}
Known::Yes(list)
}
pub(crate) fn split_template_arguments(spelling: &str) -> Option<(String, Vec<String>)> {
let spelling = spelling.trim();
let open = spelling.find('<')?;
let close = spelling.rfind('>')?;
if close < open || close + 1 != spelling.len() {
return None;
}
let base = spelling[..open].trim().to_string();
let mut arguments: Vec<String> = Vec::new();
let mut depth = 0i32;
let mut current = String::new();
for character in spelling[open + 1..close].chars() {
match character {
'<' | '(' | '[' => depth += 1,
'>' | ')' | ']' => depth -= 1,
',' if depth == 0 => {
arguments.push(current.trim().to_string());
current.clear();
continue;
}
_ => {}
}
current.push(character);
}
if !current.trim().is_empty() {
arguments.push(current.trim().to_string());
}
Some((base, arguments))
}
pub(crate) fn the_class_a_definition_belongs_to(
root: &cpp_parser::CppSyntaxNode,
offset: usize,
) -> Option<String> {
use cpp_parser::CppAstNode;
for declaration in root.descendants() {
let range = declaration.text_range();
if usize::from(range.start()) > offset || offset >= usize::from(range.end()) {
continue;
}
let Some(declaration) = cpp_parser::CppDeclaration::cast(declaration.clone()) else {
continue;
};
let Some((qualifier, _)) =
crate::sema::scopes::the_qualified_name_of_a_declaration(declaration.syntax())
else {
continue;
};
let before = qualifier.trim_end();
let start = before
.rfind(|character: char| {
!(character.is_alphanumeric() || matches!(character, '_' | ':'))
})
.map(|boundary| boundary + 1)
.unwrap_or(0);
let class = before[start..].trim();
if !class.is_empty() && !class.contains("::") {
return Some(class.to_string());
}
}
None
}
pub(crate) fn without_the_namespace(class: &str) -> String {
let mut depth = 0usize;
let mut boundary = 0usize;
let bytes = class.as_bytes();
let mut index = 0usize;
while index + 1 < bytes.len() {
match bytes[index] {
b'<' => depth += 1,
b'>' => depth = depth.saturating_sub(1),
b':' if depth == 0 && bytes[index + 1] == b':' => boundary = index + 2,
_ => {}
}
index += 1;
}
class[boundary.min(class.len())..].to_string()
}
pub(crate) fn is_a_parameter_name(name: &str) -> bool {
!name.is_empty()
&& !matches!(
name,
"class" | "typename" | "struct" | "union" | "enum" | "concept"
)
&& name
.chars()
.all(|character| character.is_alphanumeric() || character == '_')
}
pub(crate) fn lists_usable_parameter_names(names: &[String]) -> bool {
!names.is_empty()
&& names.iter().any(|name| !name.is_empty())
&& names
.iter()
.all(|name| name.is_empty() || is_a_parameter_name(name))
}
pub(crate) fn an_element_type_through_the_members(
index: &ProjectIndex,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
class: &str,
parameters: &[String],
arguments: &[String],
depth: usize,
) -> Option<String> {
if depth > 3 {
return None;
}
let Known::Yes(members) = members_of(index, scopes, root, path, class) else {
if crate::probes::inference() {
eprintln!("[inference] element_type: no member list for {class}");
}
return None;
};
for name in ["element_type", "value_type"] {
let Some(fact) = members
.members
.iter()
.filter(|member| member.fact.name == name)
.map(|member| &member.fact)
.find(|fact| fact.type_of.is_some())
else {
continue;
};
let Some(written) = fact.type_of.as_deref() else {
continue;
};
let substituted = crate::sema::types::substituted_spelling(written, parameters, arguments);
let target = base_type_name(&substituted).to_string();
if crate::probes::inference() {
eprintln!(
"[inference] element_type: {class}::{name} wrote {written:?} -> {substituted:?} -> {target:?}"
);
}
if !target.is_empty()
&& !parameters.iter().any(|parameter| parameter == &target)
&& target != base_type_name(class)
{
return Some(target);
}
}
for member in &members.members {
if member.fact.kind != crate::DeclKind::Type {
continue;
}
let Some(target) = member.fact.type_of.as_deref() else {
continue;
};
if base_type_name(target) == base_type_name(class) {
continue;
}
let bare_target = without_arguments(target.trim()).to_string();
let qualified = resolved_in_the_enclosing_scopes(index, scopes, path, class, &bare_target);
let qualified = resolve_aliases(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
&qualified,
);
if let Some(found) = an_element_type_through_the_members(
index,
scopes,
root,
path,
&qualified,
parameters,
arguments,
depth + 1,
) {
return Some(found);
}
}
for base in bases_of(index, scopes, root, path, class)
.value()
.unwrap_or_default()
{
let base = resolved_in_the_enclosing_scopes(index, scopes, path, class, base.trim());
let base = resolve_aliases(
&crate::sema::declarations::ShapeTable::new(),
index,
scopes,
root,
path,
&base,
);
if let Some(found) = an_element_type_through_the_members(
index,
scopes,
root,
path,
&base,
parameters,
arguments,
depth + 1,
) {
return Some(found);
}
}
None
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct TableCost {
pub names: crate::index::names::NameIndexCost,
pub edges: usize,
pub edge_bytes: usize,
pub member_list_entries: usize,
pub member_lists: usize,
pub member_list_bytes: usize,
pub guard_entries: usize,
pub guard_bytes: usize,
pub visibility_entries: usize,
pub visibility_bytes: usize,
pub condition_entries: usize,
pub condition_bytes: usize,
pub path_bytes: usize,
}
impl TableCost {
pub fn total(&self) -> usize {
self.names.bytes
+ self.edge_bytes
+ self.member_list_bytes
+ self.guard_bytes
+ self.visibility_bytes
+ self.condition_bytes
+ self.path_bytes
}
}
pub(crate) fn names_define_static_array(callee: &cpp_parser::CppSyntaxNode) -> bool {
let spelled = callee.text().to_string();
let spelled = spelled.trim();
let bare = match spelled.find('<') {
Some(at) => spelled[..at].trim(),
None => spelled,
};
matches!(
bare,
"std::define_static_array" | "::std::define_static_array"
)
}
pub(crate) fn the_return_the_body_gives_back(
memo: &TypeMemo,
index: &ProjectIndex,
declaring: &mut dyn FnMut(&Path) -> Option<crate::FileView>,
scopes: &crate::ScopeTree,
root: &cpp_parser::CppSyntaxNode,
path: &Path,
depth: usize,
candidate: &ProjectDefinition,
) -> Option<String> {
if depth > MAX_TYPE_DEPTH {
return None;
}
if candidate.file != path {
return None;
}
let the_root = root;
let the_scopes = scopes;
let the_path = path;
let in_the_reading = candidate.fact.name_range.start_offset;
let token = cpp_parser::token_at(the_root, in_the_reading)?;
let declaration = token.parent_ancestors().find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::Declaration
})?;
use cpp_parser::CppAstNode;
let body = cpp_parser::CppDeclaration::cast(declaration)?.get_body()?;
let mut agreed: Option<String> = None;
for statement in body
.syntax()
.descendants()
.filter_map(cpp_parser::CppReturnStat::cast)
{
if statement
.syntax()
.ancestors()
.take_while(|ancestor| ancestor != body.syntax())
.any(|ancestor| {
cpp_parser::CppSyntaxKind::from(ancestor.kind())
== cpp_parser::CppSyntaxKind::LambdaExpr
})
{
continue;
}
let Some(expression) = statement.get_expr() else {
match &agreed {
None => agreed = Some("void".to_string()),
Some(previous) if previous == "void" => {}
Some(_) => return None,
}
continue;
};
let Known::Yes((type_of, _)) = type_of_expression_memoed(
memo,
&crate::sema::declarations::ShapeTable::new(),
index,
declaring,
the_scopes,
the_root,
the_path,
expression.syntax(),
depth + 1,
) else {
return None;
};
let written = type_of.to_string();
match &agreed {
None => agreed = Some(written),
Some(previous) if *previous == written => {}
Some(_) => return None,
}
}
agreed
}