#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Trait {
Integral,
FloatingPoint,
Arithmetic,
Pointer,
Void,
Signed,
Unsigned,
Reference,
Const,
Volatile,
Array,
Function,
}
impl Trait {
fn named(name: &str) -> Option<Trait> {
Some(match name {
"is_integral" => Trait::Integral,
"is_floating_point" => Trait::FloatingPoint,
"is_arithmetic" => Trait::Arithmetic,
"is_pointer" => Trait::Pointer,
"is_void" => Trait::Void,
"is_signed" => Trait::Signed,
"is_unsigned" => Trait::Unsigned,
"is_reference" => Trait::Reference,
"is_const" => Trait::Const,
"is_volatile" => Trait::Volatile,
"is_array" => Trait::Array,
"is_function" => Trait::Function,
_ => return None,
})
}
fn of(self, spelling: &str) -> Option<bool> {
let spelling = spelling.trim();
let reference = spelling.ends_with('&');
let without_reference = spelling.trim_end_matches('&').trim();
let topmost = without_reference;
let qualified_const = (topmost.starts_with("const ") && !topmost.contains('*'))
|| topmost.ends_with(" const");
let qualified_volatile = (topmost.starts_with("volatile ") && !topmost.contains('*'))
|| topmost.ends_with(" volatile");
let mut bare = without_reference;
loop {
if let Some(rest) = bare.strip_prefix("const ") {
bare = rest.trim();
continue;
}
if let Some(rest) = bare.strip_prefix("volatile ") {
bare = rest.trim();
continue;
}
break;
}
let mut pointers_start = bare;
while let Some(rest) = pointers_start.strip_suffix('*') {
pointers_start = rest.trim();
}
let pointers = bare.ends_with('*');
let scalars = pointers_start.trim();
let array = scalars.contains('[');
let function = !array && scalars.contains('(');
let integral = matches!(
scalars,
"char"
| "signed char"
| "unsigned char"
| "short"
| "unsigned short"
| "int"
| "unsigned int"
| "unsigned"
| "long"
| "unsigned long"
| "long long"
| "unsigned long long"
| "bool"
| "wchar_t"
| "char8_t"
| "char16_t"
| "char32_t"
| "size_t"
| "ptrdiff_t"
| "std::size_t"
);
let floating = matches!(scalars, "float" | "double" | "long double");
let signed =
!scalars.starts_with("unsigned") && !matches!(scalars, "bool" | "unsigned") && integral;
let a_parameter_by_convention = scalars.len() == 1
&& scalars
.chars()
.all(|character| character.is_ascii_uppercase());
let unknown =
a_parameter_by_convention || scalars.starts_with("decltype") || scalars == "auto";
match self {
Trait::Reference => return Some(reference),
Trait::Const => {
if unknown {
return None;
}
return Some(qualified_const);
}
Trait::Volatile => {
if unknown {
return None;
}
return Some(qualified_volatile);
}
Trait::Array => {
if unknown {
return None;
}
return Some(array);
}
Trait::Function => {
if unknown {
return None;
}
return Some(function);
}
_ => {}
}
if unknown {
return None;
}
Some(match self {
Trait::Integral => integral && !pointers && !reference,
Trait::FloatingPoint => floating && !pointers && !reference,
Trait::Arithmetic => (integral || floating) && !pointers && !reference,
Trait::Pointer => pointers && !reference,
Trait::Void => scalars == "void" && !pointers && !reference,
Trait::Signed => signed,
Trait::Unsigned => integral && !signed,
Trait::Reference | Trait::Const | Trait::Volatile | Trait::Array | Trait::Function => {
unreachable!("answered before the scalar")
}
})
}
}
pub fn satisfies(condition: &str, bindings: &[(String, String)]) -> Option<bool> {
let condition = condition.trim();
if condition.is_empty() {
return None;
}
for operator in ["||", "&&"] {
let parts = top_level_split(condition, operator);
if parts.len() > 1 {
let mut decided = Vec::with_capacity(parts.len());
for part in parts {
decided.push(satisfies(&part, bindings)?);
}
return Some(if operator == "||" {
decided.iter().any(|one| *one)
} else {
decided.iter().all(|one| *one)
});
}
}
if let Some(rest) = condition.strip_prefix('!') {
return Some(!satisfies(rest, bindings)?);
}
if condition == "true" {
return Some(true);
}
if condition == "false" {
return Some(false);
}
if let Some(arguments) = a_trait_call_with_name(condition, "is_same") {
let mut parts = top_level_split(arguments, ",").into_iter();
let left = substitute(&parts.next()?, bindings);
let right = substitute(&parts.next()?, bindings);
if left.contains('<') || right.contains('<') {
return None;
}
return Some(left.trim() == right.trim());
}
if let Some(arguments) = a_trait_call_with_name(condition, "is_same") {
let mut parts = top_level_split(arguments, ",").into_iter();
let left = substitute(&parts.next()?, bindings);
let right = substitute(&parts.next()?, bindings);
if left.contains('<') || right.contains('<') {
return None;
}
return Some(left.trim() == right.trim());
}
let trait_call = a_trait_call(condition)?;
let argument = substitute(trait_call.argument, bindings);
if argument.contains('<') || argument.is_empty() {
return None;
}
Trait::named(&trait_call.name)?.of(&argument)
}
pub fn the_condition_of(declaration: &str) -> Option<&str> {
the_enable_if_argument(declaration)
}
fn the_enable_if_argument(declaration: &str) -> Option<&str> {
let at = declaration.find("enable_if")?;
let after = &declaration[at + "enable_if".len()..];
let open = after.find('<')?;
let mut depth = 0isize;
for (index, character) in after[open..].char_indices() {
match character {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
let inside = &after[open + 1..open + index];
return Some(inside.split(',').next().unwrap_or_default().trim());
}
}
_ => {}
}
}
None
}
pub fn a_requires_clause(clause: &str) -> Option<&str> {
let text = clause.trim_start();
let rest = text.strip_prefix("requires")?.trim_start();
if rest.starts_with('{') {
return None;
}
(!rest.is_empty()).then_some(rest)
}
fn a_trait_call_with_name<'a>(condition: &'a str, wanted: &str) -> Option<&'a str> {
let call = a_trait_call(condition)?;
(call.name == wanted).then_some(call.argument)
}
struct TraitCall<'a> {
name: String,
argument: &'a str,
}
fn a_trait_call(condition: &str) -> Option<TraitCall<'_>> {
let condition = condition.trim();
let condition = condition.strip_suffix("::value").unwrap_or(condition);
let condition = condition.strip_suffix("{}").unwrap_or(condition);
let condition = condition.strip_suffix("()").unwrap_or(condition);
let condition = condition.trim();
let open = condition.find('<')?;
let name = condition[..open].trim();
let name = name.strip_suffix("_v").unwrap_or(name);
let name = name.rsplit("::").next().unwrap_or(name).trim();
let close = condition.rfind('>')?;
Some(TraitCall {
name: name.to_string(),
argument: condition[open + 1..close].trim(),
})
}
fn substitute(spelling: &str, bindings: &[(String, String)]) -> String {
let mut out = String::with_capacity(spelling.len());
let mut at = 0usize;
let characters: Vec<(usize, char)> = spelling.char_indices().collect();
while at < characters.len() {
let (start, character) = characters[at];
if !character.is_alphanumeric() && character != '_' {
out.push(character);
at += 1;
continue;
}
let mut end = at;
while end < characters.len()
&& (characters[end].1.is_alphanumeric() || characters[end].1 == '_')
{
end += 1;
}
let word = &spelling[start
..characters
.get(end)
.map_or(spelling.len(), |(offset, _)| *offset)];
match bindings.iter().find(|(parameter, _)| parameter == word) {
Some((_, concrete)) => out.push_str(concrete),
None => out.push_str(word),
}
at = end;
}
out
}
fn top_level_split(text: &str, operator: &str) -> Vec<String> {
let mut parts = Vec::new();
let mut depth = 0isize;
let mut start = 0usize;
let bytes = text.as_bytes();
let mut at = 0usize;
while at < bytes.len() {
match bytes[at] as char {
'<' | '(' => depth += 1,
'>' | ')' => depth -= 1,
_ => {}
}
if depth == 0 && text[at..].starts_with(operator) {
parts.push(text[start..at].trim().to_string());
at += operator.len();
start = at;
continue;
}
at += 1;
}
parts.push(text[start..].trim().to_string());
parts
}
pub fn a_concept_name(declaration: &str) -> Option<String> {
if let Some(at) = declaration.find("requires") {
let after = declaration[at + "requires".len()..].trim_start();
if let Some(open) = after.find('<') {
let name = after[..open].trim();
if is_a_name(name) {
return Some(name.to_string());
}
}
}
let at = declaration.find("template")?;
let after = &declaration[at + "template".len()..];
let open = after.find('<')?;
let mut depth = 0isize;
let mut close = None;
for (index, character) in after[open..].char_indices() {
match character {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
close = Some(open + index);
break;
}
}
_ => {}
}
}
let inside = &after[open + 1..close?];
for parameter in inside.split(',') {
let words: Vec<&str> = parameter.split_whitespace().collect();
let [first, second, ..] = words.as_slice() else {
continue;
};
if matches!(*first, "typename" | "class" | "auto" | "template")
|| first.contains('=')
|| !is_a_name(first)
|| !is_a_name(second)
{
continue;
}
return Some((*first).to_string());
}
None
}
fn is_a_name(word: &str) -> bool {
!word.is_empty()
&& word
.chars()
.next()
.is_some_and(|first| first.is_alphabetic() || first == '_')
&& word
.chars()
.all(|character| character.is_alphanumeric() || character == '_')
}
pub fn satisfies_with(
condition: &str,
bindings: &[(String, String)],
expand: &mut dyn FnMut(&str) -> Option<(String, String)>,
) -> Option<bool> {
satisfies_inside(condition, bindings, expand, 0)
}
const MAX_CONCEPT_DEPTH: usize = 8;
fn satisfies_inside(
condition: &str,
bindings: &[(String, String)],
expand: &mut dyn FnMut(&str) -> Option<(String, String)>,
depth: usize,
) -> Option<bool> {
let condition = condition.trim();
if condition.is_empty() {
return None;
}
for operator in ["||", "&&"] {
let parts = top_level_split(condition, operator);
if parts.len() > 1 {
let mut decided = Vec::with_capacity(parts.len());
for part in parts {
let verdict = satisfies_inside(&part, bindings, expand, depth);
decided.push(verdict?);
}
return Some(if operator == "||" {
decided.iter().any(|one| *one)
} else {
decided.iter().all(|one| *one)
});
}
}
if let Some(rest) = condition.strip_prefix('!') {
return Some(!satisfies_inside(rest, bindings, expand, depth)?);
}
if condition == "true" {
return Some(true);
}
if condition == "false" {
return Some(false);
}
if let Some(arguments) = a_trait_call_with_name(condition, "is_same") {
let mut parts = top_level_split(arguments, ",").into_iter();
let left = substitute(&parts.next()?, bindings);
let right = substitute(&parts.next()?, bindings);
if left.contains('<') || right.contains('<') {
return None;
}
return Some(left.trim() == right.trim());
}
let trait_call = a_trait_call(condition)?;
let argument = substitute(trait_call.argument, bindings);
if argument.contains('<') || argument.is_empty() {
return None;
}
if let Some(trait_) = Trait::named(&trait_call.name) {
return trait_.of(&argument);
}
if depth >= MAX_CONCEPT_DEPTH {
return None;
}
let (parameter, body) = match expand(&trait_call.name) {
Some(found) => found,
None => {
return None;
}
};
let substituted = substitute(&body, &[(parameter, argument)]);
satisfies_inside(&substituted, bindings, expand, depth + 1)
}