blob: 9684f25dd835aac771f36547fb3f7fe3fa8a5fae [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Strict parser for `RawCppBundle` (schema v1) JSON emitted by
//! `tools/anneal-clang-dump/main.cc`.
//!
//! Unlike `anneal-lower-cpp`, this parser retains every FFI-relevant layout,
//! C++ object-model, and LLVM ABI passing fact (`is_packed`, `sign_ext`,
//! `indirect.byval`, `has_non_trivial_dtor`, `is_polymorphic`, `bases`,
//! `has_mutable`) and extracts direct/opaque call targets from `body_stmt`
//! for transitive `extern "C"` unwind-safety auditing.
use std::collections::BTreeSet;
use serde_json::{Map, Value};
use crate::report::ParseError;
/// Language policy emitted by `anneal-clang-dump` (`langPolicyJson`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppLangPolicy {
pub is_cplusplus: bool,
pub lang_standard: String,
pub pointer_width_bits: u64,
pub c_long_bits: Option<u64>,
pub char_is_signed: bool,
pub strict_aliasing: bool,
pub signed_overflow: String,
pub exceptions_enabled: bool,
pub fast_math: bool,
pub little_endian: Option<bool>,
}
/// Structural C/C++ type emitted by `typeJson`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CppType {
Void,
Bool,
Int {
bits: u64,
signed: bool,
is_char_like: bool,
enum_id: Option<String>,
enum_name: Option<String>,
/// Canonical built-in C/C++ integer spelling (e.g. `long`, `long long`,
/// `signed char`) emitted by `anneal-clang-dump`, preserving exact C
/// prototype compatibility on platforms where fixed-width typedefs
/// differ from `long`/`long long`.
c_spelling: Option<String>,
},
Ptr {
pointee: Box<CppType>,
is_const: bool,
is_restrict: bool,
may_alias: bool,
},
Ref {
pointee: Box<CppType>,
is_const: bool,
is_rvalue: bool,
may_alias: bool,
},
Array {
elem: Box<CppType>,
len: u64,
},
Record {
id: String,
},
NullPtrT,
Unsupported {
desc: String,
},
}
/// One field in a C/C++ record (`recordJson`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppField {
pub name: String,
pub offset_bits: u64,
pub bit_width: Option<u64>,
pub ty: CppType,
/// Optional member `const`-qualification (`fields[].is_const`). `None`
/// when omitted by older schema v1 bundles; `--emit-lean` fails closed
/// unless explicitly present.
pub is_const: Option<bool>,
}
/// Direct C++ base subobject (`recordJson`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppBase {
pub record_id: String,
pub is_virtual: bool,
pub offset_bytes: Option<u64>,
}
/// Record layout and C++ object-model facts (`recordJson`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppRecord {
pub id: String,
pub name: String,
/// Fully qualified C++ record name (e.g. `ns::Point`) when emitted for a
/// C++ translation unit.
pub qualified_name: Option<String>,
/// True when the C/C++ record was declared as an anonymous
/// `typedef struct { ... } Name;` (so C assertions must spell `Name`, not
/// `struct Name`).
pub is_anonymous_typedef: bool,
pub is_union: bool,
pub size_bytes: u64,
pub align_bytes: u64,
pub is_packed: bool,
pub fields: Vec<CppField>,
pub is_cxx_record: bool,
pub is_polymorphic: bool,
pub is_trivially_copyable: bool,
pub has_non_trivial_dtor: bool,
pub dtor_symbol: Option<String>,
/// Transitive `mutable` subobject flag (`has_mutable`) emitted by
/// `anneal-clang-dump` for `CXXRecordDecl`s. `None` when omitted on a
/// C++ record; `const T&` -> Rust `&T` binding fails closed unless
/// explicitly `Some(false)`.
pub has_mutable: Option<bool>,
pub bases: Vec<CppBase>,
}
/// LLVM/Clang `ABIArgInfo` passing class (`abiArgJson`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AbiPassing {
DirectInt { bits: u64 },
ExtendInt { bits: u64, sign_ext: bool },
DirectPtr,
DirectOther { desc: String },
Ignore,
Indirect { byval: bool },
Other { desc: String },
}
/// Per-function ABI witness (`abiWitnessJson`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppAbiWitness {
pub cc: String,
pub return_passing: Option<AbiPassing>,
pub param_passing: Vec<AbiPassing>,
}
/// Function parameter entry (`functionJson`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppParam {
pub name: String,
pub ty: CppType,
pub is_this: bool,
pub dtor_symbol: Option<String>,
}
/// C++ method classification (`cxxFunctionFacts`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CppMethodKind {
Free,
Method,
Ctor,
Dtor,
}
/// Function signature and ABI metadata (`functionJson`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppFunction {
pub symbol: String,
pub unmangled_name: String,
/// Fully qualified C++ function name (e.g. `api::apply_mode`) emitted by
/// `anneal-clang-dump` for C++ translation units.
pub qualified_name: Option<String>,
pub is_extern_c: bool,
pub is_definition: bool,
pub is_variadic: bool,
/// `Some(true)` for a prototyped declaration (`FunctionProtoType`),
/// `Some(false)` for an unprototyped C declaration (`FunctionNoProtoType`,
/// e.g. `int f()`), or `None` when omitted by older schema v1 bundles.
pub has_prototype: Option<bool>,
pub return_ty: CppType,
pub params: Vec<CppParam>,
pub abi_witness: CppAbiWitness,
pub method_kind: CppMethodKind,
pub is_virtual: bool,
/// True iff `body_stmt` was present and non-null in `RawCppBundle`.
pub has_body_stmt: bool,
/// Deterministic sorted list of direct callee/ctor/dtor linker symbols
/// referenced by this function's body, initializers, or parameter cleanup.
pub direct_callees: Vec<String>,
/// True iff the function body contains an indirect call, virtual call, or
/// unmodeled statement/expression that could invoke a throwing callee.
pub has_opaque_call: bool,
}
/// One enumerator constant in a C/C++ enum definition (`enums[].enumerators`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppEnumerator {
pub name: String,
pub value_str: String,
}
/// C/C++ enum underlying-type and enumerator descriptor in
/// `RawCppBundle.enums`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppEnum {
pub id: Option<String>,
pub name: String,
/// Fully qualified C++ enum name (e.g. `ns::Mode`) when emitted for a C++
/// translation unit.
pub qualified_name: Option<String>,
/// True when declared as `typedef enum { ... } Name;` without an enum tag.
pub is_anonymous_typedef: bool,
pub bits: u64,
pub signed: bool,
/// True when the C++ enum has fixed underlying type `bool` (valid values
/// restricted to `{0, 1}`; must never bind as an unrestricted integer).
pub underlying_is_bool: bool,
pub is_fixed: Option<bool>,
pub is_scoped: Option<bool>,
pub enumerators: Option<Vec<CppEnumerator>>,
}
/// Top-level `RawCppBundle` v1 view for FFI verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppBundle {
pub tu_main_file: String,
pub target_triple: String,
pub lang_policy: CppLangPolicy,
pub records: Vec<CppRecord>,
pub enums: Vec<CppEnum>,
pub functions: Vec<CppFunction>,
}
impl CppBundle {
/// Unambiguously resolves a C/C++ record by exact `id`, short `name`, or
/// `struct.<key>` / `union.<key>` prefix.
pub(crate) fn find_record(&self, key: &str) -> Option<&CppRecord> {
let exact: Vec<&CppRecord> = self.records.iter().filter(|r| r.id == key).collect();
if let [only] = exact.as_slice() {
return Some(*only);
}
if !exact.is_empty() {
return None;
}
let matches: Vec<&CppRecord> = self
.records
.iter()
.filter(|r| {
r.name == key || r.id == format!("struct.{key}") || r.id == format!("union.{key}")
})
.collect();
match matches.as_slice() {
[only] => Some(*only),
_ => None,
}
}
}
/// Parses a `RawCppBundle` schema v1 JSON string, failing closed on missing
/// required ABI or layout fields.
pub fn parse_cpp_bundle(text: &str) -> Result<CppBundle, ParseError> {
let value: Value = serde_json::from_str(text).map_err(|e| ParseError::Json(e.to_string()))?;
let root = as_obj(&value, "bundle")?;
let version = req_u64(root, "schema_version", "bundle")?;
if version != 1 {
return Err(ParseError::Schema(format!(
"unsupported RawCppBundle schema_version {version} (expected 1)"
)));
}
let tu_main_file = req_str(root, "tu_main_file", "bundle")?;
let target_triple = req_str(root, "target_triple", "bundle")?;
let lp = as_obj(req_field(root, "lang_policy", "bundle")?, "lang_policy")?;
let lang_policy = CppLangPolicy {
is_cplusplus: req_bool(lp, "is_cplusplus", "lang_policy")?,
lang_standard: req_str(lp, "lang_standard", "lang_policy")?,
pointer_width_bits: req_u64(lp, "pointer_width_bits", "lang_policy")?,
c_long_bits: opt_u64(lp, "c_long_bits", "lang_policy")?,
char_is_signed: req_bool(lp, "char_is_signed", "lang_policy")?,
strict_aliasing: req_bool(lp, "strict_aliasing", "lang_policy")?,
signed_overflow: req_str(lp, "signed_overflow", "lang_policy")?,
exceptions_enabled: req_bool(lp, "exceptions_enabled", "lang_policy")?,
fast_math: req_bool(lp, "fast_math", "lang_policy")?,
little_endian: opt_bool(lp, "little_endian", "lang_policy")?,
};
let mut records = Vec::new();
for r in req_arr(root, "records", "bundle")? {
records.push(parse_record(r)?);
}
let mut enums = Vec::new();
if let Some(ev) = opt_field(root, "enums") {
let arr = ev.as_array().ok_or_else(|| {
ParseError::Schema("bundle: field `enums` must be an array".to_owned())
})?;
for e in arr {
let eo = as_obj(e, "cpp enum")?;
let id = opt_str(eo, "id", "cpp enum")?;
let name = req_str(eo, "name", "cpp enum")?;
let ctx = format!("cpp enum `{name}`");
let enumerators = match opt_field(eo, "enumerators") {
None => None,
Some(ev_arr) => {
let items = ev_arr.as_array().ok_or_else(|| {
ParseError::Schema(format!("{ctx}: field `enumerators` must be an array"))
})?;
let mut parsed = Vec::with_capacity(items.len());
for item in items {
let io = as_obj(item, &ctx)?;
parsed.push(CppEnumerator {
name: req_str(io, "name", &ctx)?,
value_str: req_str(io, "value_str", &ctx)?,
});
}
Some(parsed)
}
};
enums.push(CppEnum {
id,
name,
qualified_name: opt_str(eo, "qualified_name", &ctx)?,
is_anonymous_typedef: opt_bool(eo, "is_anonymous_typedef", &ctx)?.unwrap_or(false),
bits: req_u64(eo, "bits", &ctx)?,
signed: req_bool(eo, "signed", &ctx)?,
underlying_is_bool: opt_bool(eo, "underlying_is_bool", &ctx)?.unwrap_or(false),
is_fixed: opt_bool(eo, "is_fixed", &ctx)?,
is_scoped: opt_bool(eo, "is_scoped", &ctx)?,
enumerators,
});
}
}
let mut functions = Vec::new();
for f in req_arr(root, "functions", "bundle")? {
functions.push(parse_function(f)?);
}
Ok(CppBundle { tu_main_file, target_triple, lang_policy, records, enums, functions })
}
fn parse_record(v: &Value) -> Result<CppRecord, ParseError> {
let o = as_obj(v, "record")?;
let id = req_str(o, "id", "record")?;
let ctx = format!("record `{id}`");
let name = opt_str(o, "name", &ctx)?.unwrap_or_default();
let qualified_name = opt_str(o, "qualified_name", &ctx)?;
let is_anonymous_typedef = opt_bool(o, "is_anonymous_typedef", &ctx)?.unwrap_or(false);
let is_union = req_bool(o, "is_union", &ctx)?;
let size_bytes = req_u64(o, "size_bytes", &ctx)?;
let align_bytes = req_u64(o, "align_bytes", &ctx)?;
let is_packed = opt_bool(o, "is_packed", &ctx)?.unwrap_or(false);
let mut fields = Vec::new();
for f in req_arr(o, "fields", &ctx)? {
let fo = as_obj(f, &ctx)?;
let bit_width = match opt_field(fo, "bit_width") {
None => None,
Some(bv) => match bv.as_u64() {
Some(n) => Some(n),
None => {
return Err(ParseError::Schema(format!(
"{ctx}: field `bit_width` must be a non-negative \
integer or null"
)));
}
},
};
fields.push(CppField {
name: req_str(fo, "name", &ctx)?,
offset_bits: req_u64(fo, "offset_bits", &ctx)?,
bit_width,
ty: parse_cpp_type(req_field(fo, "ty", &ctx)?)?,
is_const: opt_bool(fo, "is_const", &ctx)?,
});
}
let is_cxx_record = opt_bool(o, "is_cxx_record", &ctx)?.unwrap_or(false);
let is_polymorphic = if is_cxx_record {
req_bool(o, "is_polymorphic", &ctx)?
} else {
opt_bool(o, "is_polymorphic", &ctx)?.unwrap_or(false)
};
let is_trivially_copyable = if is_cxx_record {
req_bool(o, "is_trivially_copyable", &ctx)?
} else {
opt_bool(o, "is_trivially_copyable", &ctx)?.unwrap_or(true)
};
let has_non_trivial_dtor = if is_cxx_record {
req_bool(o, "has_non_trivial_dtor", &ctx)?
} else {
opt_bool(o, "has_non_trivial_dtor", &ctx)?.unwrap_or(false)
};
let dtor_symbol = opt_str(o, "dtor_symbol", &ctx)?;
let has_mutable = opt_bool(o, "has_mutable", &ctx)?;
let mut bases = Vec::new();
if let Some(bases_val) = opt_field(o, "bases") {
let arr = bases_val
.as_array()
.ok_or_else(|| ParseError::Schema(format!("{ctx}: `bases` must be an array")))?;
for b in arr {
let bo = as_obj(b, &ctx)?;
let is_virtual = req_bool(bo, "is_virtual", &ctx)?;
let offset_bytes = match opt_field(bo, "offset_bytes") {
None => None,
Some(ov) => match ov.as_u64() {
Some(n) => Some(n),
None => {
return Err(ParseError::Schema(format!(
"{ctx}: base `offset_bytes` must be a non-negative \
integer or null"
)));
}
},
};
bases.push(CppBase {
record_id: req_str(bo, "record_id", &ctx)?,
is_virtual,
offset_bytes,
});
}
}
Ok(CppRecord {
id,
name,
qualified_name,
is_anonymous_typedef,
is_union,
size_bytes,
align_bytes,
is_packed,
fields,
is_cxx_record,
is_polymorphic,
is_trivially_copyable,
has_non_trivial_dtor,
dtor_symbol,
has_mutable,
bases,
})
}
fn parse_function(v: &Value) -> Result<CppFunction, ParseError> {
let o = as_obj(v, "function")?;
let symbol = req_str(o, "symbol", "function")?;
let ctx = format!("function `{symbol}`");
let unmangled_name = req_str(o, "unmangled_name", &ctx)?;
let qualified_name = opt_str(o, "qualified_name", &ctx)?;
let is_extern_c = req_bool(o, "is_extern_c", &ctx)?;
let is_definition = req_bool(o, "is_definition", &ctx)?;
let is_variadic = req_bool(o, "is_variadic", &ctx)?;
let has_prototype = opt_bool(o, "has_prototype", &ctx)?;
let return_ty = parse_cpp_type(req_field(o, "return_ty", &ctx)?)?;
let mut params = Vec::new();
for p in req_arr(o, "params", &ctx)? {
let po = as_obj(p, &ctx)?;
params.push(CppParam {
name: req_str(po, "name", &ctx)?,
ty: parse_cpp_type(req_field(po, "ty", &ctx)?)?,
is_this: opt_bool(po, "is_this", &ctx)?.unwrap_or(false),
dtor_symbol: opt_str(po, "dtor_symbol", &ctx)?,
});
}
let abi = as_obj(req_field(o, "abi_witness", &ctx)?, &ctx)?;
let cc = req_str(abi, "cc", &ctx)?;
let return_passing = if cc == "unknown" {
None
} else {
Some(parse_abi_passing(
req_field(abi, "return_passing", &ctx)?,
&format!("{ctx}.abi_witness.return_passing"),
)?)
};
let mut param_passing = Vec::new();
if cc != "unknown" {
for (i, pp) in req_arr(abi, "param_passing", &ctx)?.iter().enumerate() {
param_passing
.push(parse_abi_passing(pp, &format!("{ctx}.abi_witness.param_passing[{i}]"))?);
}
}
let method_kind = match opt_str(o, "method_kind", &ctx)?.as_deref() {
None | Some("free") => CppMethodKind::Free,
Some("method") => CppMethodKind::Method,
Some("ctor") => CppMethodKind::Ctor,
Some("dtor") => CppMethodKind::Dtor,
Some(other) => {
return Err(ParseError::Schema(format!("{ctx}: unknown method_kind `{other}`")));
}
};
let is_virtual = opt_bool(o, "is_virtual", &ctx)?.unwrap_or(false);
let mut callees = BTreeSet::new();
let mut has_opaque_call = false;
for p in &params {
if let Some(dtor) = &p.dtor_symbol {
callees.insert(dtor.clone());
}
}
let has_body_stmt = match opt_field(o, "body_stmt") {
Some(body) => {
collect_body_callees(body, &mut callees, &mut has_opaque_call);
true
}
None => false,
};
for extra_key in ["ctor_inits", "member_dtors", "base_dtors"] {
if let Some(extra) = opt_field(o, extra_key) {
collect_body_callees(extra, &mut callees, &mut has_opaque_call);
}
}
Ok(CppFunction {
symbol,
unmangled_name,
qualified_name,
is_extern_c,
is_definition,
is_variadic,
has_prototype,
return_ty,
params,
abi_witness: CppAbiWitness { cc, return_passing, param_passing },
method_kind,
is_virtual,
has_body_stmt,
direct_callees: callees.into_iter().collect(),
has_opaque_call,
})
}
fn collect_body_callees(v: &Value, callees: &mut BTreeSet<String>, has_opaque_call: &mut bool) {
match v {
Value::Object(map) => {
let kind_str = map.get("kind").and_then(Value::as_str);
if let Some(kind) = kind_str {
match kind {
"call" => {
let is_builtin =
map.get("is_builtin").and_then(Value::as_bool).unwrap_or(false);
let trivial_assign =
map.get("trivial_assign").and_then(Value::as_bool).unwrap_or(false);
if trivial_assign {
// Trivial copy/move assignment lowers inline and
// cannot unwind.
} else if is_builtin {
// Clang sets `is_builtin: true` on `LIBBUILTIN`s
// such as `longjmp` and global `operator new`
// (`_Znwm`), which can non-locally jump or throw
// across Rust `extern "C"` frames. Allowlist only
// pure non-unwinding intrinsics.
let sym = map.get("callee_symbol").and_then(Value::as_str);
if sym != Some("__builtin_expect") {
*has_opaque_call = true;
}
} else {
let is_indirect =
map.get("is_indirect").and_then(Value::as_bool).unwrap_or(false);
let is_virtual =
map.get("is_virtual").and_then(Value::as_bool).unwrap_or(false);
if is_indirect || is_virtual {
*has_opaque_call = true;
} else if let Some(sym) =
map.get("callee_symbol").and_then(Value::as_str)
{
callees.insert(sym.to_owned());
} else {
*has_opaque_call = true;
}
}
}
"unsupported_stmt" | "unsupported_expr" | "unsupported" => {
*has_opaque_call = true;
}
_ => {}
}
}
// Trivial `construct` expressions (`is_trivial: true`) are lowered
// inline without a `bundle.functions` entry and cannot throw.
let is_trivial_construct = kind_str == Some("construct")
&& map.get("is_trivial").and_then(Value::as_bool).unwrap_or(false);
if !is_trivial_construct {
if let Some(sym) = map.get("ctor_symbol").and_then(Value::as_str) {
callees.insert(sym.to_owned());
}
}
if let Some(sym) = map.get("dtor_symbol").and_then(Value::as_str) {
callees.insert(sym.to_owned());
}
for (k, child) in map {
if k == "ty" {
continue;
}
collect_body_callees(child, callees, has_opaque_call);
}
}
Value::Array(items) => {
for item in items {
collect_body_callees(item, callees, has_opaque_call);
}
}
_ => {}
}
}
/// Parses an `abi_witness` passing descriptor (`abiArgJson` schema).
pub fn parse_abi_passing(v: &Value, ctx: &str) -> Result<AbiPassing, ParseError> {
let o = as_obj(v, ctx)?;
let kind = req_str(o, "kind", ctx)?;
match kind.as_str() {
"direct_int" => Ok(AbiPassing::DirectInt { bits: req_u64(o, "bits", ctx)? }),
"extend_int" => Ok(AbiPassing::ExtendInt {
bits: req_u64(o, "bits", ctx)?,
sign_ext: req_bool(o, "sign_ext", ctx)?,
}),
"direct_ptr" => Ok(AbiPassing::DirectPtr),
"direct_other" => Ok(AbiPassing::DirectOther { desc: req_str(o, "desc", ctx)? }),
"ignore" => Ok(AbiPassing::Ignore),
"indirect" => Ok(AbiPassing::Indirect { byval: req_bool(o, "byval", ctx)? }),
"other" => Ok(AbiPassing::Other { desc: req_str(o, "desc", ctx)? }),
other => {
Err(ParseError::Schema(format!("{ctx}: unknown abi_witness passing kind `{other}`")))
}
}
}
fn parse_cpp_type(v: &Value) -> Result<CppType, ParseError> {
let o = as_obj(v, "cpp type")?;
let kind = req_str(o, "kind", "cpp type")?;
match kind.as_str() {
"void" => Ok(CppType::Void),
"bool" => Ok(CppType::Bool),
"int" => Ok(CppType::Int {
bits: req_u64(o, "bits", "int type")?,
signed: req_bool(o, "signed", "int type")?,
is_char_like: opt_bool(o, "is_char_like", "int type")?.unwrap_or(false),
enum_id: opt_str(o, "enum_id", "int type")?,
enum_name: opt_str(o, "enum_name", "int type")?,
c_spelling: opt_str(o, "c_spelling", "int type")?,
}),
"ptr" => Ok(CppType::Ptr {
pointee: Box::new(parse_cpp_type(req_field(o, "pointee", "ptr type")?)?),
is_const: req_bool(o, "is_const", "ptr type")?,
is_restrict: req_bool(o, "is_restrict", "ptr type")?,
may_alias: req_bool(o, "may_alias", "ptr type")?,
}),
"ref" => Ok(CppType::Ref {
pointee: Box::new(parse_cpp_type(req_field(o, "pointee", "ref type")?)?),
is_const: req_bool(o, "is_const", "ref type")?,
is_rvalue: req_bool(o, "is_rvalue", "ref type")?,
may_alias: opt_bool(o, "may_alias", "ref type")?.unwrap_or(false),
}),
"array" => Ok(CppType::Array {
elem: Box::new(parse_cpp_type(req_field(o, "elem", "array type")?)?),
len: req_u64(o, "len", "array type")?,
}),
"record" => Ok(CppType::Record { id: req_str(o, "id", "record type")? }),
"nullptr_t" => Ok(CppType::NullPtrT),
"unsupported" => Ok(CppType::Unsupported { desc: req_str(o, "desc", "unsupported type")? }),
other => Err(ParseError::Schema(format!("cpp type: unknown kind `{other}`"))),
}
}
pub(crate) fn as_obj<'a>(v: &'a Value, ctx: &str) -> Result<&'a Map<String, Value>, ParseError> {
v.as_object().ok_or_else(|| ParseError::Schema(format!("{ctx}: expected JSON object")))
}
pub(crate) fn req_field<'a>(
o: &'a Map<String, Value>,
key: &str,
ctx: &str,
) -> Result<&'a Value, ParseError> {
o.get(key).ok_or_else(|| ParseError::Schema(format!("{ctx}: missing required `{key}`")))
}
pub(crate) fn opt_field<'a>(o: &'a Map<String, Value>, key: &str) -> Option<&'a Value> {
match o.get(key) {
None | Some(Value::Null) => None,
Some(v) => Some(v),
}
}
pub(crate) fn req_str(o: &Map<String, Value>, key: &str, ctx: &str) -> Result<String, ParseError> {
req_field(o, key, ctx)?
.as_str()
.map(str::to_owned)
.ok_or_else(|| ParseError::Schema(format!("{ctx}: field `{key}` must be a string")))
}
pub(crate) fn opt_str(
o: &Map<String, Value>,
key: &str,
ctx: &str,
) -> Result<Option<String>, ParseError> {
match opt_field(o, key) {
None => Ok(None),
Some(v) => v.as_str().map(|s| Some(s.to_owned())).ok_or_else(|| {
ParseError::Schema(format!("{ctx}: field `{key}` must be a string or null"))
}),
}
}
pub(crate) fn req_bool(o: &Map<String, Value>, key: &str, ctx: &str) -> Result<bool, ParseError> {
req_field(o, key, ctx)?
.as_bool()
.ok_or_else(|| ParseError::Schema(format!("{ctx}: field `{key}` must be a bool")))
}
pub(crate) fn opt_bool(
o: &Map<String, Value>,
key: &str,
ctx: &str,
) -> Result<Option<bool>, ParseError> {
match opt_field(o, key) {
None => Ok(None),
Some(v) => v.as_bool().map(Some).ok_or_else(|| {
ParseError::Schema(format!("{ctx}: field `{key}` must be a bool or null"))
}),
}
}
pub(crate) fn req_u64(o: &Map<String, Value>, key: &str, ctx: &str) -> Result<u64, ParseError> {
req_field(o, key, ctx)?.as_u64().ok_or_else(|| {
ParseError::Schema(format!("{ctx}: field `{key}` must be a non-negative integer"))
})
}
pub(crate) fn opt_u64(
o: &Map<String, Value>,
key: &str,
ctx: &str,
) -> Result<Option<u64>, ParseError> {
match opt_field(o, key) {
None => Ok(None),
Some(v) => v.as_u64().map(Some).ok_or_else(|| {
ParseError::Schema(format!(
"{ctx}: field `{key}` must be a non-negative integer or null"
))
}),
}
}
pub(crate) fn req_arr<'a>(
o: &'a Map<String, Value>,
key: &str,
ctx: &str,
) -> Result<&'a Vec<Value>, ParseError> {
req_field(o, key, ctx)?
.as_array()
.ok_or_else(|| ParseError::Schema(format!("{ctx}: field `{key}` must be an array")))
}