fig 7.0.0

Parse, edit, and convert config files while preserving comments. Supports JSON, YAML, TOML, and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use std::fmt;

use crate::Format;
use crate::capi::{self, Status};

/// Errors produced while parsing, serializing, or deserializing.
///
/// Implements [`std::error::Error`], and (with the `serde` feature)
/// [`serde::de::Error`]/[`serde::ser::Error`] so it can flow through serde.
///
/// `#[non_exhaustive]`: new failure modes get their own variant as the core grows
/// them, so a `match` needs a `_` arm (or an `Err(e) => …` catch-all). The struct
/// variants are non-exhaustive too, so a pattern on one takes `..`; the derive
/// macros build them through the constructors below ([`Error::missing_field`]
/// and the rest), which is also how a hand-written `FromValue` impl does.
///
/// `NotFound` carries no path. The core's status says only that something on
/// the way was missing, not which segment, so the one path the binding could
/// attach is the one the caller just passed.
#[derive(Debug)]
// `Number` is only constructed on the serde paths.
#[cfg_attr(not(feature = "serde"), allow(dead_code))]
#[non_exhaustive]
pub enum Error {
    /// A null or otherwise invalid argument reached the C ABI.
    InvalidArgument,
    /// The input could not be parsed as the requested format. Carries a
    /// [`ParseError`] with the core's message and (when known) source location.
    Parse(ParseError),
    /// Allocation failed inside the parser.
    OutOfMemory,
    /// The requested format is not supported.
    UnsupportedFormat,
    /// The operation is not defined for these arguments, though each argument
    /// is individually valid — distinct from [`Error::InvalidArgument`] (a
    /// malformed call). Returned, for instance, by
    /// [`Editor::uncomment_leading`](crate::Editor::uncomment_leading) when
    /// the lines turn out not to be an entry.
    UnsupportedOperation,
    /// A path or key was not found.
    NotFound,
    /// An unexpected internal error occurred.
    Internal,
    /// A scalar's bytes were not valid UTF-8.
    Utf8,
    /// A numeric scalar could not be parsed (message holds the raw text).
    Number(String),
    /// An error with no structure of its own: a serde-level or derive-level
    /// one, e.g. a type mismatch reported by a `Deserialize` impl, or a
    /// derived enum's fixed "expected a string or a mapping"; or a value the
    /// target format has no way to write, e.g. an infinite float into JSON.
    Message(String),
    /// A required field was absent while building a derived `FromValue` type.
    ///
    /// Both parts are compile-time `&'static str`s, so constructing this is
    /// allocation-free and the message text is assembled lazily in `Display`
    /// rather than `format!`-ed at every derived call site.
    #[non_exhaustive]
    MissingField {
        field: &'static str,
        ty: &'static str,
    },
    /// A derived `FromValue` impl expected a mapping but found another kind.
    #[non_exhaustive]
    ExpectedMapping { ty: &'static str },
    /// A derived enum `FromValue` impl saw a variant/tag it doesn't recognize.
    /// `got` is the (runtime) text that didn't match any known variant.
    #[non_exhaustive]
    UnknownVariant {
        enum_name: &'static str,
        got: String,
    },
    /// A derived tuple-variant `FromValue` impl got the wrong element count.
    #[non_exhaustive]
    WrongSeqLen {
        label: &'static str,
        expected: usize,
        got: usize,
    },
    /// A primitive conversion expected one kind of value but found another.
    /// `found` is one of the `&'static str` kind names from `kind_of`.
    #[non_exhaustive]
    TypeMismatch {
        expected: &'static str,
        found: &'static str,
    },
    /// An integer value was outside the range of the target type. Only the
    /// target type name is kept (a `&'static str`) — deliberately *not* the
    /// offending value, since an `i128` payload would force 16-byte alignment
    /// on the whole `Error` enum and bloat every `Result<_, Error>` site.
    #[non_exhaustive]
    IntOutOfRange { ty: &'static str },
    /// A runtime language was refused by [`language::register`](crate::language::register):
    /// the reason, as the core gave it, and where when it names a place.
    Language(LanguageFailure),
    /// Reading the input or writing the output failed, in a language
    /// crate's `from_reader` or `to_writer`.
    Io(std::io::Error),
    /// Building a typed value failed below the document's root: `path` says
    /// where, spelled as a [`Warning`](crate::Warning)'s path is
    /// (`servers[0].port`), and `error` is what failed there, never itself
    /// an `At`. [`Error::path`] and [`Error::innermost`] read it from any
    /// error, so a caller can ask what failed whether or not it was nested.
    #[non_exhaustive]
    At { path: String, error: Box<Error> },
}

/// Why a runtime language was refused, from [`Error::Language`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LanguageFailure {
    /// The core's reason — the rule the description broke, the sample that
    /// failed and how, or the name already taken.
    pub message: String,
    /// A byte offset into the text the failure is about, when the failure
    /// names one: the position of the NUL in a declared string that has
    /// one. `None` otherwise, including every refusal the core reports
    /// today, which says which sample failed but not where in it.
    pub byte_offset: Option<usize>,
}

impl fmt::Display for LanguageFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.byte_offset {
            Some(off) => write!(f, "{} (byte offset {off})", self.message),
            None => f.write_str(&self.message),
        }
    }
}

impl std::error::Error for LanguageFailure {}

/// Details of a parse failure, projected from the C ABI's `FigError`.
///
/// Its `Display` is the error's whole sentence, which [`Error::Parse`] prints
/// as is: `failed to parse input: <message>` for the core's diagnostic, or
/// the message alone when it is already a sentence of its own (an edit the
/// document refused, a parse failure the core gave no detail for).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ParseError {
    /// A human-readable message: what the language's parser gave.
    pub message: String,
    /// Byte offset of the failure within the input, when the language
    /// reports one. An offset of 0 is indistinguishable from "unknown" at the
    /// C ABI and also reads as `None`.
    pub byte_offset: Option<usize>,
    /// 1-based line of the failure, when known (see `byte_offset`).
    pub line: Option<u32>,
    /// 1-based column of the failure, when known (see `byte_offset`).
    pub column: Option<u32>,
    /// `message` is the whole sentence, not a detail to follow
    /// `failed to parse input: `.
    sentence: bool,
}

impl ParseError {
    /// Build from a filled `FigError`. `byte_offset`/`line`/`column` of 0 are the
    /// ABI's "unknown" sentinel and map to `None`. The message is read as
    /// lossy UTF-8.
    pub(crate) fn from_core(e: &capi::FigError) -> Self {
        let message = String::from_utf8_lossy(&e.message).into_owned();
        ParseError {
            message,
            byte_offset: (e.byte_offset != 0).then_some(e.byte_offset),
            line: (e.line != 0).then_some(e.line),
            column: (e.column != 0).then_some(e.column),
            sentence: false,
        }
    }

    /// A detail-free parse error for paths that have no `FigError` (a bare
    /// `PARSE_ERROR` status). Its message is the whole sentence, so it prints
    /// once: it used to be the same words `Display` puts in front of a
    /// message, and read `failed to parse input: failed to parse input`.
    pub(crate) fn generic() -> Self {
        Self::sentence(String::from("failed to parse input"))
    }

    /// An edit the editor refused because the document would no longer parse
    /// as `format` with it applied. fig knows no more than that — the core
    /// reports a bare status — so this says which part of the request did it.
    pub(crate) fn refused_edit(format: Format, what: EditTarget) -> Self {
        let name = format.name();
        Self::sentence(match what {
            EditTarget::Value => format!("the new value would not parse as {name}"),
            EditTarget::Key => format!("the new key would not parse as {name}"),
            EditTarget::Comment => format!("the new comment would not parse as {name}"),
            EditTarget::Document => format!("the edited document would not parse as {name}"),
        })
    }

    fn sentence(message: String) -> Self {
        ParseError {
            message,
            byte_offset: None,
            line: None,
            column: None,
            sentence: true,
        }
    }
}

/// What part of an edit request was new text, for the sentence a refused
/// edit reads as (see [`ParseError::refused_edit`]).
#[derive(Clone, Copy, Debug)]
pub(crate) enum EditTarget {
    /// A value, item list or container body the caller supplied.
    Value,
    /// A renamed key or container.
    Key,
    /// A comment's text.
    Comment,
    /// A structural edit (delete, move, reorder) that supplied no text.
    Document,
}

/// An editor call's status as a `Result`: a `PARSE_ERROR` is the edit's own
/// refusal, said in a sentence (see [`ParseError::refused_edit`]), and every
/// other status folds as [`Error::from_status`] folds it.
pub(crate) fn edit_status(
    status: Result<(), Status>,
    format: Format,
    what: EditTarget,
) -> Result<(), Error> {
    match status {
        Ok(()) => Ok(()),
        Err(Status::ParseError) => Err(Error::Parse(ParseError::refused_edit(format, what))),
        Err(status) => Error::from_status(status),
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.sentence {
            f.write_str(&self.message)?;
        } else {
            write!(f, "failed to parse input: {}", self.message)?;
        }
        match (self.line, self.column) {
            (Some(l), Some(c)) => write!(f, " (line {l}, column {c})"),
            _ => match self.byte_offset {
                Some(off) => write!(f, " (byte offset {off})"),
                None => Ok(()),
            },
        }
    }
}

impl std::error::Error for ParseError {}

impl Error {
    /// `#[cold]`/`#[inline(never)]` constructors keep derived `from_value`
    /// bodies tiny: the error-building code lives here (compiled once) instead
    /// of being inlined — with `format!`/`String` machinery — at every field,
    /// variant, and tag site across the whole dependency graph.
    #[cold]
    #[inline(never)]
    pub fn missing_field(field: &'static str, ty: &'static str) -> Self {
        Error::MissingField { field, ty }
    }

    #[cold]
    #[inline(never)]
    pub fn expected_mapping(ty: &'static str) -> Self {
        Error::ExpectedMapping { ty }
    }

    #[cold]
    #[inline(never)]
    pub fn unknown_variant(enum_name: &'static str, got: &str) -> Self {
        Error::UnknownVariant {
            enum_name,
            got: got.to_string(),
        }
    }

    #[cold]
    #[inline(never)]
    pub fn wrong_seq_len(label: &'static str, expected: usize, got: usize) -> Self {
        Error::WrongSeqLen {
            label,
            expected,
            got,
        }
    }

    /// A [`Error::Message`] from a compile-time string — the derive macros'
    /// constructor for their fixed messages. Cold and out of line, so the
    /// allocation is compiled once here rather than at every derived site.
    #[cold]
    #[inline(never)]
    pub fn msg_static(msg: &'static str) -> Self {
        Error::Message(msg.to_owned())
    }

    #[cold]
    #[inline(never)]
    pub fn type_mismatch(expected: &'static str, found: &'static str) -> Self {
        Error::TypeMismatch { expected, found }
    }

    #[cold]
    #[inline(never)]
    pub fn int_out_of_range(ty: &'static str) -> Self {
        Error::IntOutOfRange { ty }
    }

    pub(crate) fn from_status(status: Status) -> Result<(), Self> {
        match status {
            Status::Ok => Ok(()),
            Status::InvalidArgument => Err(Self::InvalidArgument),
            Status::ParseError => Err(Self::Parse(ParseError::generic())),
            Status::OutOfMemory => Err(Self::OutOfMemory),
            Status::UnsupportedFormat => Err(Self::UnsupportedFormat),
            Status::UnsupportedOperation => Err(Self::UnsupportedOperation),
            Status::NotFound => Err(Self::NotFound),
            // `InternalError` folds into `Internal`.
            Status::InternalError => Err(Self::Internal),
        }
    }

    /// A core call's answer as a `Result`, its status folded as
    /// [`Error::from_status`] folds it.
    pub(crate) fn check<T>(r: Result<T, Status>) -> Result<T, Self> {
        r.map_err(|status| Self::from_status(status).err().unwrap_or(Self::Internal))
    }

    /// A failure the core reported with what `FigError` carries: a parse
    /// error with its message and location, any other status as
    /// [`Error::from_status`] folds it.
    pub(crate) fn from_fig_error(e: &capi::FigError) -> Self {
        if e.code == Status::ParseError {
            return Self::Parse(ParseError::from_core(e));
        }
        Self::from_status(e.code).err().unwrap_or(Self::Internal)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::InvalidArgument => f.write_str("invalid argument"),
            Error::Parse(e) => write!(f, "{e}"),
            Error::OutOfMemory => f.write_str("out of memory"),
            Error::UnsupportedFormat => f.write_str("unsupported format"),
            Error::UnsupportedOperation => f.write_str("unsupported operation"),
            Error::NotFound => f.write_str("path or region not found"),
            Error::Internal => f.write_str("internal error"),
            Error::Language(failure) => write!(f, "runtime language: {failure}"),
            Error::Utf8 => f.write_str("scalar was not valid UTF-8"),
            Error::Number(raw) => write!(f, "invalid number: {raw}"),
            Error::Message(msg) => f.write_str(msg),
            Error::MissingField { field, ty } => {
                write!(f, "missing field `{field}` while building `{ty}`")
            }
            Error::ExpectedMapping { ty } => write!(f, "expected a mapping to build `{ty}`"),
            Error::UnknownVariant { enum_name, got } => {
                write!(f, "unknown variant `{got}` for enum `{enum_name}`")
            }
            Error::WrongSeqLen {
                label,
                expected,
                got,
            } => {
                write!(
                    f,
                    "expected {expected} element(s) for `{label}`, found {got}"
                )
            }
            Error::TypeMismatch { expected, found } => {
                write!(f, "expected {expected}, found {found}")
            }
            Error::IntOutOfRange { ty } => {
                write!(f, "integer out of range for {ty}")
            }
            Error::Io(e) => write!(f, "{e}"),
            Error::At { path, error } => write!(f, "{path}: {error}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Parse(e) => Some(e),
            Error::Language(e) => Some(e),
            Error::Io(e) => Some(e),
            Error::At { error, .. } => Some(&**error),
            _ => None,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

impl Error {
    /// Where in the document a typed value failed to build, as
    /// [`Error::At`] spells it (`servers[0].port`), or `None` for an error
    /// at the root or one that is not about a value at all.
    pub fn path(&self) -> Option<&str> {
        match self {
            Error::At { path, .. } => Some(path),
            _ => None,
        }
    }

    /// What failed, beneath the location an [`Error::At`] adds: the error
    /// itself for any other variant. Match on this to ask what went wrong
    /// whether or not it happened below the root.
    pub fn innermost(&self) -> &Error {
        match self {
            Error::At { error, .. } => error,
            other => other,
        }
    }

    /// This error, as having happened under the mapping key `key`. Used by
    /// the `FromValue` impls, `#[derive(FromValue)]` and the serde reader as
    /// each returns from a level of the document.
    #[doc(hidden)]
    #[cold]
    pub fn at_key(self, key: &str) -> Self {
        self.prefixed(key)
    }

    /// This error, as having happened under sequence item `index`.
    #[doc(hidden)]
    #[cold]
    pub fn at_index(self, index: usize) -> Self {
        self.prefixed(&format!("[{index}]"))
    }

    fn prefixed(self, segment: &str) -> Self {
        match self {
            Error::At { path, error } => {
                // An index runs on (`a[0]`); a key after anything is dotted.
                let sep = if path.starts_with('[') { "" } else { "." };
                Error::At {
                    path: format!("{segment}{sep}{path}"),
                    error,
                }
            }
            // Where a document failed to parse, or could not be read at all,
            // is not a place in a value.
            e @ (Error::Parse(_) | Error::Io(_) | Error::Language(_)) => e,
            other => Error::At {
                path: segment.to_string(),
                error: Box::new(other),
            },
        }
    }
}

#[cfg(feature = "serde")]
impl serde::de::Error for Error {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        Error::Message(msg.to_string())
    }
}

#[cfg(feature = "serde")]
impl serde::ser::Error for Error {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        Error::Message(msg.to_string())
    }
}