use fhir_types::codec::DecodeError;
use fhir_types::codec::EncodeError;
use fhir_types::codec::Json;
use fhir_types::codec::Path;
use fhir_types::codec::Primitive;
use fhir_types::codec::Value;
use fhir_types::r4::attachment::Attachment;
use fhir_types::r4::codeable_concept::CodeableConcept;
use fhir_types::r4::coding::Coding;
use fhir_types::r4::count::Count;
use fhir_types::r4::duration::Duration;
use fhir_types::r4::identifier::Identifier;
use fhir_types::r4::period::Period;
use fhir_types::r4::primitives;
use fhir_types::r4::primitives::Boolean;
use fhir_types::r4::primitives::Date;
use fhir_types::r4::primitives::DateTime;
use fhir_types::r4::primitives::Decimal;
use fhir_types::r4::primitives::Instant;
use fhir_types::r4::primitives::Integer;
use fhir_types::r4::primitives::PositiveInt;
use fhir_types::r4::primitives::Time;
use fhir_types::r4::primitives::UnsignedInt;
use fhir_types::r4::primitives::Url;
use fhir_types::r4::quantity::Quantity;
use fhir_types::r4::range::Range;
use fhir_types::r4::reference::Reference;
use fhir_types::schema::ValueKind;
use crate::model::ast::keyword::DataType;
use crate::tree::element::Location;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FhirKind {
String,
Date,
DateTime,
Instant,
Boolean,
Coding,
CodeableConcept,
Period,
Reference,
Identifier,
Quantity,
Integer,
UnsignedInt,
PositiveInt,
Decimal,
Count,
Time,
Duration,
Url,
Attachment,
Range,
}
impl FhirKind {
#[must_use]
pub const fn of(data_type: DataType) -> Option<Self> {
match data_type {
DataType::String | DataType::Id => Some(Self::String),
DataType::DateTime => Some(Self::DateTime),
DataType::Coding => Some(Self::Coding),
DataType::CodeableConcept => Some(Self::CodeableConcept),
DataType::Identifier => Some(Self::Identifier),
DataType::Quantity | DataType::Proportion => Some(Self::Quantity),
DataType::None | DataType::Dosage => None,
}
}
#[must_use]
pub fn of_code(code: &str) -> Option<Self> {
match code {
"string" => Some(Self::String),
"date" => Some(Self::Date),
"dateTime" => Some(Self::DateTime),
"instant" => Some(Self::Instant),
"boolean" => Some(Self::Boolean),
"Coding" => Some(Self::Coding),
"CodeableConcept" => Some(Self::CodeableConcept),
"Period" => Some(Self::Period),
"Reference" => Some(Self::Reference),
"Identifier" => Some(Self::Identifier),
"Quantity" => Some(Self::Quantity),
"integer" => Some(Self::Integer),
"unsignedInt" => Some(Self::UnsignedInt),
"positiveInt" => Some(Self::PositiveInt),
"decimal" => Some(Self::Decimal),
"Count" => Some(Self::Count),
"time" => Some(Self::Time),
"Duration" => Some(Self::Duration),
"url" => Some(Self::Url),
"Attachment" => Some(Self::Attachment),
"Range" => Some(Self::Range),
_ => None,
}
}
#[must_use]
pub fn at(location: &Location) -> Option<Self> {
match *location {
Location::Complex(schema) => match schema.path {
"Coding" => Some(Self::Coding),
"CodeableConcept" => Some(Self::CodeableConcept),
"Period" => Some(Self::Period),
"Reference" => Some(Self::Reference),
"Identifier" => Some(Self::Identifier),
"Quantity" => Some(Self::Quantity),
"Count" => Some(Self::Count),
"Duration" => Some(Self::Duration),
"Attachment" => Some(Self::Attachment),
"Range" => Some(Self::Range),
_ => None,
},
Location::Primitive(ValueKind::Text) | Location::Attribute => Some(Self::String),
Location::Primitive(_)
| Location::PrimitiveElement
| Location::Choice(_)
| Location::Resource
| Location::Deferred => None,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::String => "string",
Self::Date => "date",
Self::DateTime => "dateTime",
Self::Instant => "instant",
Self::Boolean => "boolean",
Self::Coding => "Coding",
Self::CodeableConcept => "CodeableConcept",
Self::Period => "Period",
Self::Reference => "Reference",
Self::Identifier => "Identifier",
Self::Quantity => "Quantity",
Self::Integer => "integer",
Self::UnsignedInt => "unsignedInt",
Self::PositiveInt => "positiveInt",
Self::Decimal => "decimal",
Self::Count => "Count",
Self::Time => "time",
Self::Duration => "Duration",
Self::Url => "url",
Self::Attachment => "Attachment",
Self::Range => "Range",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FhirValue {
String(primitives::String),
Date(Date),
DateTime(DateTime),
Instant(Instant),
Boolean(Boolean),
Coding(Box<Coding>),
CodeableConcept(Box<CodeableConcept>),
Period(Box<Period>),
Reference(Box<Reference>),
Identifier(Box<Identifier>),
Quantity(Box<Quantity>),
Integer(Integer),
UnsignedInt(UnsignedInt),
PositiveInt(PositiveInt),
Decimal(Decimal),
Count(Box<Count>),
Time(Time),
Duration(Box<Duration>),
Url(Url),
Attachment(Box<Attachment>),
Range(Box<Range>),
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum FhirError {
#[error("the value at {element} does not read as {kind}")]
Decode {
element: String,
kind: &'static str,
#[source]
source: DecodeError,
},
#[error("the {kind} value has no JSON form")]
Encode {
kind: &'static str,
#[source]
source: EncodeError,
},
#[error("the {kind} value at {element} carries no value of its own")]
NoValue {
element: String,
kind: &'static str,
},
}
impl FhirValue {
#[must_use]
pub const fn kind(&self) -> FhirKind {
match *self {
Self::String(_) => FhirKind::String,
Self::Date(_) => FhirKind::Date,
Self::DateTime(_) => FhirKind::DateTime,
Self::Instant(_) => FhirKind::Instant,
Self::Boolean(_) => FhirKind::Boolean,
Self::Coding(_) => FhirKind::Coding,
Self::CodeableConcept(_) => FhirKind::CodeableConcept,
Self::Period(_) => FhirKind::Period,
Self::Reference(_) => FhirKind::Reference,
Self::Identifier(_) => FhirKind::Identifier,
Self::Quantity(_) => FhirKind::Quantity,
Self::Integer(_) => FhirKind::Integer,
Self::UnsignedInt(_) => FhirKind::UnsignedInt,
Self::PositiveInt(_) => FhirKind::PositiveInt,
Self::Decimal(_) => FhirKind::Decimal,
Self::Count(_) => FhirKind::Count,
Self::Time(_) => FhirKind::Time,
Self::Duration(_) => FhirKind::Duration,
Self::Url(_) => FhirKind::Url,
Self::Attachment(_) => FhirKind::Attachment,
Self::Range(_) => FhirKind::Range,
}
}
pub fn read(kind: FhirKind, element: &str, value: &Value) -> Result<Self, FhirError> {
let mut path = Path::root(element);
let refuse = |source: DecodeError| FhirError::Decode {
element: String::from(element),
kind: kind.as_str(),
source,
};
match kind {
FhirKind::String => primitives::String::from_json_parts(Some(value), None, &mut path)
.map(Self::String)
.map_err(refuse),
FhirKind::Date => Date::from_json_parts(Some(value), None, &mut path)
.map(Self::Date)
.map_err(refuse),
FhirKind::DateTime => DateTime::from_json_parts(Some(value), None, &mut path)
.map(Self::DateTime)
.map_err(refuse),
FhirKind::Instant => Instant::from_json_parts(Some(value), None, &mut path)
.map(Self::Instant)
.map_err(refuse),
FhirKind::Boolean => Boolean::from_json_parts(Some(value), None, &mut path)
.map(Self::Boolean)
.map_err(refuse),
FhirKind::Coding => object(value, element, kind)
.and_then(|object| Coding::from_json(object, &mut path).map_err(refuse))
.map(|coding| Self::Coding(Box::new(coding))),
FhirKind::CodeableConcept => object(value, element, kind)
.and_then(|object| CodeableConcept::from_json(object, &mut path).map_err(refuse))
.map(|concept| Self::CodeableConcept(Box::new(concept))),
FhirKind::Period => object(value, element, kind)
.and_then(|object| Period::from_json(object, &mut path).map_err(refuse))
.map(|period| Self::Period(Box::new(period))),
FhirKind::Reference => object(value, element, kind)
.and_then(|object| Reference::from_json(object, &mut path).map_err(refuse))
.map(|reference| Self::Reference(Box::new(reference))),
FhirKind::Identifier => object(value, element, kind)
.and_then(|object| Identifier::from_json(object, &mut path).map_err(refuse))
.map(|identifier| Self::Identifier(Box::new(identifier))),
FhirKind::Quantity => object(value, element, kind)
.and_then(|object| Quantity::from_json(object, &mut path).map_err(refuse))
.map(|quantity| Self::Quantity(Box::new(quantity))),
FhirKind::Integer => Integer::from_json_parts(Some(value), None, &mut path)
.map(Self::Integer)
.map_err(refuse),
FhirKind::UnsignedInt => UnsignedInt::from_json_parts(Some(value), None, &mut path)
.map(Self::UnsignedInt)
.map_err(refuse),
FhirKind::PositiveInt => PositiveInt::from_json_parts(Some(value), None, &mut path)
.map(Self::PositiveInt)
.map_err(refuse),
FhirKind::Decimal => Decimal::from_json_parts(Some(value), None, &mut path)
.map(Self::Decimal)
.map_err(refuse),
FhirKind::Count => object(value, element, kind)
.and_then(|object| Count::from_json(object, &mut path).map_err(refuse))
.map(|count| Self::Count(Box::new(count))),
FhirKind::Time => Time::from_json_parts(Some(value), None, &mut path)
.map(Self::Time)
.map_err(refuse),
FhirKind::Duration => object(value, element, kind)
.and_then(|object| Duration::from_json(object, &mut path).map_err(refuse))
.map(|duration| Self::Duration(Box::new(duration))),
FhirKind::Url => Url::from_json_parts(Some(value), None, &mut path)
.map(Self::Url)
.map_err(refuse),
FhirKind::Attachment => object(value, element, kind)
.and_then(|object| Attachment::from_json(object, &mut path).map_err(refuse))
.map(|attachment| Self::Attachment(Box::new(attachment))),
FhirKind::Range => object(value, element, kind)
.and_then(|object| Range::from_json(object, &mut path).map_err(refuse))
.map(|range| Self::Range(Box::new(range))),
}
}
pub fn write(&self, element: &str) -> Result<Value, FhirError> {
let kind = self.kind().as_str();
let complex = |result: Result<fhir_types::codec::Object, EncodeError>| {
result
.map(Value::Object)
.map_err(|source| FhirError::Encode { kind, source })
};
let primitive = |result: Result<Option<Value>, EncodeError>| {
result
.map_err(|source| FhirError::Encode { kind, source })?
.ok_or_else(|| FhirError::NoValue {
element: String::from(element),
kind,
})
};
match *self {
Self::String(ref text) => primitive(text.value_json()),
Self::Date(ref date) => primitive(date.value_json()),
Self::DateTime(ref date) => primitive(date.value_json()),
Self::Instant(ref instant) => primitive(instant.value_json()),
Self::Boolean(ref boolean) => primitive(boolean.value_json()),
Self::Coding(ref coding) => complex(coding.to_json()),
Self::CodeableConcept(ref concept) => complex(concept.to_json()),
Self::Period(ref period) => complex(period.to_json()),
Self::Reference(ref reference) => complex(reference.to_json()),
Self::Identifier(ref identifier) => complex(identifier.to_json()),
Self::Quantity(ref quantity) => complex(quantity.to_json()),
Self::Integer(ref integer) => primitive(integer.value_json()),
Self::UnsignedInt(ref integer) => primitive(integer.value_json()),
Self::PositiveInt(ref integer) => primitive(integer.value_json()),
Self::Decimal(ref decimal) => primitive(decimal.value_json()),
Self::Count(ref count) => complex(count.to_json()),
Self::Time(ref time) => primitive(time.value_json()),
Self::Duration(ref duration) => complex(duration.to_json()),
Self::Url(ref url) => primitive(url.value_json()),
Self::Attachment(ref attachment) => complex(attachment.to_json()),
Self::Range(ref range) => complex(range.to_json()),
}
}
}
fn object<'tree>(
value: &'tree Value,
element: &str,
kind: FhirKind,
) -> Result<&'tree fhir_types::codec::Object, FhirError> {
let path = Path::root(element);
fhir_types::codec::expect_object(value, &path).map_err(|source| FhirError::Decode {
element: String::from(element),
kind: kind.as_str(),
source,
})
}
#[cfg(test)]
mod tests {
use super::FhirKind;
use super::FhirValue;
use fhir_types::codec::Value;
#[test]
fn a_coding_reads_and_writes_through_the_generated_codec() {
let document = Value::from_serde_json(serde_json::json!({
"system": "http://example.org/fhir/CodeSystem/synthetic-problems",
"code": "SYN-001"
}));
let value = FhirValue::read(FhirKind::Coding, "Condition.code.coding", &document)
.expect("the object reads as a Coding");
assert_eq!(value.kind(), FhirKind::Coding);
let written = value
.write("Condition.code.coding")
.expect("a Coding has a JSON form");
assert_eq!(written, document, "the codec round trips the element");
}
#[test]
fn a_date_time_keeps_the_text_the_document_carried() {
let document = Value::String(String::from("2026-09-13T10:00:00.123456+02:00"));
let value = FhirValue::read(FhirKind::DateTime, "Condition.recordedDate", &document)
.expect("the string reads as a dateTime");
assert_eq!(
value
.write("Condition.recordedDate")
.expect("a dateTime has a JSON form"),
document,
"the fractional seconds and the offset survive"
);
}
#[test]
fn an_instant_keeps_the_text_the_document_carried() {
let document = Value::String(String::from("2026-09-13T10:00:00.123+02:00"));
let value = FhirValue::read(FhirKind::Instant, "Observation.issued", &document)
.expect("the string reads as an instant");
assert_eq!(value.kind(), FhirKind::Instant);
assert_eq!(value.kind().as_str(), "instant");
assert_eq!(
value
.write("Observation.issued")
.expect("an instant has a JSON form"),
document,
"the fractional seconds and the offset survive"
);
}
#[test]
fn a_date_short_of_an_instant_names_the_element_and_the_kind() {
let document = Value::String(String::from("2026-09-13"));
let error = FhirValue::read(FhirKind::Instant, "Observation.issued", &document)
.expect_err("a date is no instant");
let message = error.to_string();
assert!(message.contains("Observation.issued"), "{message}");
assert!(message.contains("instant"), "{message}");
}
#[test]
fn every_pair_the_resolver_derives_names_a_kind_the_cells_carry() {
for &(class, codes) in crate::resolve::derive::PAIRS {
for code in codes {
assert!(
FhirKind::of_code(code).is_some(),
"{class} pairs with {code}, which no kind carries"
);
}
}
assert_eq!(
FhirKind::of_code(crate::resolve::derive::TEXT),
Some(FhirKind::String)
);
}
#[test]
fn a_value_of_the_wrong_shape_names_the_element() {
let document = Value::String(String::from("not an object"));
let error = FhirValue::read(FhirKind::Coding, "Condition.code.coding", &document)
.expect_err("a string is no Coding");
assert!(
error.to_string().contains("Condition.code.coding"),
"the refusal names the element: {error}"
);
}
}