extern crate self as fig;
mod diagnostics;
mod editor;
mod error;
mod language_crate;
mod value;
pub(crate) use fig_core::api as capi;
#[cfg(feature = "derive")]
mod convert;
#[cfg(feature = "serde")]
mod de;
#[cfg(feature = "serde")]
mod ser;
use std::os::raw::c_int;
pub use diagnostics::{Warning, WarningCause, WarningCode};
pub use editor::{Editor, Segment};
#[cfg(feature = "helper")]
pub mod helper;
pub mod kit;
pub mod language;
#[cfg(test)]
mod test_languages;
pub use error::{Error, LanguageFailure, ParseError};
pub use value::{ExtKind, Value};
#[cfg(feature = "derive")]
pub use convert::{FromValue, ToValue};
#[cfg(feature = "derive")]
#[doc(hidden)]
pub use convert::{field, field_or_default, map_get};
#[cfg(feature = "derive")]
pub use fig_macros::{FromValue, ToValue};
#[cfg(feature = "serde")]
pub use de::from_slice;
#[cfg(feature = "serde")]
pub use ser::to_value;
pub(crate) type FigNodeId = fig_core::kit::ast::NodeId;
pub(crate) use capi::{FigNodeKind, NODE_NONE as FIG_NODE_NONE};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct Span {
pub start: usize,
pub end: usize,
}
impl From<std::ops::Range<usize>> for Span {
fn from(r: std::ops::Range<usize>) -> Self {
Span {
start: r.start,
end: r.end,
}
}
}
impl From<Span> for std::ops::Range<usize> {
fn from(s: Span) -> Self {
s.start..s.end
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Format(c_int);
impl Format {
pub(crate) fn to_c(self) -> c_int {
self.0
}
pub(crate) fn from_c(value: c_int) -> Option<Format> {
if value <= 0 || capi::format_name(value).is_none() {
return None;
}
Some(Format(value))
}
pub fn by_name(name: &str) -> Option<Format> {
if name.contains('\0') {
return None;
}
let value = capi::format_by_name(name);
if value <= 0 {
return None;
}
Some(Format(value))
}
pub fn name(self) -> &'static str {
format_name_static(self.0)
}
pub fn split_stream(self, input: &[u8]) -> Result<Vec<language::StreamDocument>, Error> {
match capi::stream_split(input, self.to_c()) {
Ok(docs) => Ok(docs
.into_iter()
.map(|d| language::StreamDocument {
start: d.start,
end: d.end,
explicit: d.marked,
})
.collect()),
Err(e) => Err(Error::from_fig_error(&e)),
}
}
pub fn detect(input: &[u8], order: &[&str]) -> Option<Format> {
let names: Vec<&str> = order.iter().copied().filter(|n| !n.contains('\0')).collect();
let out = capi::detect_order(input, &names).ok()?;
Format::from_c(out)
}
}
fn format_name_static(abi: c_int) -> &'static str {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
static NAMES: OnceLock<Mutex<HashMap<c_int, &'static str>>> = OnceLock::new();
let names = NAMES.get_or_init(|| Mutex::new(HashMap::new()));
let mut names = names.lock().unwrap_or_else(|p| p.into_inner());
if let Some(name) = names.get(&abi) {
return name;
}
let Some(name) = capi::format_name(abi) else {
return "";
};
let name: &'static str = Box::leak(name.into_boxed_str());
names.insert(abi, name);
name
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct SerializeOptions {
pub pretty: bool,
pub indent: u8,
pub strip_comments: bool,
pub lossless: bool,
pub width: u16,
}
impl Default for SerializeOptions {
fn default() -> Self {
Self {
pretty: true,
indent: 2,
strip_comments: false,
lossless: false,
width: 80,
}
}
}
impl SerializeOptions {
pub fn compact() -> Self {
Self {
pretty: false,
..Self::default()
}
}
pub fn pretty(indent: u8) -> Self {
Self {
pretty: true,
indent,
..Self::default()
}
}
pub fn indent(self, indent: u8) -> Self {
Self { indent, ..self }
}
pub fn lossless(self) -> Self {
Self {
lossless: true,
..self
}
}
pub fn strip_comments(self) -> Self {
Self {
strip_comments: true,
..self
}
}
pub fn width(self, width: u16) -> Self {
Self { width, ..self }
}
}
impl From<SerializeOptions> for capi::FigSerializeOptions {
fn from(o: SerializeOptions) -> Self {
capi::FigSerializeOptions {
pretty: o.pretty,
indent: o.indent,
strip_comments: o.strip_comments,
lossless: o.lossless,
width: o.width,
flow: false,
splice: false,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Version {
pub major: u8,
pub minor: u8,
pub patch: u8,
}
pub fn version() -> Version {
let packed = capi::version();
Version {
major: (packed >> 16) as u8,
minor: (packed >> 8) as u8,
patch: packed as u8,
}
}
pub fn version_string() -> &'static str {
capi::version_string()
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Capabilities {
pub read: bool,
pub edit: bool,
pub serialize: bool,
pub references: bool,
}
impl Capabilities {
pub const fn new(read: bool, edit: bool, serialize: bool) -> Self {
Capabilities {
read,
edit,
serialize,
references: false,
}
}
pub const fn with_references(mut self, references: bool) -> Self {
self.references = references;
self
}
}
pub fn capabilities(format: Format) -> Capabilities {
let bits = capi::format_capabilities(format.to_c());
Capabilities {
read: bits & (1 << 0) != 0,
edit: bits & (1 << 1) != 0,
serialize: bits & (1 << 2) != 0,
references: bits & (1 << 3) != 0,
}
}
#[derive(Debug)]
pub struct Document {
inner: capi::Document,
}
impl Document {
pub fn parse(input: &[u8], format: Format) -> Result<Self, Error> {
match capi::Document::parse_ex(input, format.to_c()) {
Ok(inner) => Ok(Self { inner }),
Err(e) => Err(Error::from_fig_error(&e)),
}
}
}
impl Document {
pub fn to_value(&self) -> Result<Value, Error> {
let resolved = self.resolve_aliases()?;
let doc = resolved.as_ref().unwrap_or(self);
match doc.root() {
None => Ok(Value::Null),
Some(id) => doc.node_to_value(id),
}
}
pub(crate) fn resolve_aliases(&self) -> Result<Option<Document>, Error> {
match self.inner.resolve_aliases() {
Ok(resolved) => Ok(resolved.map(|inner| Document { inner })),
Err(e) => Err(Error::from_fig_error(&e)),
}
}
fn node_to_value(&self, id: FigNodeId) -> Result<Value, Error> {
if let Some((kind, text)) = self.extended(id) {
return Ok(Value::Extended { kind, text });
}
let kind = self.kind(id);
match kind {
FigNodeKind::Null => Ok(Value::Null),
FigNodeKind::Bool => Ok(Value::Bool(self.get_bool(id).ok_or(Error::Internal)?)),
FigNodeKind::Int | FigNodeKind::Float => {
let raw = self.number_raw(id).ok_or(Error::Internal)??;
Value::parse_number(raw, kind == FigNodeKind::Float)
}
FigNodeKind::String => Ok(Value::Str(
self.get_str(id).ok_or(Error::Internal)??.to_owned(),
)),
FigNodeKind::Sequence => {
let mut items = Vec::with_capacity(self.child_count(id));
let mut next = self.first_child(id);
while let Some(child) = next {
items.push(self.node_to_value(child)?);
next = self.next_sibling(child);
}
Ok(Value::Seq(items))
}
FigNodeKind::Mapping => {
let mut entries = Vec::with_capacity(self.child_count(id));
let mut next = self.first_child(id);
while let Some(kv) = next {
let key = self.kv_key(kv).ok_or(Error::Internal)?;
let value = match self.kv_value(kv) {
Some(vid) => self.node_to_value(vid)?,
None => Value::Null,
};
entries.push((self.node_to_value(key)?, value));
next = self.next_sibling(kv);
}
Ok(Value::Map(entries))
}
FigNodeKind::KeyValue
| FigNodeKind::Invalid
| FigNodeKind::Alias
| FigNodeKind::Extended => Err(Error::Internal),
}
}
pub(crate) fn root(&self) -> Option<FigNodeId> {
normalize(self.inner.root())
}
pub(crate) fn kind(&self, node: FigNodeId) -> FigNodeKind {
match self.inner.node_kind(node) {
FigNodeKind::Extended => match self.extended(node) {
Some((ExtKind::CharLiteral, _)) => FigNodeKind::Int,
_ => FigNodeKind::String,
},
k => k,
}
}
pub(crate) fn first_child(&self, node: FigNodeId) -> Option<FigNodeId> {
normalize(self.inner.first_child(node))
}
pub(crate) fn next_sibling(&self, node: FigNodeId) -> Option<FigNodeId> {
normalize(self.inner.next_sibling(node))
}
pub(crate) fn child_count(&self, node: FigNodeId) -> usize {
self.inner.child_count(node)
}
pub(crate) fn kv_key(&self, node: FigNodeId) -> Option<FigNodeId> {
normalize(self.inner.keyvalue_key(node))
}
pub(crate) fn kv_value(&self, node: FigNodeId) -> Option<FigNodeId> {
normalize(self.inner.keyvalue_value(node))
}
pub(crate) fn get_bool(&self, node: FigNodeId) -> Option<bool> {
self.inner.node_bool(node)
}
pub(crate) fn number_raw(&self, node: FigNodeId) -> Option<Result<&str, Error>> {
self.inner
.node_number(node)
.map(|bytes| std::str::from_utf8(bytes).map_err(|_| Error::Utf8))
}
pub(crate) fn get_str(&self, node: FigNodeId) -> Option<Result<&str, Error>> {
self.inner
.node_string(node)
.map(|bytes| std::str::from_utf8(bytes).map_err(|_| Error::Utf8))
}
pub(crate) fn extended(&self, node: FigNodeId) -> Option<(ExtKind, String)> {
let (kind, bytes) = self.inner.node_extended(node)?;
let ext = ExtKind::from_c(c_int::from(kind.ordinal()))?;
let text = std::str::from_utf8(bytes).ok()?.to_owned();
Some((ext, text))
}
}
impl Document {
pub fn serialize(&self, format: Format) -> Result<String, Error> {
self.serialize_with(format, SerializeOptions::default())
}
pub fn serialize_with(
&self,
format: Format,
options: SerializeOptions,
) -> Result<String, Error> {
let core_options: capi::FigSerializeOptions = options.into();
let bytes = Error::check(self.inner.serialize_to_vec(format.to_c(), Some(&core_options)))?;
String::from_utf8(bytes).map_err(|_| Error::Utf8)
}
pub fn diagnose(
&self,
format: Format,
options: SerializeOptions,
) -> Result<Vec<Warning>, Error> {
let core_options: capi::FigSerializeOptions = options.into();
let warnings = Error::check(self.inner.diagnose_to_vec(format.to_c(), Some(&core_options)))?;
Ok(warnings.iter().map(Warning::from_core).collect())
}
}
fn normalize(id: FigNodeId) -> Option<FigNodeId> {
if id == FIG_NODE_NONE { None } else { Some(id) }
}
#[cfg(test)]
mod tests {
use super::{Document, Error};
use crate::test_languages::by_name;
#[test]
fn parses_json_document() {
let doc = Document::parse(br#"{"name":"fig","ok":true}"#, by_name("json"));
assert!(doc.is_ok());
}
#[test]
fn parse_error_is_reported() {
let err = Document::parse(br#"{"name":"fig""#, by_name("json")).unwrap_err();
let Error::Parse(detail) = &err else {
panic!("expected Error::Parse, got {err:?}");
};
assert!(!detail.message.is_empty());
assert_eq!(detail.byte_offset, Some(13));
}
#[test]
fn version_and_capabilities() {
use super::{capabilities, version, version_string};
let v = version();
assert_eq!(
version_string(),
format!("{}.{}.{}", v.major, v.minor, v.patch)
);
let json = capabilities(by_name("json"));
assert!(json.read && json.edit && json.serialize);
}
#[test]
fn document_serialize_converts_cross_format() {
let doc = Document::parse(b"name: fig\nnums:\n- 1\n- 2\n", by_name("yaml")).unwrap();
assert_eq!(
doc.serialize(by_name("json")).unwrap(),
"{\n \"name\": \"fig\",\n \"nums\": [\n 1,\n 2\n ]\n}\n",
);
}
#[test]
fn document_diagnose_reports_dropped_null() {
use super::{SerializeOptions, WarningCause, WarningCode};
let doc = Document::parse(b"a: null\nb: 1\n", by_name("yaml")).unwrap();
let warns = doc
.diagnose(by_name("toml"), SerializeOptions::default())
.unwrap();
assert_eq!(warns.len(), 1);
assert_eq!(warns[0].code, WarningCode::ValueDropped);
assert_eq!(warns[0].cause, WarningCause::FormatLimitation);
assert_eq!(warns[0].path, "a");
let none = doc
.diagnose(by_name("toml"), SerializeOptions::default().lossless())
.unwrap();
assert!(none.is_empty());
}
#[test]
fn parse_error_message_is_surfaced_in_display() {
let err = Document::parse(br#"{"name":"fig""#, by_name("json")).unwrap_err();
assert!(err.to_string().starts_with("failed to parse input: "));
}
#[test]
fn editor_comment_ops_add_set_and_delete() {
use super::{Editor, Segment};
let mut ed = Editor::open(b"a: 1\nb: 2\n", by_name("yaml")).unwrap();
ed.add_leading_comment(&[Segment::Key("b")], "why").unwrap();
ed.set_trailing_comment(&[Segment::Key("b")], "two")
.unwrap();
assert_eq!(ed.source().unwrap(), "a: 1\n# why\nb: 2 # two\n");
ed.delete_trailing_comment(&[Segment::Key("b")]).unwrap();
ed.delete_leading_comment(&[Segment::Key("b")]).unwrap();
assert_eq!(ed.source().unwrap(), "a: 1\nb: 2\n");
}
#[test]
fn editor_comments_unsupported_in_strict_json() {
use super::{Editor, Error, Segment};
let mut ed = Editor::open(br#"{"a":1}"#, by_name("json")).unwrap();
assert!(matches!(
ed.add_leading_comment(&[Segment::Key("a")], "x"),
Err(Error::UnsupportedFormat)
));
}
}