use cpp_parser::{CppAstNode, CppCallExpr};
use super::{Check, CheckContext, DiagnosticCode};
pub struct ConceptNotSatisfied;
impl Check for ConceptNotSatisfied {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::ConceptNotSatisfied];
fn check(context: &mut CheckContext<'_>) {
for call in context.own::<CppCallExpr>().collect::<Vec<_>>() {
let Some(callee) = call.get_callee() else {
continue;
};
let Some(name) = super::spelling_of(callee.syntax()) else {
continue;
};
let Some(constraints) =
constraints_of_a_declaration(context, &name).map(<[String]>::to_vec)
else {
continue;
};
for (at, argument) in call.get_args().iter().enumerate() {
let Some(concept) = constraints
.get(at)
.filter(|written| !written.is_empty())
.and_then(|written| Concept::from_constraint(written))
else {
continue;
};
let crate::Known::Yes((passed, _)) = context.type_of(argument.syntax()) else {
continue;
};
if concept.is_satisfied_by(&passed, context) != Some(false) {
continue;
}
context.add(
DiagnosticCode::ConceptNotSatisfied,
cpp_parser::source_range(argument.syntax().text_range()),
name.clone(),
t!(
"`%{passed}` does not satisfy `%{concept}`, which constrains the parameter this argument is \
passed for",
passed = passed.to_string(),
concept = concept.spelling()
),
);
}
}
}
}
fn constraints_of_a_declaration<'a>(
context: &'a CheckContext<'_>,
name: &str,
) -> Option<&'a [String]> {
let mut own: Option<&[String]> = None;
let mut own_declarations = 0;
for fact in &context.summary.declarations {
if fact.name != name || fact.parameter_list.is_none() {
continue;
}
own_declarations += 1;
own = Some(&fact.constraints);
}
match own_declarations {
0 => {}
1 => return own,
_ => return None,
}
let index = context.model.index();
let declared = index.files_declaring(name, context.path);
let mut elsewhere: Option<&[String]> = None;
let mut elsewhere_declarations = 0;
for found in &declared {
if found.fact.parameter_list.is_none() {
continue;
}
elsewhere_declarations += 1;
elsewhere = Some(&found.fact.constraints);
}
match elsewhere_declarations {
1 => elsewhere,
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Concept {
Integral,
FloatingPoint,
SameAs(String),
ConvertibleTo(String),
DerivedFrom(String),
NeedsAnObjectType(&'static str),
}
impl Concept {
fn from_constraint(constraint: &str) -> Option<Concept> {
let unqualified = constraint.rsplit("::").next().unwrap_or(constraint);
let (name, arguments) = match unqualified.split_once('<') {
Some((name, rest)) => (name.trim(), Some(rest.trim_end_matches('>'))),
None => (unqualified.trim(), None),
};
match name {
"integral" | "signed_integral" | "unsigned_integral" => Some(Concept::Integral),
"floating_point" => Some(Concept::FloatingPoint),
"same_as" => {
let arguments = split_at_top_level_commas(arguments?);
Some(Concept::SameAs(arguments.first()?.trim().to_string()))
}
"convertible_to" => {
let arguments = split_at_top_level_commas(arguments?);
Some(Concept::ConvertibleTo(
arguments.first()?.trim().to_string(),
))
}
"derived_from" => {
let arguments = split_at_top_level_commas(arguments?);
Some(Concept::DerivedFrom(arguments.first()?.trim().to_string()))
}
"default_initializable"
| "move_constructible"
| "copy_constructible"
| "movable"
| "copyable"
| "semiregular"
| "regular" => Some(Concept::NeedsAnObjectType(match name {
"default_initializable" => "std::default_initializable",
"move_constructible" => "std::move_constructible",
"copy_constructible" => "std::copy_constructible",
"movable" => "std::movable",
"copyable" => "std::copyable",
"semiregular" => "std::semiregular",
_ => "std::regular",
})),
_ => None,
}
}
fn spelling(&self) -> String {
match self {
Concept::Integral => "std::integral".to_string(),
Concept::FloatingPoint => "std::floating_point".to_string(),
Concept::SameAs(other) => format!("std::same_as<{other}>"),
Concept::ConvertibleTo(other) => format!("std::convertible_to<{other}>"),
Concept::DerivedFrom(other) => format!("std::derived_from<{other}>"),
Concept::NeedsAnObjectType(spelling) => spelling.to_string(),
}
}
fn is_satisfied_by(
&self,
passed: &crate::sema::types::Type,
context: &CheckContext<'_>,
) -> Option<bool> {
match self {
Concept::Integral => Some(is_an_integer(passed)),
Concept::FloatingPoint => Some(is_a_floating_point(passed)),
Concept::SameAs(declared) => {
let declared = crate::sema::types::parse_type_spelling(declared);
match passed.convertible_to(&declared) {
crate::Known::No => Some(false),
crate::Known::Yes(()) => Some(passed.to_string() == declared.to_string()),
crate::Known::Unknown(_) => None,
}
}
Concept::DerivedFrom(base) => derives_from(context, passed, base),
Concept::NeedsAnObjectType(_) => {
Some(!passed.to_string().contains('&'))
}
Concept::ConvertibleTo(target) => {
let target = crate::sema::types::parse_type_spelling(target);
match passed.convertible_to(&target) {
crate::Known::No => Some(false),
crate::Known::Yes(()) => Some(true),
crate::Known::Unknown(_) => Some(!matches!(
crate::sema::convert::conversion(passed, &target.to_string(), |_| None),
crate::sema::convert::Conversion::Refused
)),
}
}
}
}
}
fn plain_type_spelling(passed: &crate::sema::types::Type) -> Option<String> {
match passed {
crate::sema::types::Type::Builtin { spelling } => Some(spelling.clone()),
crate::sema::types::Type::Named { name, arguments } if arguments.is_empty() => {
Some(name.clone())
}
_ => None,
}
}
fn is_an_integer(passed: &crate::sema::types::Type) -> bool {
let Some(spelling) = plain_type_spelling(passed) else {
return false;
};
matches!(
spelling.as_str(),
"bool"
| "char"
| "signed char"
| "unsigned char"
| "wchar_t"
| "char8_t"
| "char16_t"
| "char32_t"
| "short"
| "short int"
| "signed short"
| "signed short int"
| "unsigned short"
| "unsigned short int"
| "int"
| "signed"
| "signed int"
| "unsigned"
| "unsigned int"
| "long"
| "long int"
| "signed long"
| "signed long int"
| "unsigned long"
| "unsigned long int"
| "long long"
| "long long int"
| "signed long long"
| "signed long long int"
| "unsigned long long"
| "unsigned long long int"
| "size_t"
| "ptrdiff_t"
| "intptr_t"
| "uintptr_t"
| "int8_t"
| "int16_t"
| "int32_t"
| "int64_t"
| "uint8_t"
| "uint16_t"
| "uint32_t"
| "uint64_t"
)
}
fn is_a_floating_point(passed: &crate::sema::types::Type) -> bool {
let Some(spelling) = plain_type_spelling(passed) else {
return false;
};
matches!(spelling.as_str(), "float" | "double" | "long double")
}
fn split_at_top_level_commas(text: &str) -> Vec<String> {
let mut parts = Vec::new();
let mut depth = 0isize;
let mut start = 0usize;
for (at, character) in text.char_indices() {
match character {
'<' | '(' | '[' => depth += 1,
'>' | ')' | ']' => depth -= 1,
',' if depth == 0 => {
parts.push(text[start..at].to_string());
start = at + 1;
}
_ => {}
}
}
parts.push(text[start..].to_string());
parts
}
fn derives_from(
context: &CheckContext<'_>,
derived: &crate::sema::types::Type,
base: &str,
) -> Option<bool> {
use crate::sema::types::Type;
let Type::Named { name, arguments } = derived else {
return Some(false);
};
if !arguments.is_empty() {
return None;
}
let index = context.model.index();
let base = base.trim();
let base = base.rsplit("::").next().unwrap_or(base);
let mut waiting = vec![name.clone()];
let mut seen = std::collections::HashSet::new();
let mut answered = true;
while let Some(class) = waiting.pop() {
if !seen.insert(class.clone()) {
continue;
}
if class.rsplit("::").next().unwrap_or(&class) == base {
return Some(true);
}
let declared = index.files_declaring(&class, context.path);
let mut found = None;
let mut declarations = 0;
for visible in &declared {
if visible.fact.kind != crate::DeclKind::Type {
continue;
}
declarations += 1;
found = Some(&visible.fact);
}
let (true, 1) = (answered, declarations) else {
answered = false;
continue;
};
let Some(fact) = found else {
answered = false;
continue;
};
for written in &fact.bases {
let written = written.trim();
let name = written.split_whitespace().next_back().unwrap_or(written);
waiting.push(name.trim_end_matches('<').to_string());
}
}
answered.then_some(false)
}