Skip to main content

yomi_core/
decls.rs

1//! Writing and reading declaration files (JSON) (section 2.8 of `spec/host/02-registry.md`).
2//!
3//! JSON is read and written with `serde_json`. Reading has limits on the size of the input ([`MAX_DECLS_BYTES`]) and the
4//! nesting depth ([`MAX_JSON_DEPTH`]), and does not panic on broken or huge input.
5
6mod convert;
7mod json;
8mod ty;
9
10use convert::*;
11use json::*;
12use ty::*;
13
14use std::collections::HashMap;
15use std::sync::Arc;
16
17use crate::package::{CommandError, Env, PackageEntry};
18use crate::registry::{CommandKind, Kind, NativeKind, Registry, RegistryError, Sugar};
19use crate::value::{Identity, MAX_TYPE_DEPTH, Ty, TypeDecl, TypeKind, Value, VariantDecl};
20
21/// The `format` of a declaration file.
22const FORMAT: &str = "yomi-decls";
23
24/// The version of the declaration file format that can be read.
25/// Format versions: version 2 added default values of command parameters (`params[].default`). Version 1 is also read
26/// (without defaults).
27const VERSION: i64 = 2;
28
29/// The maximum size of a declaration file to read (bytes).
30pub const MAX_DECLS_BYTES: usize = 16 * 1024 * 1024;
31
32/// The maximum nesting depth of JSON.
33pub const MAX_JSON_DEPTH: usize = 128;
34
35// ---------------------------------------------------------------------------
36// Errors
37// ---------------------------------------------------------------------------
38
39/// The reason a declaration file could not be read.
40#[non_exhaustive]
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum DeclErrorKind {
43    /// Cannot be read as JSON (positions are 1-based).
44    Syntax {
45        /// Line.
46        line: u32,
47        /// Column (in characters).
48        col: u32,
49    },
50    /// The input is too large ([`MAX_DECLS_BYTES`]).
51    TooLarge,
52    /// The JSON nesting is too deep ([`MAX_JSON_DEPTH`]), or the nesting of a type name is too deep.
53    TooDeep,
54    /// Not a declaration file (the whole is not an object, or `format` is not `"yomi-decls"`).
55    NotDecls,
56    /// A declaration file with a version that cannot be read.
57    UnsupportedVersion(i64),
58    /// A required item is missing.
59    MissingField,
60    /// The JSON type of an item does not match.
61    WrongType,
62    /// A type name is invalid (an unregistered type, or an unreadable notation). The value is the string as written.
63    InvalidType(String),
64    /// A value is invalid (an unknown `kind`, a `default` that does not match the type, and so on).
65    InvalidValue,
66    /// Invalid as a registry (colliding names, errors in type declarations, and so on).
67    Registry(RegistryError),
68}
69
70impl DeclErrorKind {
71    /// The stable English name.
72    pub fn code(&self) -> &'static str {
73        match self {
74            DeclErrorKind::Syntax { .. } => "syntax",
75            DeclErrorKind::TooLarge => "too_large",
76            DeclErrorKind::TooDeep => "too_deep",
77            DeclErrorKind::NotDecls => "not_decls",
78            DeclErrorKind::UnsupportedVersion(_) => "unsupported_version",
79            DeclErrorKind::MissingField => "missing_field",
80            DeclErrorKind::WrongType => "wrong_type",
81            DeclErrorKind::InvalidType(_) => "invalid_type",
82            DeclErrorKind::InvalidValue => "invalid_value",
83            DeclErrorKind::Registry(_) => "registry",
84        }
85    }
86}
87
88/// The error when a declaration file could not be read. Has no message text.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct DeclError {
91    /// Kind.
92    pub kind: DeclErrorKind,
93    /// Where the problem is (in the form `commands[3].params[0].type`; empty for the whole).
94    pub path: String,
95}
96
97impl std::fmt::Display for DeclError {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        write!(f, "{}", self.kind.code())?;
100        if !self.path.is_empty() {
101            write!(f, " at {}", self.path)?;
102        }
103        match &self.kind {
104            DeclErrorKind::Syntax { line, col } => write!(f, " ({line}:{col})"),
105            DeclErrorKind::UnsupportedVersion(v) => write!(f, " ({v})"),
106            DeclErrorKind::InvalidType(t) => write!(f, " ({t})"),
107            DeclErrorKind::Registry(e) => write!(f, " ({e})"),
108            _ => Ok(()),
109        }
110    }
111}
112
113impl std::error::Error for DeclError {}
114
115/// Makes a `DeclError` from the kind of error and the location (the JSON path).
116fn err(kind: DeclErrorKind, path: &str) -> DeclError {
117    DeclError {
118        kind,
119        path: path.to_string(),
120    }
121}
122
123// ---------------------------------------------------------------------------
124// Values and JSON (initial values of variables)
125// ---------------------------------------------------------------------------
126
127/// Adds a key or an index to a JSON path.
128fn join(path: &str, part: &str) -> String {
129    if path.is_empty() {
130        part.to_string()
131    } else if part.starts_with('[') {
132        format!("{path}{part}")
133    } else {
134        format!("{path}.{part}")
135    }
136}
137
138// ---------------------------------------------------------------------------
139// Writing
140// ---------------------------------------------------------------------------
141
142/// The name of a command kind in declaration files.
143fn kind_name(k: CommandKind) -> &'static str {
144    k.name()
145}
146
147impl Registry {
148    /// Writes the registry as a declaration file (JSON) (section 2.8 of `spec/host/02-registry.md`).
149    ///
150    /// Arrays are sorted by name in ascending order, so the same registry gives the same string. Tools (checking, the LSP,
151    /// `assign-ids`) read this with [`Registry::from_decls`] and can check scripts without the host's Rust code.
152    pub fn export_decls(&self) -> String {
153        let mut root: Vec<(String, Json)> = vec![
154            ("format".into(), s(FORMAT)),
155            ("version".into(), Json::from(VERSION)),
156        ];
157        // Packages
158        let mut packages: Vec<&PackageEntry> = self.packages.iter().collect();
159        packages.sort_by(|a, b| a.name.cmp(&b.name));
160        root.push((
161            "packages".into(),
162            Json::Array(
163                packages
164                    .iter()
165                    .map(|p| {
166                        let mut deps = p.depends.clone();
167                        deps.sort();
168                        let mut fields = vec![
169                            ("name".into(), s(&p.name)),
170                            ("version".into(), Json::from(p.version)),
171                            (
172                                "depends".into(),
173                                Json::Array(deps.iter().map(|d| s(d)).collect()),
174                            ),
175                        ];
176                        // Mark only the standard packages (others keep the same shape as before)
177                        if p.std {
178                            fields.push(("std".into(), Json::Bool(true)));
179                        }
180                        obj(fields)
181                    })
182                    .collect(),
183            ),
184        ));
185        // Commands
186        root.push((
187            "commands".into(),
188            Json::Array(
189                self.commands()
190                    .iter()
191                    .map(|c| {
192                        let mut o: Vec<(String, Json)> = vec![
193                            ("name".into(), s(&c.name)),
194                            ("kind".into(), s(kind_name(c.kind))),
195                        ];
196                        if let Some(p) = &c.package {
197                            o.push(("package".into(), s(p)));
198                        }
199                        o.push((
200                            "params".into(),
201                            Json::Array(
202                                c.args
203                                    .iter()
204                                    .zip(&c.params)
205                                    .zip(&c.defaults)
206                                    .map(|((t, n), d)| {
207                                        let mut p: Vec<(String, Json)> = Vec::new();
208                                        if let Some(n) = n {
209                                            p.push(("name".into(), s(n)));
210                                        }
211                                        p.push(("type".into(), s(&t.name())));
212                                        if let Some(d) = d {
213                                            p.push(("default".into(), value_json(d)));
214                                        }
215                                        obj(p)
216                                    })
217                                    .collect(),
218                            ),
219                        ));
220                        o.push((
221                            "returns".into(),
222                            if c.ret == Ty::Unit {
223                                Json::Null
224                            } else {
225                                s(&c.ret.name())
226                            },
227                        ));
228                        o.push((
229                            "aliases".into(),
230                            Json::Array(c.aliases.iter().map(|a| s(a)).collect()),
231                        ));
232                        if let Some(d) = &c.doc {
233                            o.push(("doc".into(), s(d)));
234                        }
235                        obj(o)
236                    })
237                    .collect(),
238            ),
239        ));
240        // Variables
241        let mut vars: Vec<&crate::registry::VarDecl> = self.vars.iter().collect();
242        vars.sort_by(|a, b| a.name.cmp(&b.name));
243        root.push((
244            "variables".into(),
245            Json::Array(
246                vars.iter()
247                    .map(|v| {
248                        let mut o: Vec<(String, Json)> = vec![
249                            ("name".into(), s(&v.name)),
250                            ("type".into(), s(&v.ty.name())),
251                            (
252                                "kind".into(),
253                                s(match v.kind {
254                                    Kind::Save => "save",
255                                    Kind::Persistent => "persistent",
256                                }),
257                            ),
258                            ("default".into(), value_json(&v.init)),
259                            ("read_only".into(), Json::Bool(v.read_only)),
260                        ];
261                        if let Some(d) = &v.doc {
262                            o.push(("doc".into(), s(d)));
263                        }
264                        obj(o)
265                    })
266                    .collect(),
267            ),
268        ));
269        // Types
270        let mut types: Vec<usize> = (0..self.types.len()).collect();
271        types.sort_by(|&a, &b| self.types[a].name.cmp(&self.types[b].name));
272        root.push((
273            "types".into(),
274            Json::Array(
275                types
276                    .iter()
277                    .map(|&i| {
278                        let t = &self.types[i];
279                        let mut o: Vec<(String, Json)> = vec![("name".into(), s(&t.name))];
280                        match &t.kind {
281                            TypeKind::Struct { fields } => {
282                                o.push(("kind".into(), s("struct")));
283                                o.push((
284                                    "fields".into(),
285                                    Json::Array(
286                                        fields
287                                            .iter()
288                                            .map(|(n, ty)| {
289                                                obj(vec![
290                                                    ("name".into(), s(n)),
291                                                    ("type".into(), s(&ty.name())),
292                                                ])
293                                            })
294                                            .collect(),
295                                    ),
296                                ));
297                            }
298                            TypeKind::Enum { variants } => {
299                                o.push(("kind".into(), s("enum")));
300                                o.push((
301                                    "variants".into(),
302                                    Json::Array(
303                                        variants
304                                            .iter()
305                                            .map(|v| {
306                                                obj(vec![
307                                                    ("name".into(), s(&v.name)),
308                                                    (
309                                                        "fields".into(),
310                                                        Json::Array(
311                                                            v.args
312                                                                .iter()
313                                                                .map(|a| {
314                                                                    obj(vec![(
315                                                                        "type".into(),
316                                                                        s(&a.name()),
317                                                                    )])
318                                                                })
319                                                                .collect(),
320                                                        ),
321                                                    ),
322                                                ])
323                                            })
324                                            .collect(),
325                                    ),
326                                ));
327                            }
328                        }
329                        if let Some(d) = &self.type_docs[i] {
330                            o.push(("doc".into(), s(d)));
331                        }
332                        obj(o)
333                    })
334                    .collect(),
335            ),
336        ));
337        // Sugar
338        let mut sugar: Vec<(String, Json)> = Vec::new();
339        for kind in [Sugar::Plain, Sugar::Quote, Sugar::Choice] {
340            match self.sugar_binding(kind) {
341                Some(Some(name)) => sugar.push((kind.name().into(), s(name))),
342                Some(None) => sugar.push((kind.name().into(), Json::Null)),
343                None => {}
344            }
345        }
346        root.push(("sugar".into(), obj(sugar)));
347        write_json(&obj(root))
348    }
349
350    /// Makes a registry without functions from a declaration file (JSON; the output of [`Registry::export_decls`]).
351    ///
352    /// The registry can only be used for compiling scripts (checking, the LSP, `assign-ids`, `yomi check`). Passing it to
353    /// [`Vm::new`](crate::Vm::new) or [`Vm::load`](crate::Vm::load) is an error ([`Registry::is_decl_only`]).
354    ///
355    /// - `format` must be `"yomi-decls"` and `version` must be 1. Unknown items are ignored.
356    /// - Broken input, input that is too large ([`MAX_DECLS_BYTES`]) and nesting that is too deep ([`MAX_JSON_DEPTH`]) do
357    ///   not panic; a [`DeclError`] is returned.
358    pub fn from_decls(json: &str) -> Result<Registry, DeclError> {
359        let root = parse_json(json)?;
360        build(&root)
361    }
362}
363
364// ---------------------------------------------------------------------------
365// Reading (from the JSON tree to a registry)
366// ---------------------------------------------------------------------------
367
368/// Turns a registry error into a declaration file error with a location.
369fn reg_err(e: RegistryError, path: &str) -> DeclError {
370    err(DeclErrorKind::Registry(e), path)
371}
372
373/// Makes the path of an array item (`array[i]`).
374fn item_path(array: &str, i: usize) -> String {
375    format!("{array}[{i}]")
376}
377
378/// The function of a command that cannot run (a registry made from a declaration file).
379fn no_function() -> crate::registry::NativeFn {
380    Arc::new(|_env: Env<'_>, _args: &[Value]| {
381        Err(CommandError::with_code("core.decl_only_function", []))
382    })
383}
384
385/// Builds a registry from the JSON tree. Types are registered before commands and variables (which use them), and aliases
386/// after commands.
387fn build(root: &Json) -> JResult<Registry> {
388    check_header(root)?;
389    let mut reg = Registry::new();
390    reg.decl_only = true;
391    build_packages(&mut reg, root)?;
392    let kinds = build_types(&mut reg, root)?;
393    build_commands(&mut reg, root, &kinds)?;
394    build_variables(&mut reg, root, &kinds)?;
395    build_sugar(&mut reg, root)?;
396    Ok(reg)
397}
398
399/// Checks the format and version of the declaration file.
400fn check_header(root: &Json) -> JResult<()> {
401    if !matches!(root, Json::Object(_)) {
402        return Err(err(DeclErrorKind::NotDecls, ""));
403    }
404    match root.get("format") {
405        Some(Json::String(f)) if f == FORMAT => {}
406        _ => return Err(err(DeclErrorKind::NotDecls, "format")),
407    }
408    match root.get("version") {
409        Some(Json::Number(n)) => match n.as_i64() {
410            Some(1 | VERSION) => {}
411            Some(other) => return Err(err(DeclErrorKind::UnsupportedVersion(other), "version")),
412            None => return Err(err(DeclErrorKind::WrongType, "version")),
413        },
414        Some(_) => return Err(err(DeclErrorKind::WrongType, "version")),
415        None => return Err(err(DeclErrorKind::MissingField, "version")),
416    }
417    Ok(())
418}
419
420/// Packages.
421fn build_packages(reg: &mut Registry, root: &Json) -> JResult<()> {
422    for (i, p) in opt_arr(root, "packages", "")?.iter().enumerate() {
423        let path = item_path("packages", i);
424        let name = want_str(p, "name", &path)?;
425        if reg.packages.iter().any(|e| e.name == name) {
426            return Err(reg_err(RegistryError::DuplicatePackage(name.into()), &path));
427        }
428        let version = match p.get("version") {
429            Some(Json::Number(n)) => n
430                .as_u64()
431                .and_then(|v| u32::try_from(v).ok())
432                .ok_or_else(|| err(DeclErrorKind::InvalidValue, &join(&path, "version")))?,
433            Some(_) => return Err(err(DeclErrorKind::WrongType, &join(&path, "version"))),
434            None => 1,
435        };
436        let mut depends = Vec::new();
437        for (k, d) in opt_arr(p, "depends", &path)?.iter().enumerate() {
438            match d {
439                Json::String(t) => depends.push(t.clone()),
440                _ => {
441                    return Err(err(
442                        DeclErrorKind::WrongType,
443                        &join(&join(&path, "depends"), &format!("[{k}]")),
444                    ));
445                }
446            }
447        }
448        let std = match p.get("std") {
449            Some(Json::Bool(b)) => *b,
450            Some(_) => return Err(err(DeclErrorKind::WrongType, &join(&path, "std"))),
451            None => false,
452        };
453        reg.packages
454            .push(PackageEntry::decl_only(name, version, depends, std));
455    }
456    Ok(())
457}
458
459/// Types. Sorted so that used types are registered first. Returns a table from type name to whether it is a struct
460/// (false means enum).
461fn build_types(reg: &mut Registry, root: &Json) -> JResult<HashMap<String, bool>> {
462    let types_json = opt_arr(root, "types", "")?;
463    let mut kinds: HashMap<String, bool> = HashMap::new();
464    for (i, t) in types_json.iter().enumerate() {
465        let path = item_path("types", i);
466        let name = want_str(t, "name", &path)?;
467        let is_struct = match want_str(t, "kind", &path)? {
468            "struct" => true,
469            "enum" => false,
470            _ => return Err(err(DeclErrorKind::InvalidValue, &join(&path, "kind"))),
471        };
472        if kinds.insert(name.to_string(), is_struct).is_some() {
473            return Err(reg_err(RegistryError::DuplicateType(name.into()), &path));
474        }
475    }
476    let mut parsed: Vec<(usize, TypeDecl)> = Vec::new();
477    for (i, t) in types_json.iter().enumerate() {
478        let path = item_path("types", i);
479        let name = want_str(t, "name", &path)?.to_string();
480        let kind = if kinds[&name] {
481            let mut fields = Vec::new();
482            for (k, f) in opt_arr(t, "fields", &path)?.iter().enumerate() {
483                let fp = format!("{path}.fields[{k}]");
484                let fname = want_str(f, "name", &fp)?.to_string();
485                let ty = parse_ty(want_str(f, "type", &fp)?, &kinds, &join(&fp, "type"))?;
486                fields.push((fname, ty));
487            }
488            TypeKind::Struct { fields }
489        } else {
490            let mut variants = Vec::new();
491            for (k, v) in opt_arr(t, "variants", &path)?.iter().enumerate() {
492                let vp = format!("{path}.variants[{k}]");
493                let vname = want_str(v, "name", &vp)?.to_string();
494                let mut args = Vec::new();
495                for (m, a) in opt_arr(v, "fields", &vp)?.iter().enumerate() {
496                    let ap = format!("{vp}.fields[{m}]");
497                    args.push(parse_ty(
498                        want_str(a, "type", &ap)?,
499                        &kinds,
500                        &join(&ap, "type"),
501                    )?);
502                }
503                variants.push(VariantDecl { name: vname, args });
504            }
505            TypeKind::Enum { variants }
506        };
507        parsed.push((i, TypeDecl { name, kind }));
508    }
509    // In dependency order (used types first)
510    let index_of: HashMap<&str, usize> = parsed
511        .iter()
512        .enumerate()
513        .map(|(k, (_, d))| (d.name.as_str(), k))
514        .collect();
515    let mut waiting: Vec<usize> = vec![0; parsed.len()];
516    let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); parsed.len()];
517    for (k, (_, d)) in parsed.iter().enumerate() {
518        let mut used: Vec<&str> = d.used_types();
519        used.sort_unstable();
520        used.dedup();
521        for u in used {
522            if let Some(&j) = index_of.get(u)
523                && j != k
524            {
525                waiting[k] += 1;
526                dependents[j].push(k);
527            }
528        }
529    }
530    let mut ready: Vec<usize> = (0..parsed.len()).filter(|&k| waiting[k] == 0).collect();
531    ready.reverse();
532    let mut done = vec![false; parsed.len()];
533    while let Some(k) = ready.pop() {
534        done[k] = true;
535        let (orig, decl) = &parsed[k];
536        let path = item_path("types", *orig);
537        reg.add_type(None, decl.clone())
538            .map_err(|e| reg_err(e, &path))?;
539        let doc = opt_str(&types_json[*orig], "doc", &path)?;
540        if let Some(d) = doc {
541            let last = reg.type_docs.len() - 1;
542            reg.type_docs[last] = Some(d.to_string());
543        }
544        for &m in dependents[k].iter().rev() {
545            waiting[m] -= 1;
546            if waiting[m] == 0 {
547                ready.push(m);
548            }
549        }
550    }
551    if let Some(k) = done.iter().position(|d| !d) {
552        // Types that use each other (including themselves)
553        let (orig, decl) = &parsed[k];
554        return Err(reg_err(
555            RegistryError::RecursiveType(decl.name.clone()),
556            &item_path("types", *orig),
557        ));
558    }
559    Ok(kinds)
560}
561
562/// Commands and their aliases.
563fn build_commands(reg: &mut Registry, root: &Json, kinds: &HashMap<String, bool>) -> JResult<()> {
564    let mut alias_list: Vec<(String, String, String)> = Vec::new();
565    for (i, c) in opt_arr(root, "commands", "")?.iter().enumerate() {
566        let path = item_path("commands", i);
567        let name = want_str(c, "name", &path)?;
568        let kind = match want_str(c, "kind", &path)? {
569            "effect" => CommandKind::Effect,
570            "query" => CommandKind::Query,
571            "stop" => CommandKind::Stop,
572            _ => return Err(err(DeclErrorKind::InvalidValue, &join(&path, "kind"))),
573        };
574        let package = opt_str(c, "package", &path)?;
575        let mut args: Vec<Ty> = Vec::new();
576        let mut params: Vec<Option<String>> = Vec::new();
577        let mut defaults: Vec<Option<Value>> = Vec::new();
578        for (k, p) in opt_arr(c, "params", &path)?.iter().enumerate() {
579            let pp = format!("{path}.params[{k}]");
580            let ty = parse_ty(want_str(p, "type", &pp)?, kinds, &join(&pp, "type"))?;
581            let default = match p.get("default") {
582                Some(Json::Null) | None => None,
583                Some(d) => Some(json_value(d, &ty, &reg.types, &join(&pp, "default"))?),
584            };
585            args.push(ty);
586            params.push(opt_str(p, "name", &pp)?.map(str::to_string));
587            defaults.push(default);
588        }
589        // Parameters with default values have names and come last
590        if defaults
591            .iter()
592            .zip(&params)
593            .any(|(d, n)| d.is_some() && n.is_none())
594            || defaults
595                .windows(2)
596                .any(|w| w[0].is_some() && w[1].is_none())
597        {
598            return Err(err(DeclErrorKind::InvalidValue, &join(&path, "params")));
599        }
600        let ret = match opt_str(c, "returns", &path)? {
601            None | Some("()") => Ty::Unit,
602            Some(t) => parse_ty(t, kinds, &join(&path, "returns"))?,
603        };
604        match kind {
605            CommandKind::Stop => {
606                reg.add_stop(name, args, ret, package, None, None)
607                    .map_err(|e| reg_err(e, &path))?;
608                let last = reg.stops.len() - 1;
609                reg.stops[last].params = params;
610                reg.stops[last].defaults = defaults;
611                reg.stops[last].doc = opt_str(c, "doc", &path)?.map(str::to_string);
612            }
613            _ => {
614                let Some(package) = package else {
615                    return Err(err(DeclErrorKind::MissingField, &join(&path, "package")));
616                };
617                let Some(index) = reg.packages.iter().position(|e| e.name == package) else {
618                    return Err(reg_err(RegistryError::InvalidName(name.into()), &path));
619                };
620                let native_kind = if kind == CommandKind::Effect {
621                    NativeKind::Effect
622                } else {
623                    NativeKind::Query
624                };
625                reg.add_native(index, name, native_kind, args, ret, no_function())
626                    .map_err(|e| reg_err(e, &path))?;
627                let last = reg.natives.len() - 1;
628                reg.natives[last].params = params;
629                reg.natives[last].defaults = defaults;
630                reg.natives[last].doc = opt_str(c, "doc", &path)?.map(str::to_string);
631            }
632        }
633        for (k, a) in opt_arr(c, "aliases", &path)?.iter().enumerate() {
634            match a {
635                Json::String(old) => alias_list.push((
636                    old.clone(),
637                    name.to_string(),
638                    format!("{path}.aliases[{k}]"),
639                )),
640                _ => {
641                    return Err(err(
642                        DeclErrorKind::WrongType,
643                        &format!("{path}.aliases[{k}]"),
644                    ));
645                }
646            }
647        }
648    }
649    for (old, target, path) in alias_list {
650        reg.alias(&old, &target).map_err(|e| reg_err(e, &path))?;
651    }
652    Ok(())
653}
654
655/// Variables declared by the host.
656fn build_variables(reg: &mut Registry, root: &Json, kinds: &HashMap<String, bool>) -> JResult<()> {
657    for (i, v) in opt_arr(root, "variables", "")?.iter().enumerate() {
658        let path = item_path("variables", i);
659        let name = want_str(v, "name", &path)?;
660        let ty = parse_ty(want_str(v, "type", &path)?, kinds, &join(&path, "type"))?;
661        let kind = match want_str(v, "kind", &path)? {
662            "save" => Kind::Save,
663            "persistent" => Kind::Persistent,
664            _ => return Err(err(DeclErrorKind::InvalidValue, &join(&path, "kind"))),
665        };
666        let init = match v.get("default") {
667            Some(d) => json_value(d, &ty, &reg.types, &join(&path, "default"))?,
668            None => return Err(err(DeclErrorKind::MissingField, &join(&path, "default"))),
669        };
670        let read_only = match v.get("read_only") {
671            Some(Json::Bool(b)) => *b,
672            Some(Json::Null) | None => false,
673            Some(_) => return Err(err(DeclErrorKind::WrongType, &join(&path, "read_only"))),
674        };
675        let index = reg
676            .add_var(None, name, ty, kind, init)
677            .map_err(|e| reg_err(e, &path))?;
678        reg.vars[index].read_only = read_only;
679        reg.vars[index].doc = opt_str(v, "doc", &path)?.map(str::to_string);
680    }
681    Ok(())
682}
683
684/// Sugar bindings.
685fn build_sugar(reg: &mut Registry, root: &Json) -> JResult<()> {
686    if let Some(sugar) = root.get("sugar") {
687        if !matches!(sugar, Json::Object(_)) {
688            return Err(err(DeclErrorKind::WrongType, "sugar"));
689        }
690        for kind in [Sugar::Plain, Sugar::Quote, Sugar::Choice] {
691            let path = join("sugar", kind.name());
692            match sugar.get(kind.name()) {
693                None => {}
694                Some(Json::Null) => reg.ignore(kind).map_err(|e| reg_err(e, &path))?,
695                Some(Json::String(command)) => {
696                    reg.bind(kind, command).map_err(|e| reg_err(e, &path))?
697                }
698                Some(_) => return Err(err(DeclErrorKind::WrongType, &path)),
699            }
700        }
701    }
702    Ok(())
703}
704
705#[cfg(test)]
706mod tests;