use crate::{
Fields, Path, Pun, Root, Rules, Steps, Variants,
analysis::Marks,
layout::{self, Enum, Kind, Machine, Op, Rule, Shape, load, op_at, walk_limit},
ptr,
steps::{InRule, ONE, Ops, TWO, WALK},
};
pub trait Checks {
const MARKS: Marks;
}
pub struct All;
impl Checks for All {
const MARKS: Marks = Marks::ALL;
}
pub const unsafe fn validate<C: Checks, P: Path, T: ?Sized + Pun>(ptr: *const T) -> bool {
if const { !C::MARKS.any(P::LEAF, T::LAYOUT.leaves) } {
return true;
}
unsafe {
match const { T::LAYOUT.shape() } {
Shape::Scalar(spec) => spec.matches(ptr.cast()),
Shape::Array(len) => validate_elems::<C, P, T::Elem>(ptr.cast(), len),
Shape::Slice => validate_elems::<C, P, T::Elem>(ptr.cast(), ptr::metadata(ptr)),
Shape::Struct => {
validate_fields::<C, P, T, T::Fields>(ptr)
&& (const { !rules_marked::<C, P, T>() } || check_rules(ptr))
}
Shape::Pattern(dfa) => dfa.matches(ptr.cast(), ptr::metadata(ptr)),
Shape::Enum(layout) if layout.union => validate_union::<T, T::Variants>(ptr),
Shape::Enum(layout) => validate_enum::<T>(ptr, layout),
Shape::Pointer(pointer) => {
pointer.nullable || load(ptr.cast(), pointer.width, pointer.endian) != 0
}
}
}
}
#[inline(always)]
const unsafe fn validate_enum<T: ?Sized + Pun>(ptr: *const T, layout: &Enum) -> bool {
let Kind::Scalar(spec) = layout.tag.layout.kind else { panic!() };
unsafe {
let tag = load(ptr.cast::<u8>().add(layout.tag.offset), spec.size, spec.endian);
validate_variants::<T, T::Variants>(ptr, tag)
}
}
const unsafe fn validate_variants<T: ?Sized + Pun, V: Variants>(ptr: *const T, tag: u128) -> bool {
let Some(expected) = (const { V::TAG }) else { return false };
let this = match const { V::RANGES } {
None => tag == expected,
Some(ranges) => layout::contains(ranges, tag),
};
unsafe {
if this {
validate_fields::<All, Root, T, V::Fields>(ptr)
} else {
validate_variants::<T, V::Next>(ptr, tag)
}
}
}
const unsafe fn validate_union<T: ?Sized + Pun, V: Variants>(ptr: *const T) -> bool {
if const { V::TAG.is_none() } {
return false;
}
unsafe { validate_fields::<All, Root, T, V::Fields>(ptr) || validate_union::<T, V::Next>(ptr) }
}
const unsafe fn validate_elems<C: Checks, P: Path, T: Pun>(ptr: *const T, len: usize) -> bool {
let mut i = 0;
let block = const { T::LAYOUT.block() };
if block > 1 {
while len - i >= block {
let (mut valid, mut j) = (true, 0);
while j < block {
valid &= unsafe { validate::<C, P, T>(ptr.add(i + j)) };
j += 1;
}
if !valid {
return false;
}
i += block;
}
}
while i < len {
if !unsafe { validate::<C, P, T>(ptr.add(i)) } {
return false;
}
i += 1;
}
true
}
const unsafe fn validate_fields<C: Checks, P: Path, T: ?Sized + Pun, F: Fields>(
ptr: *const T,
) -> bool {
let Some(field) = (const { F::FIELD }) else { return true };
const {
let leaf = match F::FIELD {
Some(field) => P::LEAF + field.leaf(),
None => P::LEAF,
};
assert!(<F::Path<P> as Path>::LEAF == leaf, "not where the field is");
};
unsafe {
let valid = match field.restriction() {
Some(spec) => {
(const { !C::MARKS.any(<F::Path<P> as Path>::LEAF, 1) })
|| spec.matches(ptr.cast::<u8>().add(field.offset()))
}
None => validate::<C, F::Path<P>, F::Type>(ptr::field::<T, F::Type>(ptr, field.offset())),
};
valid && validate_fields::<C, P, T, F::Next>(ptr)
}
}
const fn rules_marked<C: Checks, P: Path, T: ?Sized + Pun>() -> bool {
!T::LAYOUT.rules().is_empty() && C::MARKS.any(P::LEAF + T::LAYOUT.leaves - 1, 1)
}
#[inline(always)]
pub const unsafe fn check_rules<T: ?Sized + Pun>(ptr: *const T) -> bool {
const { assert!(listed::<T, T::Rules>(0), "not the rules of the struct") };
let (len, tail, size) = tail_of(ptr);
unsafe { check_listed::<T, T::Rules>(ptr.cast(), size, tail, len, 0) }
}
#[cfg_attr(not(debug_assertions), inline(always))]
const unsafe fn check_listed<T: ?Sized + Pun, L: Rules>(
base: *const u8,
size: usize,
tail: usize,
len: usize,
regions: usize,
) -> bool {
if const { L::RULE == usize::MAX } {
return true;
}
let Some(value) = (unsafe { eval::<InRule<T, L>, L::Expr>(base, size) }) else { return false };
let regions = match const { T::LAYOUT.rule(L::RULE) } {
Some(Rule::Size(_)) if value == size as u128 => regions,
Some(Rule::Len(_)) if value == len as u128 => regions,
Some(Rule::Assert(_)) if value != 0 => regions,
Some(Rule::Region(_)) if value <= (tail - regions) as u128 => regions + value as usize,
_ => return false,
};
unsafe { check_listed::<T, L::Next>(base, size, tail, len, regions) }
}
const fn listed<T: ?Sized + Pun, L: Rules>(from: usize) -> bool {
let rules = T::LAYOUT.rules();
let mut i = from;
while i < rules.len() && rules[i].ops().is_none() {
i += 1;
}
if L::RULE == usize::MAX {
return i >= rules.len();
}
L::RULE == i && covers::<InRule<T, L>, L::Expr>() && listed::<T, L::Next>(i + 1)
}
const fn covers<X: Ops, S: Steps>() -> bool {
!X::OPS.is_empty() && S::FIRST == 0 && S::END == X::OPS.len()
}
#[inline(always)]
pub const unsafe fn length<T: ?Sized + Pun>(base: *const u8, n: usize) -> Option<u128> {
let (own, offset) = const {
let rule = T::LAYOUT.length_rule();
let own = match T::LAYOUT.length_rule() {
Some(rule) => rule.base == 0 && sizing::<T, T::Rules>() != usize::MAX,
None => false,
};
let fields = T::LAYOUT.struct_fields();
let offset = if fields.is_empty() { 0 } else { fields[fields.len() - 1].offset };
if let (Some(rule), false) = (rule, own) {
let last = <<T::Fields as Fields>::Last as Fields>::FIELD;
let inner = <<<T::Fields as Fields>::Last as Fields>::Type as Pun>::LAYOUT.length_rule();
assert!(
matches!(last, Some(field) if field.offset() == offset)
&& matches!(inner, Some(inner) if inner.base + offset == rule.base
&& inner.elements == rule.elements
&& layout::same_ops(inner.ops, rule.ops)),
"not the last field of the struct"
);
}
(own, offset)
};
if own {
return unsafe { length_listed::<T, T::Rules>(base, n) };
}
unsafe { length::<<<T::Fields as Fields>::Last as Fields>::Type>(base.add(offset), n - offset) }
}
const fn sizing<T: ?Sized + Pun, L: Rules>() -> usize {
match T::LAYOUT.rule(L::RULE) {
_ if L::RULE == usize::MAX => usize::MAX,
Some(Rule::Size(_) | Rule::Len(_)) => L::RULE,
_ => sizing::<T, L::Next>(),
}
}
#[inline(always)]
const unsafe fn length_listed<T: ?Sized + Pun, L: Rules>(
base: *const u8,
n: usize,
) -> Option<u128> {
if const { L::RULE == usize::MAX } {
return None;
}
if const { matches!(T::LAYOUT.rule(L::RULE), Some(Rule::Size(_) | Rule::Len(_))) } {
const { assert!(listed::<T, T::Rules>(0), "not the rules of the struct") };
return unsafe { eval::<InRule<T, L>, L::Expr>(base, n) };
}
unsafe { length_listed::<T, L::Next>(base, n) }
}
#[inline(always)]
pub const unsafe fn region_at<'a, T: ?Sized + Pun, L: Rules>(
base: *const u8,
size: usize,
(head, tail): (usize, usize),
index: usize,
(start, count): (usize, usize),
) -> &'a [u8] {
const { assert!(listed::<T, T::Rules>(0), "not the rules of the struct") };
let rest = tail - start;
if const { L::RULE == usize::MAX } {
assert!(count == index && T::LAYOUT.has_last_region(), "no such region");
return unsafe { core::slice::from_raw_parts(base.add(head + start), rest) };
}
if const { !matches!(T::LAYOUT.rule(L::RULE), Some(Rule::Region(_))) } {
return unsafe { region_at::<T, L::Next>(base, size, (head, tail), index, (start, count)) };
}
let region = match unsafe { eval::<InRule<T, L>, L::Expr>(base, size) } {
Some(region) if region <= rest as u128 => region as usize,
_ => rest,
};
if count == index {
return unsafe { core::slice::from_raw_parts(base.add(head + start), region) };
}
unsafe { region_at::<T, L::Next>(base, size, (head, tail), index, (start + region, count + 1)) }
}
#[inline(always)]
const unsafe fn eval<X: Ops, S: Steps>(base: *const u8, size: usize) -> Option<u128> {
let mut machine = Machine::NEW;
if unsafe { steps::<X, S>(&mut machine, base, size) } { Some(machine.result()) } else { None }
}
#[cfg_attr(not(debug_assertions), inline(always))]
const unsafe fn steps<X: Ops, S: Steps>(
machine: &mut Machine,
base: *const u8,
size: usize,
) -> bool {
const {
assert!(
S::KIND != ONE || matches!(op_at(X::OPS, S::AT), Some(op) if !matches!(op, Op::Walk { .. })),
"not the operations of the expression"
);
};
unsafe {
match const { S::KIND } {
ONE => match const { op_at(X::OPS, S::AT) } {
Some(op) => machine.apply(op, S::AT, base, size),
None => false,
},
TWO => {
if !steps::<X, S::A>(machine, base, size) {
return false;
}
steps::<X, S::B>(machine, base, size)
}
WALK => walk::<X, S>(machine, base, size),
_ => true,
}
}
}
#[cfg_attr(not(debug_assertions), inline(always))]
const unsafe fn walk<X: Ops, W: Steps>(
machine: &mut Machine,
base: *const u8,
size: usize,
) -> bool {
const {
assert!(
W::KIND != WALK
|| matches!(op_at(X::OPS, W::AT), Some(Op::Walk { .. }))
&& covers::<W::InCond<X>, W::Cond>()
&& covers::<W::InThen<X>, W::Then>(),
"not the operations of the expression"
);
};
let Some(Op::Walk { var, .. }) = (const { op_at(X::OPS, W::AT) }) else {
return false;
};
if !machine.computes(W::AT) {
return true;
}
let mut state = machine.top();
let (mut steps, limit) = (0, walk_limit(size));
let result = loop {
let (mut cond, mut next) = (machine.enter(var, state), machine.enter(var, state));
if !unsafe { self::steps::<W::InCond<X>, W::Cond>(&mut cond, base, size) } {
break None;
}
if cond.result() == 0 {
break Some(state);
}
if steps == limit {
break None;
}
steps += 1;
if !unsafe { self::steps::<W::InThen<X>, W::Then>(&mut next, base, size) } {
break None;
}
state = next.result();
};
machine.replace(result)
}
#[inline(always)]
pub const fn tail_of<T: ?Sized + Pun>(ptr: *const T) -> (usize, usize, usize) {
let (layout, shape) = const { (T::LAYOUT, T::LAYOUT.tail_shape()) };
if const { T::LAYOUT.is_unsized() } {
let len = ptr::metadata(ptr);
(len, len * layout.stride(), layout.head() + len * layout.stride())
} else {
(shape.len, shape.bytes, layout.size())
}
}