use std::collections::BTreeMap;
use proptest::{collection::vec, prelude::*, sample::select};
use typesayer_types::{
FieldDef,
field::{FieldType, FieldValue, ObjectField, OneOfDiscriminator, VariantArm},
signature::Signature,
};
const MAX_DEPTH: u32 = 10;
const MAX_TYPE_NODES: u32 = 1000;
const EXPECTED_BRANCH_SIZE: u32 = 5;
const MAX_COLLECTION_SIZE: usize = 20;
const MAX_LEAF_BUDGET: usize = 1000;
const MAX_STRING_LEN: usize = 100;
#[rustfmt::skip]
const SAFE_ALPHABET: &[char] = &[
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
' ', '.', ',', '!', '?', '-',
];
pub fn arb_safe_string() -> impl Strategy<Value = String> {
vec(select(SAFE_ALPHABET), 0..=MAX_STRING_LEN)
.prop_map(|chars| chars.into_iter().collect::<String>().trim().to_owned())
}
pub fn arb_supported_field_type() -> impl Strategy<Value = FieldType> {
let leaf = prop_oneof![
Just(FieldType::String),
Just(FieldType::Int),
Just(FieldType::Float),
Just(FieldType::Bool),
Just(FieldType::Enum(vec!["a".into(), "b".into(), "c".into()])),
];
leaf.prop_recursive(MAX_DEPTH, MAX_TYPE_NODES, EXPECTED_BRANCH_SIZE, |inner| {
prop_oneof![
inner.clone().prop_map(|t| FieldType::List(Box::new(t))),
inner
.clone()
.prop_filter("non-nested-nullable", |t| !matches!(
t,
FieldType::Nullable(_)
))
.prop_map(|t| FieldType::Nullable(Box::new(t))),
inner.clone().prop_map(|t| FieldType::Map(Box::new(t))),
inner.prop_map(|t| FieldType::Object(vec![ObjectField {
name: "f1".into(),
description: String::new(),
field_type: t,
}])),
]
})
}
pub fn arb_value_for_type(field_type: FieldType) -> BoxedStrategy<FieldValue> {
arb_value_for_type_with_budget(field_type, MAX_LEAF_BUDGET)
}
fn arb_value_for_type_with_budget(
field_type: FieldType,
budget: usize,
) -> BoxedStrategy<FieldValue> {
match field_type {
FieldType::String => arb_safe_string().prop_map(FieldValue::Str).boxed(),
FieldType::Int => any::<i32>()
.prop_map(|i| FieldValue::Int(i64::from(i)))
.boxed(),
FieldType::Float => (-1e9_f64..1e9_f64)
.prop_filter("finite", |f| f.is_finite())
.prop_map(FieldValue::Float)
.boxed(),
FieldType::Bool => any::<bool>().prop_map(FieldValue::Bool).boxed(),
FieldType::Enum(variants) => select(variants).prop_map(FieldValue::Str).boxed(),
FieldType::Nullable(inner) => {
let inner_strategy = arb_value_for_type_with_budget((*inner).clone(), budget);
prop_oneof![Just(FieldValue::Null), inner_strategy]
.prop_filter("non-ambiguous-null", |v| match v {
FieldValue::Str(s) => !s.is_empty() && !s.eq_ignore_ascii_case("null"),
_ => true,
})
.boxed()
}
FieldType::Map(value_type) => {
let cap = budget.min(MAX_COLLECTION_SIZE);
(0..=cap)
.prop_flat_map(move |n| {
let per_elem_budget = budget.checked_div(n).map_or(0, |b| b.max(1));
let value_strategy =
arb_value_for_type_with_budget((*value_type).clone(), per_elem_budget);
let key_strategy =
arb_safe_string().prop_filter("non-empty", |s| !s.is_empty());
vec((key_strategy, value_strategy), n..=n).prop_map(|pairs| {
let map: BTreeMap<String, FieldValue> = pairs.into_iter().collect();
FieldValue::Object(map)
})
})
.boxed()
}
FieldType::Object(fields) => {
let per_field_budget = budget.checked_div(fields.len()).map_or(0, |b| b.max(1));
let field_strategies: Vec<BoxedStrategy<(String, FieldValue)>> = fields
.into_iter()
.map(|f| {
let name = f.name.clone();
arb_value_for_type_with_budget(f.field_type, per_field_budget)
.prop_map(move |v| (name.clone(), v))
.boxed()
})
.collect();
field_strategies
.prop_map(|pairs| {
let map: BTreeMap<String, FieldValue> = pairs.into_iter().collect();
FieldValue::Object(map)
})
.boxed()
}
FieldType::List(inner) => {
let cap = budget.min(MAX_COLLECTION_SIZE);
(0..=cap)
.prop_flat_map(move |n| {
let per_elem_budget = budget.checked_div(n).map_or(0, |b| b.max(1));
let elem_strategy =
arb_value_for_type_with_budget((*inner).clone(), per_elem_budget);
vec(elem_strategy, n..=n).prop_map(FieldValue::List)
})
.boxed()
}
FieldType::Media { .. } => {
unreachable!("arb_value_for_type called with Media (Media is unsupported)")
}
FieldType::OneOf { .. } | FieldType::AnyOf { .. } => {
unreachable!(
"arb_value_for_type called with OneOf/AnyOf (Phase 5 extends \
arb_supported_field_type with variant generation)"
)
}
}
}
pub fn arb_supported_type_and_value() -> impl Strategy<Value = (FieldType, FieldValue)> {
arb_supported_field_type().prop_flat_map(|ft| {
let v = arb_value_for_type(ft.clone());
(Just(ft), v)
})
}
pub fn arb_supported_list_type_and_value() -> impl Strategy<Value = (FieldType, FieldValue)> {
arb_supported_field_type()
.prop_map(|inner| FieldType::List(Box::new(inner)))
.prop_flat_map(|list_ft| {
let v = arb_value_for_type(list_ft.clone());
(Just(list_ft), v)
})
}
pub fn arb_unsupported_field_type() -> impl Strategy<Value = FieldType> {
prop_oneof![Just(FieldType::List(Box::new(FieldType::Media {
kind: modelplease::MediaKind::Image,
accepted_sources: enumset::EnumSet::all(),
}))),]
}
#[must_use]
#[expect(
clippy::expect_used,
reason = "test-support helper; infallible by construction"
)]
pub fn single_output_signature(name: &str, field_type: FieldType) -> Signature {
Signature::builder("proptest")
.input(FieldDef::input("q", FieldType::String, "question"))
.output(FieldDef::output(name, field_type, "output"))
.build()
.expect("single-output signature must build")
}
#[expect(
clippy::expect_used,
reason = "test-support helper; FieldValue is Serialize by construction"
)]
fn serialize_completion_body(field_type: &FieldType, value: &FieldValue) -> String {
match (field_type, value) {
(FieldType::String | FieldType::Enum(_), FieldValue::Str(s)) => s.clone(),
(FieldType::Nullable(inner), FieldValue::Null)
if matches!(**inner, FieldType::String | FieldType::Enum(_)) =>
{
"null".to_owned()
}
(FieldType::Nullable(inner), v)
if matches!(**inner, FieldType::String | FieldType::Enum(_)) =>
{
serialize_completion_body(inner, v)
}
(_, v) => serde_json::to_string(v).expect("FieldValue is Serialize"),
}
}
#[must_use]
pub fn serialize_completion(
field_name: &str,
field_type: &FieldType,
value: &FieldValue,
) -> String {
serialize_completion_with_drift(field_name, field_type, value, DriftPerturbation::None)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DriftPerturbation {
None,
FenceJson,
FenceBare,
ProsePrefix,
SingleKeyWrapper,
FenceAndWrapper,
}
pub fn arb_drift_perturbation() -> impl Strategy<Value = DriftPerturbation> {
prop_oneof![
Just(DriftPerturbation::None),
Just(DriftPerturbation::FenceJson),
Just(DriftPerturbation::FenceBare),
Just(DriftPerturbation::ProsePrefix),
Just(DriftPerturbation::SingleKeyWrapper),
Just(DriftPerturbation::FenceAndWrapper),
]
}
fn drift_applicable(ft: &FieldType) -> bool {
match ft {
FieldType::List(_)
| FieldType::Object(_)
| FieldType::Map(_)
| FieldType::OneOf { .. }
| FieldType::AnyOf { .. } => true,
FieldType::Nullable(inner) => drift_applicable(inner),
_ => false,
}
}
fn single_key_wrapper_safe(ft: &FieldType) -> bool {
match ft {
FieldType::List(_) => true,
FieldType::Nullable(inner) => single_key_wrapper_safe(inner),
_ => false,
}
}
#[must_use]
#[expect(
clippy::expect_used,
reason = "test-support helper; FieldValue is Serialize by construction"
)]
pub fn serialize_completion_with_drift(
field_name: &str,
field_type: &FieldType,
value: &FieldValue,
perturb: DriftPerturbation,
) -> String {
let mut content_body = match (field_type, value) {
(FieldType::String | FieldType::Enum(_), FieldValue::Str(s)) => s.clone(),
(FieldType::Nullable(inner), FieldValue::Null)
if matches!(**inner, FieldType::String | FieldType::Enum(_)) =>
{
"null".to_owned()
}
(FieldType::Nullable(inner), v)
if matches!(**inner, FieldType::String | FieldType::Enum(_)) =>
{
serialize_completion_body(inner, v)
}
(_, v) => serde_json::to_string(v).expect("FieldValue is Serialize"),
};
if drift_applicable(field_type) {
let safe_perturb = match perturb {
DriftPerturbation::SingleKeyWrapper | DriftPerturbation::FenceAndWrapper
if !single_key_wrapper_safe(field_type) =>
{
DriftPerturbation::None
}
other => other,
};
content_body = apply_drift(&content_body, field_name, safe_perturb);
}
format!("[[ ## {field_name} ## ]]\n{content_body}\n[[ ## completed ## ]]")
}
fn apply_drift(content: &str, field_name: &str, perturb: DriftPerturbation) -> String {
match perturb {
DriftPerturbation::None => content.to_owned(),
DriftPerturbation::FenceJson => format!("```json\n{content}\n```"),
DriftPerturbation::FenceBare => format!("```\n{content}\n```"),
DriftPerturbation::ProsePrefix => format!("Here is your {field_name}: {content}"),
DriftPerturbation::SingleKeyWrapper => format!("{{\"{field_name}\": {content}}}"),
DriftPerturbation::FenceAndWrapper => {
format!("```json\n{{\"{field_name}\": {content}}}\n```")
}
}
}
#[must_use]
pub fn chunk_at_positions<'a>(s: &'a str, raw_positions: &[u8]) -> Vec<&'a str> {
if s.is_empty() {
return vec![""];
}
let len = s.len();
let mut points: Vec<usize> = raw_positions
.iter()
.map(|&p| (p as usize) % len)
.filter(|&p| p > 0 && s.is_char_boundary(p))
.collect();
points.sort_unstable();
points.dedup();
let mut chunks: Vec<&str> = Vec::with_capacity(points.len() + 1);
let mut last = 0;
for &p in &points {
chunks.push(&s[last..p]);
last = p;
}
chunks.push(&s[last..]);
chunks
}
#[derive(Clone, Copy, Debug)]
enum ArmShape {
Int,
Bool,
StringList,
IntList,
SingleFieldObject,
}
impl ArmShape {
fn field_type(self) -> FieldType {
match self {
Self::Int => FieldType::Int,
Self::Bool => FieldType::Bool,
Self::StringList => FieldType::List(Box::new(FieldType::String)),
Self::IntList => FieldType::List(Box::new(FieldType::Int)),
Self::SingleFieldObject => FieldType::Object(vec![ObjectField {
name: "x".into(),
description: String::new(),
field_type: FieldType::Int,
}]),
}
}
fn arb_value(self) -> BoxedStrategy<FieldValue> {
match self {
Self::Int => any::<i32>()
.prop_map(|i| FieldValue::Int(i64::from(i)))
.boxed(),
Self::Bool => any::<bool>().prop_map(FieldValue::Bool).boxed(),
Self::StringList => vec(arb_safe_string(), 0..=4)
.prop_map(|items| {
FieldValue::List(items.into_iter().map(FieldValue::Str).collect())
})
.boxed(),
Self::IntList => vec(any::<i32>(), 0..=4)
.prop_map(|items| {
FieldValue::List(
items
.into_iter()
.map(|i| FieldValue::Int(i64::from(i)))
.collect(),
)
})
.boxed(),
Self::SingleFieldObject => any::<i32>()
.prop_map(|i| {
FieldValue::Object(BTreeMap::from([(
"x".into(),
FieldValue::Int(i64::from(i)),
)]))
})
.boxed(),
}
}
}
fn arm_set_choices() -> Vec<Vec<ArmShape>> {
vec![
vec![ArmShape::Int, ArmShape::StringList],
vec![ArmShape::Int, ArmShape::SingleFieldObject],
vec![ArmShape::Bool, ArmShape::StringList],
vec![ArmShape::Bool, ArmShape::SingleFieldObject],
vec![ArmShape::StringList, ArmShape::SingleFieldObject],
vec![ArmShape::IntList, ArmShape::SingleFieldObject],
vec![ArmShape::Int, ArmShape::Bool, ArmShape::StringList],
vec![ArmShape::Int, ArmShape::Bool, ArmShape::SingleFieldObject],
]
}
pub fn arb_variant_type_and_value() -> impl Strategy<Value = (FieldType, FieldValue)> {
let arm_sets = arm_set_choices();
let arm_count = arm_sets.len();
(0..arm_count, any::<bool>(), any::<u32>()).prop_flat_map(
move |(set_idx, use_anyof, picker)| {
let shapes = arm_sets[set_idx].clone();
let chosen_idx = (picker as usize) % shapes.len();
let chosen_shape = shapes[chosen_idx];
let arms: Vec<VariantArm> = shapes
.iter()
.map(|s| VariantArm {
description: format!("{s:?}"),
field_type: s.field_type(),
})
.collect();
let field_type = if use_anyof {
FieldType::AnyOf { arms }
} else {
FieldType::OneOf {
arms,
discriminator: None,
}
};
chosen_shape.arb_value().prop_map(move |inner| {
(
field_type.clone(),
FieldValue::Variant {
arm_index: chosen_idx,
value: Box::new(inner),
},
)
})
},
)
}
pub fn arb_tagged_oneof_type_and_value() -> impl Strategy<Value = (FieldType, FieldValue)> {
let arms_template: Vec<(&'static str, &'static str, FieldType)> = vec![
("kind_a", "alpha", FieldType::Int),
("kind_b", "beta", FieldType::String),
("kind_c", "gamma", FieldType::List(Box::new(FieldType::Int))),
];
let arms_field_types: Vec<FieldType> = arms_template
.iter()
.map(|(tag, _, payload_ty)| {
FieldType::Object(vec![
ObjectField {
name: "kind".into(),
description: String::new(),
field_type: FieldType::Enum(vec![(*tag).to_string()]),
},
ObjectField {
name: "payload".into(),
description: String::new(),
field_type: payload_ty.clone(),
},
])
})
.collect();
let arms: Vec<VariantArm> = arms_template
.iter()
.zip(arms_field_types.iter())
.map(|((_, desc, _), ft)| VariantArm {
description: (*desc).to_string(),
field_type: ft.clone(),
})
.collect();
let tags: Vec<String> = arms_template
.iter()
.map(|(tag, _, _)| (*tag).to_string())
.collect();
let field_type = FieldType::OneOf {
arms,
discriminator: Some(OneOfDiscriminator {
property: "kind".into(),
tags: tags.clone(),
}),
};
(0_usize..arms_template.len(), any::<u32>()).prop_flat_map(move |(idx, seed)| {
let tag = tags[idx].clone();
let payload_strategy: BoxedStrategy<FieldValue> = match arms_template[idx].2 {
FieldType::Int => any::<i32>()
.prop_map(|i| FieldValue::Int(i64::from(i)))
.boxed(),
FieldType::String => arb_safe_string().prop_map(FieldValue::Str).boxed(),
FieldType::List(_) => vec(any::<i32>(), 0..=3)
.prop_map(|items| {
FieldValue::List(
items
.into_iter()
.map(|i| FieldValue::Int(i64::from(i)))
.collect(),
)
})
.boxed(),
_ => unreachable!("template payload types are fixed"),
};
let _ = seed;
let ft = field_type.clone();
payload_strategy.prop_map(move |payload| {
let inner = FieldValue::Object(BTreeMap::from([
("kind".into(), FieldValue::Str(tag.clone())),
("payload".into(), payload),
]));
(
ft.clone(),
FieldValue::Variant {
arm_index: idx,
value: Box::new(inner),
},
)
})
})
}
pub fn arb_chunking_positions() -> impl Strategy<Value = Vec<u8>> {
vec(any::<u8>(), 0..=10)
}