Skip to main content

roas_codegen/rust/
view.rs

1//! The view model: what templates see. Every type is already spelled
2//! for Rust, every name is final, every attribute is decided. A
3//! template lays this out and nothing more.
4
5use crate::config::{Config, FieldConfig, Layout, TypeConfig};
6use crate::diagnostic::{Diagnostic, DiagnosticKind, SchemaId, Severity};
7use crate::front::{Constraints, FloatWidth, IntWidth};
8use crate::generate::GenerateError;
9use crate::ir::{Additional, Ir, TypeDef, TypeKind, TypeRef};
10use crate::rust::attrs::{cfg_gates, check_container_attrs, check_field_attrs, serde_aliases};
11use crate::rust::naming::{Allocator, legal, pascal, snake};
12use serde::Serialize;
13use std::collections::BTreeMap;
14
15#[derive(Debug, Clone, Serialize, Default)]
16pub(crate) struct SupportView {
17    pub double_option: bool,
18    pub reject_null: bool,
19    pub require_present: bool,
20    pub int64: bool,
21    pub int32: bool,
22    /// A `number` held exactly, under `exact_numbers`: `Decimal`.
23    pub decimal: bool,
24    /// `exact_numbers` is on: the support reads numbers as decimals may.
25    pub exact_numbers: bool,
26    pub raw_holder: bool,
27    /// A closed struct reads through `ObjectOnly`.
28    pub object_only: bool,
29    /// A string enum reads through `StringOnly`.
30    pub string_only: bool,
31    /// A member beside `patternProperties` is held as `RawJson`.
32    pub raw_json: bool,
33    /// A struct with a catch-all reads through `roas_catch_all`.
34    pub catch_all: bool,
35    /// Generated validation is on: the report types and `Validate`.
36    pub validation: bool,
37}
38
39#[derive(Debug, Clone, Serialize)]
40pub(crate) struct FieldView {
41    pub name: String,
42    pub raw_name: String,
43    pub ty: String,
44    pub doc: Vec<String>,
45    pub attrs: Vec<String>,
46    /// The field's conditional-compilation gates, which the validation
47    /// reading it repeats.
48    #[serde(skip)]
49    pub cfg: Vec<String>,
50}
51
52/// A struct's catch-all, decoded as the members stream by.
53#[derive(Debug, Clone, Serialize)]
54pub(crate) struct CatchAllView {
55    /// The catch-all field.
56    pub field: String,
57    /// The type of one of its values.
58    pub ty: String,
59    /// The members routed to the derived code, one entry per field.
60    pub declared: Vec<DeclaredView>,
61    /// A Rust function from a member name no field reads to whether it is
62    /// let in: beside `additionalProperties: false`, only one matching a
63    /// pattern of `patternProperties`.
64    pub allowed: String,
65}
66
67/// The names one declared field is read by.
68#[derive(Debug, Clone, Serialize)]
69pub(crate) struct DeclaredView {
70    /// The field's conditional-compilation gates.
71    pub cfg: Vec<String>,
72    /// A Rust pattern: the quoted name and aliases, joined by `|`.
73    pub names: String,
74}
75
76#[derive(Debug, Clone, Serialize)]
77pub(crate) struct VariantView {
78    pub name: String,
79    pub value: String,
80    /// The payload type, for a tagged union; empty for a string enum.
81    pub ty: String,
82    pub doc: Vec<String>,
83    pub attrs: Vec<String>,
84    /// The variant's conditional-compilation gates, repeated on every
85    /// match arm naming it.
86    pub cfg: Vec<String>,
87    /// The wire value as a Rust string literal.
88    pub literal: String,
89    /// The value is made up: no tag selects the variant.
90    pub synthetic: bool,
91    /// Every wire value selecting the variant, as a match pattern.
92    pub pattern: String,
93}
94
95#[derive(Debug, Clone, Serialize)]
96pub(crate) struct BranchView {
97    /// Accessor name, e.g. `as_cat`.
98    pub accessor: String,
99    /// Constructor name, e.g. `from_cat`.
100    pub constructor: String,
101    pub ty: String,
102    pub doc: Vec<String>,
103}
104
105#[derive(Debug, Clone, Serialize)]
106pub(crate) struct TypeView {
107    /// `struct`, `enum`, `union_tagged`, `union_open`, `composed_open`,
108    /// `newtype`, `alias`.
109    pub kind: &'static str,
110    pub name: String,
111    pub raw_name: String,
112    pub doc: Vec<String>,
113    pub derives: Vec<String>,
114    pub attrs: Vec<String>,
115    pub fields: Vec<FieldView>,
116    pub variants: Vec<VariantView>,
117    pub branches: Vec<BranchView>,
118    /// Inner type of a newtype or alias.
119    pub inner: String,
120    /// Discriminator property of a tagged union.
121    pub tag: String,
122    /// For a tagged union, the index of the variant an unknown or missing
123    /// tag is read as; `None` refuses such a value.
124    pub fallback: Option<usize>,
125    /// For a union read by a parent's discriminator, the index of the
126    /// parent's variant: what the fallback falls back to when compiled out.
127    pub parent_variant: Option<usize>,
128    /// The discriminator property as a Rust string literal.
129    pub tag_literal: String,
130    /// The tag as it reads in a doc comment.
131    pub tag_doc: String,
132    /// `oneOf` rather than `anyOf`, for an open union's documentation.
133    pub exclusive: bool,
134    /// The statements of `Validate::validate_into`, with validation on;
135    /// `None` for no implementation (an alias shares its target's).
136    pub validate: Option<Vec<String>>,
137    /// The statements of `Validate::validate_null`; empty for none.
138    pub validate_null: Vec<String>,
139    /// A struct read from a JSON object only: serde's derive would also
140    /// read it from an array, so it decodes through a guard.
141    pub object_only: bool,
142    /// A string enum read from a JSON string only: serde's derive would
143    /// also read `{"a": null}` as `"a"`.
144    pub string_only: bool,
145    /// A struct with a catch-all: the members it does not declare decode
146    /// into the catch-all as they stream by.
147    pub catch_all: Option<CatchAllView>,
148    /// The Rust spelling of each `patternProperties` schema, in order.
149    #[serde(skip)]
150    pub pattern_tys: Vec<Option<String>>,
151    /// The Rust spelling of the `additionalProperties` schema beside them.
152    #[serde(skip)]
153    pub others_ty: Option<String>,
154    /// The type's conditional-compilation gates (`#[cfg(...)]` among its
155    /// configured attributes), repeated on every impl generated beside it.
156    pub cfg: Vec<String>,
157    /// Under `layout = "file_per_type"`, the stem of the file the type is
158    /// written to, below the module's directory.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub file: Option<String>,
161}
162
163#[derive(Debug, Clone, Serialize)]
164pub(crate) struct FileView {
165    /// The contract version this context follows.
166    pub template_api: u32,
167    pub source: String,
168    pub header: String,
169    pub imports: Vec<String>,
170    pub extra_imports: Vec<String>,
171    pub support: SupportView,
172    pub types: Vec<TypeView>,
173    /// Under `layout = "file_per_type"`, the module: the directory the
174    /// types' files are in, which the module file includes.
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub module: Option<String>,
177}
178
179/// A Rust dependency the generated code needs.
180#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
181#[non_exhaustive]
182pub struct RustDependency {
183    pub name: String,
184    pub features: Vec<String>,
185}
186
187impl RustDependency {
188    pub fn new(name: impl Into<String>, features: Vec<String>) -> Self {
189        RustDependency {
190            name: name.into(),
191            features,
192        }
193    }
194}
195
196/// The constraints a schema declares, as documentation until generated
197/// validation lands; the type itself does not enforce them.
198pub(crate) fn constraint_notes(c: &Constraints) -> Vec<String> {
199    let mut notes = Vec::new();
200    let mut push = |keyword: &str, value: String| notes.push(format!("`{keyword}`: {value}."));
201    if let Some(v) = c.min_length {
202        push("minLength", v.to_string());
203    }
204    if let Some(v) = c.max_length {
205        push("maxLength", v.to_string());
206    }
207    if let Some(v) = &c.pattern {
208        push("pattern", code_span(&v.escape_debug().to_string()));
209    }
210    if let Some(v) = &c.minimum {
211        push("minimum", v.to_string());
212    }
213    if let Some(v) = &c.exclusive_minimum {
214        push("exclusiveMinimum", v.to_string());
215    }
216    if let Some(v) = &c.maximum {
217        push("maximum", v.to_string());
218    }
219    if let Some(v) = &c.exclusive_maximum {
220        push("exclusiveMaximum", v.to_string());
221    }
222    if let Some(v) = &c.multiple_of {
223        push("multipleOf", v.to_string());
224    }
225    if let Some(v) = c.min_items {
226        push("minItems", v.to_string());
227    }
228    if let Some(v) = c.max_items {
229        push("maxItems", v.to_string());
230    }
231    if c.unique_items {
232        push("uniqueItems", "true".into());
233    }
234    if let Some(v) = c.min_properties {
235        push("minProperties", v.to_string());
236    }
237    if let Some(v) = c.max_properties {
238        push("maxProperties", v.to_string());
239    }
240    notes
241}
242
243pub(crate) struct Built {
244    pub file: FileView,
245    pub dependencies: Vec<RustDependency>,
246    pub diagnostics: Vec<Diagnostic>,
247}
248
249struct Builder<'a> {
250    ir: &'a Ir,
251    config: &'a Config,
252    names: BTreeMap<SchemaId, String>,
253    support: SupportView,
254    externs: BTreeMap<String, String>,
255    diagnostics: Vec<Diagnostic>,
256}
257
258pub(crate) fn build(ir: &Ir, config: &Config, source: &str) -> Result<Built, GenerateError> {
259    let mut builder = Builder {
260        ir,
261        config,
262        names: BTreeMap::new(),
263        support: SupportView {
264            exact_numbers: config.exact_numbers,
265            ..SupportView::default()
266        },
267        externs: BTreeMap::new(),
268        diagnostics: Vec::new(),
269    };
270    select_check(ir, config)?;
271    check_rust_renames(config)?;
272    builder.allocate_type_names();
273    // Reset: only what this build renders counts.
274    super::validation::take_uses_regex();
275    let mut types = Vec::new();
276    for id in &ir.order {
277        if ir.suppressed.contains(id) {
278            continue;
279        }
280        let def = &ir.types[id];
281        if let Some(view) = builder.type_view(def)? {
282            types.push(view);
283        }
284    }
285    let uses_regex = super::validation::take_uses_regex();
286    let module = (config.layout == Layout::FilePerType).then(|| {
287        assign_files(&mut types);
288        config.rust.module.clone()
289    });
290    let mut dependencies = vec![
291        RustDependency {
292            name: "serde".into(),
293            features: vec!["derive".into()],
294        },
295        RustDependency {
296            name: "serde_json".into(),
297            // Validation compares a decoded number with a bound read
298            // exactly: the decoder must read it exactly too.
299            features: if builder.config.validation {
300                vec!["raw_value".into(), "float_roundtrip".into()]
301            } else {
302                vec!["raw_value".into()]
303            },
304        },
305    ];
306    // A checked `pattern` is matched with `regex`.
307    if uses_regex {
308        dependencies.push(RustDependency {
309            name: "regex".into(),
310            features: Vec::new(),
311        });
312    }
313    for import in builder.externs.values() {
314        if !dependencies.iter().any(|d| d.name == *import) {
315            dependencies.push(RustDependency {
316                name: import.clone(),
317                features: Vec::new(),
318            });
319        }
320    }
321    dependencies.sort();
322    let imports = vec!["use serde::{Deserialize, Serialize};".to_owned()];
323    Ok(Built {
324        file: FileView {
325            template_api: crate::templates::TEMPLATE_API,
326            source: source.to_owned(),
327            header: config.header.clone().unwrap_or_default(),
328            imports,
329            extra_imports: config.extra_imports.clone(),
330            support: builder.support,
331            types,
332            module,
333        },
334        dependencies,
335        diagnostics: builder.diagnostics,
336    })
337}
338
339/// Names the file of every type under `layout = "file_per_type"`: its name
340/// in snake case, unique and lowercase, so distinct on a case-insensitive
341/// disk too, and never one a Windows file system resolves elsewhere. The
342/// module includes the files, so their names are not Rust names.
343fn assign_files(types: &mut [TypeView]) {
344    let mut taken = std::collections::BTreeSet::new();
345    for t in types {
346        let base = crate::write::capped_stem(crate::config::rust_module_name(&snake(
347            std::slice::from_ref(&t.name),
348        )));
349        let file = (1u32..)
350            .map(|i| {
351                if i == 1 {
352                    base.clone()
353                } else {
354                    format!("{base}{i}")
355                }
356            })
357            .find(|candidate| !taken.contains(candidate) && crate::write::windows_safe(candidate))
358            .expect("a free file name");
359        taken.insert(file.clone());
360        t.file = Some(file);
361    }
362}
363
364/// Every `types.<Name>` and `fields.<prop>` in the configuration must
365/// name something in the description.
366pub(crate) fn select_check(ir: &Ir, config: &Config) -> Result<(), GenerateError> {
367    for (name, type_config) in &config.types {
368        let Some(id) = ir.components.get(name) else {
369            return Err(GenerateError::UnknownSelector {
370                selector: format!("types.{name}"),
371                candidates: ir.components.keys().cloned().collect(),
372            });
373        };
374        if type_config.fields.is_empty() {
375            continue;
376        }
377        let def = &ir.types[id];
378        let fields: Vec<String> = match &def.kind {
379            TypeKind::Struct(s) => s.fields.iter().map(|f| f.raw_name.clone()).collect(),
380            _ => Vec::new(),
381        };
382        for field in type_config.fields.keys() {
383            if !fields.contains(field) {
384                return Err(GenerateError::UnknownSelector {
385                    selector: format!("types.{name}.fields.{field}"),
386                    candidates: fields.clone(),
387                });
388            }
389        }
390    }
391    Ok(())
392}
393
394/// Every configured Rust `rename` on a type or field must be a valid Rust
395/// identifier (once keywords are legalized), never arbitrary punctuation.
396fn check_rust_renames(config: &Config) -> Result<(), GenerateError> {
397    fn check_ident(name: &str, selector: &str) -> Result<(), GenerateError> {
398        let legalized = legal(name.to_owned());
399        if name.is_empty()
400            || name == "_"
401            || !syn::parse_str::<syn::Ident>(&legalized).is_ok_and(|ident| ident == legalized)
402        {
403            return Err(GenerateError::Config(format!(
404                "`{selector} = {name:?}` is not a valid Rust identifier"
405            )));
406        }
407        Ok(())
408    }
409    for (type_name, type_config) in &config.types {
410        if let Some(rename) = &type_config.rename {
411            check_ident(rename, &format!("types.{type_name}.rename"))?;
412        }
413        for (field_name, field_config) in &type_config.fields {
414            if let Some(rename) = &field_config.rename {
415                check_ident(
416                    rename,
417                    &format!("types.{type_name}.fields.{field_name}.rename"),
418                )?;
419            }
420        }
421    }
422    Ok(())
423}
424
425impl Builder<'_> {
426    fn allocate_type_names(&mut self) {
427        let mut allocator = Allocator::default();
428        // Names the generated code itself uses unqualified: its own
429        // helpers, the prelude types it spells, and its imports.
430        if self.config.exact_numbers {
431            allocator.reserve("Decimal");
432        }
433        for reserved in [
434            "Int64",
435            "Int32",
436            "Nullable",
437            "String",
438            "Option",
439            "Some",
440            "None",
441            "Vec",
442            "Box",
443            "Result",
444            "Ok",
445            "Err",
446            "Self",
447            "Serialize",
448            "Deserialize",
449            "Default",
450            "Clone",
451            "Debug",
452            "PartialEq",
453            "Eq",
454            "Hash",
455            "Copy",
456            "From",
457            "Into",
458            "double_option",
459            "reject_null",
460            "require_present",
461            "integer_token",
462            "roas_string_only",
463            "roas_string_only_variant",
464            "roas_object_only",
465            "roas_catch_all",
466        ] {
467            allocator.reserve(reserved);
468        }
469        // Generated only beside `patternProperties`.
470        if self
471            .ir
472            .types
473            .values()
474            .any(|def| matches!(&def.kind, TypeKind::Struct(s) if !s.patterns.is_empty()))
475        {
476            allocator.reserve("RawJson");
477        }
478        if self.config.validation {
479            for reserved in [
480                "Validate",
481                "ValidationReport",
482                "Finding",
483                "FindingKind",
484                "child_pointer",
485                "wide_number",
486            ] {
487                allocator.reserve(reserved);
488            }
489        }
490        // Components first: a component keeps its name whatever an inline
491        // schema is titled or positioned to be called.
492        let ir = self.ir;
493        let order = ir
494            .order
495            .iter()
496            .filter(|id| ir.types[*id].component.is_some());
497        let rest = ir
498            .order
499            .iter()
500            .filter(|id| ir.types[*id].component.is_none());
501        for id in order.chain(rest) {
502            let def = &self.ir.types[id];
503            if matches!(def.kind, TypeKind::Extern) {
504                continue;
505            }
506            let base = match def
507                .component
508                .as_ref()
509                .and_then(|c| self.config.types.get(c))
510                .and_then(|t| t.rename.clone())
511            {
512                Some(rename) => rename,
513                None => pascal(&def.suggested_name),
514            };
515            let name = allocator.allocate(legal(base));
516            self.names.insert(id.clone(), name);
517        }
518    }
519
520    /// The cfg gates a generated type carries: configured, or from the
521    /// description's `x-rust-attrs` as applied.
522    fn type_gates(&self, id: &SchemaId, at: &str) -> Result<Vec<String>, GenerateError> {
523        let Some(def) = self.ir.types.get(id) else {
524            return Ok(Vec::new());
525        };
526        let mut attrs: Vec<String> = self
527            .type_config(def)
528            .map(|t| t.attrs.clone())
529            .unwrap_or_default();
530        if self.config.allow_codegen_extensions {
531            let described: Vec<String> = match def.extensions.get("x-rust-attrs") {
532                Some(serde_json::Value::String(a)) => vec![a.clone()],
533                Some(serde_json::Value::Array(items)) => items
534                    .iter()
535                    .filter_map(|v| v.as_str().map(str::to_owned))
536                    .collect(),
537                _ => Vec::new(),
538            };
539            attrs.extend(
540                described
541                    .into_iter()
542                    .filter(|a| check_container_attrs(std::slice::from_ref(a), "").is_ok()),
543            );
544        }
545        cfg_gates(&attrs, at)
546    }
547
548    fn type_config(&self, def: &TypeDef) -> Option<&TypeConfig> {
549        def.component
550            .as_ref()
551            .and_then(|c| self.config.types.get(c))
552    }
553
554    /// Whether the struct `id` reads its members by other names than the
555    /// schema does: a field compiled out by a `cfg` gate (its member then
556    /// lands among the others) or read under a `serde(alias)`. A value
557    /// valid for the schema may then fail to decode. A configured
558    /// attribute that does not parse counts: generation fails on it anyway.
559    fn reshaped(&self, id: &SchemaId) -> bool {
560        let def = &self.ir.types[id];
561        let TypeKind::Struct(s) = &def.kind else {
562            return false;
563        };
564        s.fields.iter().any(|field| {
565            let mut attrs: Vec<String> = self
566                .field_config(def, &field.raw_name)
567                .map(|f| f.attrs.clone())
568                .unwrap_or_default();
569            if self.config.allow_codegen_extensions {
570                let described: Vec<String> = match field.extensions.get("x-rust-attrs") {
571                    Some(serde_json::Value::String(a)) => vec![a.clone()],
572                    Some(serde_json::Value::Array(items)) => items
573                        .iter()
574                        .filter_map(|v| v.as_str().map(str::to_owned))
575                        .collect(),
576                    _ => Vec::new(),
577                };
578                // Only the entries generation applies: a failing one is
579                // dropped there with a warning.
580                attrs.extend(
581                    described
582                        .into_iter()
583                        .filter(|a| check_field_attrs(std::slice::from_ref(a), "").is_ok()),
584                );
585            }
586            attrs.iter().any(|attr| {
587                let one = std::slice::from_ref(attr);
588                !matches!(cfg_gates(one, ""), Ok(g) if g.is_empty())
589                    || !matches!(serde_aliases(one, ""), Ok(a) if a.is_empty())
590            })
591        })
592    }
593
594    fn field_config<'c>(&'c self, def: &TypeDef, raw_name: &str) -> Option<&'c FieldConfig> {
595        self.type_config(def).and_then(|t| t.fields.get(raw_name))
596    }
597
598    /// Spell a type for Rust.
599    fn spell(&mut self, ty: &TypeRef) -> Result<String, GenerateError> {
600        Ok(match ty {
601            TypeRef::Named(id) => match &self.ir.types[id].kind {
602                TypeKind::Extern => {
603                    let component = self.ir.types[id].component.clone().unwrap_or_default();
604                    self.extern_spelling(&component)?
605                }
606                _ => self.names[id].clone(),
607            },
608            TypeRef::Boxed(inner) => format!("Box<{}>", self.spell(inner)?),
609            TypeRef::Nullable(inner) => format!("Option<{}>", self.spell(inner)?),
610            TypeRef::String => "String".into(),
611            TypeRef::Integer(IntWidth::Int64) => {
612                self.support.int64 = true;
613                "Int64".into()
614            }
615            TypeRef::Integer(IntWidth::Int32) => {
616                self.support.int32 = true;
617                "Int32".into()
618            }
619            TypeRef::Number(FloatWidth::Double) => "f64".into(),
620            TypeRef::Number(FloatWidth::Float) => "f32".into(),
621            TypeRef::Decimal => {
622                self.support.decimal = true;
623                "Decimal".into()
624            }
625            TypeRef::Boolean => "bool".into(),
626            TypeRef::Null => "()".into(),
627            TypeRef::Any => "serde_json::Value".into(),
628            TypeRef::Array(inner) => format!("Vec<{}>", self.spell(inner)?),
629            TypeRef::Map(inner) => {
630                format!("std::collections::BTreeMap<String, {}>", self.spell(inner)?)
631            }
632            TypeRef::Extern(key) => self.extern_spelling(key)?,
633        })
634    }
635
636    fn extern_spelling(&mut self, key: &str) -> Result<String, GenerateError> {
637        let spelling = self
638            .config
639            .substitutions
640            .get(key)
641            .and_then(|s| s.rust.as_ref())
642            .ok_or_else(|| {
643                GenerateError::Config(format!("substitution `{key}` has no `rust` spelling"))
644            })?;
645        if let Some(import) = &spelling.import {
646            self.externs.insert(key.to_owned(), import.clone());
647        }
648        Ok(spelling.name.clone())
649    }
650
651    fn doc(
652        description: Option<&str>,
653        default: Option<&serde_json::Value>,
654        read_only: bool,
655        write_only: bool,
656        constraints: &Constraints,
657    ) -> Vec<String> {
658        let mut lines: Vec<String> = description
659            .map(|d| d.lines().map(|l| l.trim_end().to_owned()).collect())
660            .unwrap_or_default();
661        let mut notes = Vec::new();
662        if let Some(default) = default {
663            notes.push(format!("Default: `{default}`."));
664        }
665        if read_only {
666            notes.push("Read only.".to_owned());
667        }
668        if write_only {
669            notes.push("Write only.".to_owned());
670        }
671        notes.extend(constraint_notes(constraints));
672        if !notes.is_empty() {
673            if !lines.is_empty() {
674                lines.push(String::new());
675            }
676            lines.extend(notes);
677        }
678        // Every entry becomes exactly one `///` line.
679        lines
680            .into_iter()
681            .flat_map(|l| l.split(['\n', '\r']).map(str::to_owned).collect::<Vec<_>>())
682            .collect()
683    }
684
685    fn codegen_attrs(
686        &mut self,
687        extensions: &BTreeMap<String, serde_json::Value>,
688        at: &SchemaId,
689        field: bool,
690    ) -> Vec<String> {
691        let Some(value) = extensions.get("x-rust-attrs") else {
692            return Vec::new();
693        };
694        if !self.config.allow_codegen_extensions {
695            self.diagnostics.push(Diagnostic {
696                severity: Severity::Warning,
697                kind: DiagnosticKind::IgnoredExtension { keyword: "x-rust-attrs".into() },
698                schema_id: at.clone(),
699                pointer: crate::diagnostic::source_of(&format!("{}/x-rust-attrs", at.pointer)),
700                message: "`x-rust-attrs` is code from the description and is not applied unless `allow_codegen_extensions` is set".into(),
701            });
702            return Vec::new();
703        }
704        let attrs: Vec<String> = match value {
705            serde_json::Value::String(s) => vec![s.clone()],
706            serde_json::Value::Array(items) => items
707                .iter()
708                .filter_map(|v| v.as_str().map(str::to_owned))
709                .collect(),
710            _ => Vec::new(),
711        };
712        // Code from the description passes the same checks as code from
713        // the configuration: valid Rust, and no backend-owned serde key.
714        // A failing one is dropped with a warning rather than failing the
715        // whole generation, since the description is not the user's file.
716        let mut kept = Vec::new();
717        for attr in attrs {
718            let one = std::slice::from_ref(&attr);
719            let checked = if field {
720                check_field_attrs(one, &crate::diagnostic::source_of(&at.pointer))
721            } else {
722                check_container_attrs(one, &crate::diagnostic::source_of(&at.pointer))
723            };
724            match checked {
725                Ok(()) => kept.push(attr),
726                Err(error) => self.diagnostics.push(Diagnostic {
727                    severity: Severity::Warning,
728                    kind: DiagnosticKind::IgnoredExtension {
729                        keyword: "x-rust-attrs".into(),
730                    },
731                    schema_id: at.clone(),
732                    pointer: crate::diagnostic::source_of(&format!("{}/x-rust-attrs", at.pointer)),
733                    message: format!("`x-rust-attrs` entry not applied: {error}"),
734                }),
735            }
736        }
737        kept
738    }
739
740    fn type_view(&mut self, def: &TypeDef) -> Result<Option<TypeView>, GenerateError> {
741        let name = match self.names.get(&def.id) {
742            Some(name) => name.clone(),
743            None => return Ok(None),
744        };
745        let raw_name = def
746            .component
747            .clone()
748            .unwrap_or_else(|| def.id.pointer.clone());
749        let mut doc = Vec::new();
750        if let Some(title) = def
751            .title
752            .as_deref()
753            .filter(|t| !t.trim().is_empty() && def.component.as_deref() != Some(t))
754        {
755            doc.extend(title.trim().lines().map(|l| l.trim_end().to_owned()));
756            doc.push(String::new());
757        }
758        doc.extend(Self::doc(
759            def.description.as_deref(),
760            None,
761            false,
762            false,
763            &def.constraints,
764        ));
765        if def.nullable {
766            doc.push(
767                "`null` is a valid instance; a position holding this type is an `Option`."
768                    .to_owned(),
769            );
770        }
771        while doc.last().is_some_and(String::is_empty) {
772            doc.pop();
773        }
774        let mut attrs = Vec::new();
775        if def.deprecated {
776            attrs.push("#[deprecated]".to_owned());
777        }
778        let user_attrs: Vec<String> = self
779            .type_config(def)
780            .map(|t| t.attrs.clone())
781            .unwrap_or_default();
782        check_container_attrs(&user_attrs, &raw_name)?;
783        attrs.extend(user_attrs);
784        attrs.extend(self.codegen_attrs(&def.extensions, &def.id, false));
785        // A union read by a parent's discriminator exists only where the
786        // parent does; each other variant is gated on its own.
787        if let TypeKind::UnionTagged(u) = &def.kind
788            && let Some(parent) = &u.parent
789        {
790            for gate in self.type_gates(parent, &raw_name)? {
791                if !attrs.contains(&gate) {
792                    attrs.push(gate);
793                }
794            }
795        }
796        let cfg = cfg_gates(&attrs, &raw_name)?;
797        let mut derives: Vec<String> = ["Debug", "Clone", "PartialEq"]
798            .iter()
799            .map(|s| (*s).to_owned())
800            .collect();
801        derives.extend(self.config.rust.derives.iter().cloned());
802        let mut view = TypeView {
803            kind: "struct",
804            name,
805            raw_name,
806            doc,
807            derives,
808            attrs,
809            fields: Vec::new(),
810            variants: Vec::new(),
811            branches: Vec::new(),
812            inner: String::new(),
813            tag: String::new(),
814            fallback: None,
815            parent_variant: None,
816            tag_literal: String::new(),
817            tag_doc: String::new(),
818            exclusive: false,
819            validate: None,
820            validate_null: Vec::new(),
821            object_only: false,
822            string_only: false,
823            catch_all: None,
824            pattern_tys: Vec::new(),
825            others_ty: None,
826            cfg,
827            file: None,
828        };
829        let result = self.fill_kind(def, &mut view)?;
830        if !result {
831            return Ok(None);
832        }
833        if self.config.validation {
834            self.support.validation = true;
835            let opted_out = self.type_config(def).and_then(|t| t.validation) == Some(false);
836            let emitted = |id: &SchemaId| self.names.contains_key(id);
837            let generated = |ty: &TypeRef| crate::checks::validates(self.ir, &emitted, ty);
838            let reshaped = |id: &SchemaId| self.reshaped(id);
839            view.validate =
840                super::validation::body(self.ir, def, &view, &generated, &reshaped, opted_out);
841            if view.validate.is_some() && !opted_out {
842                view.validate_null = super::validation::null_body(def);
843                // An alias spelled as a newtype has its target's null.
844                if let TypeKind::Alias(inner) = &def.kind
845                    && generated(inner)
846                {
847                    view.validate_null = vec![format!(
848                        "<{} as Validate>::validate_null(pointer, report);",
849                        view.inner
850                    )];
851                }
852            }
853            if opted_out && view.validate.is_none() {
854                return Err(crate::go::view::opt_out_on_alias(def));
855            }
856        }
857        let mut seen = std::collections::BTreeSet::new();
858        view.derives.retain(|d| seen.insert(d.clone()));
859        Ok(Some(view))
860    }
861
862    /// Fill the kind-specific parts of a view; `false` when the type is
863    /// not emitted at all.
864    fn fill_kind(&mut self, def: &TypeDef, view: &mut TypeView) -> Result<bool, GenerateError> {
865        match &def.kind {
866            TypeKind::Extern => return Ok(false),
867            TypeKind::Struct(s) => {
868                view.kind = "struct";
869                view.derives
870                    .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
871                let mut allocator = Allocator::default();
872                let mut declared = Vec::new();
873                for field in &s.fields {
874                    let rename = self
875                        .field_config(def, &field.raw_name)
876                        .and_then(|f| f.rename.clone());
877                    let base =
878                        rename.unwrap_or_else(|| snake(std::slice::from_ref(&field.raw_name)));
879                    let name = allocator.allocate(legal(base));
880                    let inner = self.spell(&field.ty)?;
881                    let (ty, mut attrs) = match (field.required, field.nullable) {
882                        (true, false) => (inner, vec![]),
883                        (true, true) => {
884                            self.support.require_present = true;
885                            (
886                                format!("Option<{inner}>"),
887                                vec![
888                                    "#[serde(deserialize_with = \"require_present::deserialize\")]"
889                                        .to_owned(),
890                                ],
891                            )
892                        }
893                        (false, false) => {
894                            self.support.reject_null = true;
895                            (
896                                format!("Option<{inner}>"),
897                                vec!["#[serde(default, skip_serializing_if = \"Option::is_none\", deserialize_with = \"reject_null::deserialize\")]".to_owned()],
898                            )
899                        }
900                        (false, true) => {
901                            self.support.double_option = true;
902                            (
903                                format!("Option<Option<{inner}>>"),
904                                vec!["#[serde(default, skip_serializing_if = \"Option::is_none\", deserialize_with = \"double_option::deserialize\")]".to_owned()],
905                            )
906                        }
907                    };
908                    if name.trim_start_matches("r#") != field.raw_name {
909                        attrs.insert(0, format!("#[serde(rename = {:?})]", field.raw_name));
910                    }
911                    if field.deprecated {
912                        attrs.push("#[deprecated]".to_owned());
913                    }
914                    let user_attrs: Vec<String> = self
915                        .field_config(def, &field.raw_name)
916                        .map(|f| f.attrs.clone())
917                        .unwrap_or_default();
918                    check_field_attrs(
919                        &user_attrs,
920                        &format!("{}.{}", view.raw_name, field.raw_name),
921                    )?;
922                    attrs.extend(user_attrs);
923                    let mut at = def.id.clone();
924                    at.pointer = field.pointer.clone();
925                    attrs.extend(self.codegen_attrs(&field.extensions, &at, true));
926                    let cfg = cfg_gates(&attrs, &format!("{}.{}", view.raw_name, field.raw_name))?;
927                    if matches!(s.additional, Additional::CatchAll(_)) {
928                        let mut names = vec![field.raw_name.clone()];
929                        names.extend(serde_aliases(
930                            &attrs,
931                            &format!("{}.{}", view.raw_name, field.raw_name),
932                        )?);
933                        declared.push(DeclaredView {
934                            cfg: cfg.clone(),
935                            names: names
936                                .iter()
937                                .map(|n| format!("{n:?}"))
938                                .collect::<Vec<_>>()
939                                .join(" | "),
940                        });
941                    }
942                    view.fields.push(FieldView {
943                        cfg,
944                        name,
945                        raw_name: field.raw_name.clone(),
946                        ty,
947                        doc: Self::doc(
948                            field.description.as_deref(),
949                            field.default.as_ref(),
950                            field.read_only,
951                            field.write_only,
952                            &field.constraints,
953                        ),
954                        attrs,
955                    });
956                }
957                match &s.additional {
958                    // With no catch-all to flatten, serde's derive reads a
959                    // sequence too: the derived code becomes inherent and a
960                    // guard decodes an object only.
961                    Additional::Denied => {
962                        view.attrs.push("#[serde(deny_unknown_fields)]".to_owned());
963                        view.attrs.push("#[serde(remote = \"Self\")]".to_owned());
964                        view.object_only = true;
965                        self.support.object_only = true;
966                    }
967                    Additional::CatchAll(ty) => {
968                        // Beside `patternProperties`, a member is held as
969                        // the text it was read from, to be read again as
970                        // each schema it is checked against.
971                        let inner = if s.patterns.is_empty() {
972                            self.spell(ty)?
973                        } else {
974                            self.support.raw_json = true;
975                            "RawJson".to_owned()
976                        };
977                        for pattern in &s.patterns {
978                            let spelled = match pattern.branch() {
979                                Some(b) => Some(self.spell(&b.ty)?),
980                                None => None,
981                            };
982                            view.pattern_tys.push(spelled);
983                        }
984                        if let crate::ir::Others::Schema(b) = &s.others {
985                            view.others_ty = Some(self.spell(&b.ty)?);
986                        }
987                        let name = allocator.allocate("additional_properties".to_owned());
988                        view.fields.push(FieldView {
989                            name: name.clone(),
990                            raw_name: "additionalProperties".to_owned(),
991                            ty: format!("std::collections::BTreeMap<String, {inner}>"),
992                            doc: vec!["Members not named above.".to_owned()],
993                            // Serialized inline; read by the impls in
994                            // `rust/catch_all.rs.jinja`, not by `flatten`.
995                            attrs: vec!["#[serde(flatten, skip_deserializing)]".to_owned()],
996                            cfg: Vec::new(),
997                        });
998                        // serde's `flatten` buffers the members it does not
999                        // know, and an integer or a raw holder cannot be read
1000                        // from the buffer: the derived code becomes inherent,
1001                        // and the declared members are handed to it while the
1002                        // rest decode into the catch-all as they stream by.
1003                        view.attrs.push("#[serde(remote = \"Self\")]".to_owned());
1004                        let allowed = match &s.only_patterns {
1005                            None => "|_: &str| true".to_owned(),
1006                            Some(patterns) => {
1007                                super::validation::mark_uses_regex();
1008                                let list = patterns
1009                                    .iter()
1010                                    .map(|p| format!("{p:?}"))
1011                                    .collect::<Vec<_>>()
1012                                    .join(", ");
1013                                // A pattern the engine cannot compile lets
1014                                // every member in rather than refuse one it
1015                                // allows.
1016                                format!(
1017                                    "|name: &str| {{ static PATTERNS: std::sync::LazyLock<Option<Vec<regex::Regex>>> = std::sync::LazyLock::new(|| [{list}].iter().map(|p| regex::Regex::new(p).ok()).collect()); PATTERNS.as_ref().is_none_or(|patterns| patterns.iter().any(|re| re.is_match(name))) }}"
1018                                )
1019                            }
1020                        };
1021                        view.catch_all = Some(CatchAllView {
1022                            field: name,
1023                            ty: inner,
1024                            declared,
1025                            allowed,
1026                        });
1027                        self.support.catch_all = true;
1028                    }
1029                }
1030            }
1031            TypeKind::StringEnum(values) => {
1032                view.kind = "enum";
1033                // serde's derive also reads a single-member object as a
1034                // variant: the derived code becomes inherent and a guard
1035                // reads a JSON string only.
1036                view.attrs.push("#[serde(remote = \"Self\")]".to_owned());
1037                view.string_only = true;
1038                self.support.string_only = true;
1039                view.derives.extend([
1040                    "Eq".to_owned(),
1041                    "Hash".to_owned(),
1042                    "Serialize".to_owned(),
1043                    "Deserialize".to_owned(),
1044                ]);
1045                let mut allocator = Allocator::default();
1046                for value in values {
1047                    let base = if value.trim().is_empty() {
1048                        "Empty".to_owned()
1049                    } else {
1050                        pascal(std::slice::from_ref(value))
1051                    };
1052                    let name = allocator.allocate(legal(base));
1053                    view.variants.push(VariantView {
1054                        name,
1055                        value: value.clone(),
1056                        ty: String::new(),
1057                        doc: Vec::new(),
1058                        attrs: vec![format!("#[serde(rename = {value:?})]")],
1059                        cfg: Vec::new(),
1060                        literal: format!("{value:?}"),
1061                        synthetic: false,
1062                        pattern: format!("{value:?}"),
1063                    });
1064                }
1065            }
1066            TypeKind::UnionTagged(u) => {
1067                view.kind = "union_tagged";
1068                view.derives.push("Serialize".to_owned());
1069                view.tag = u.tag.clone();
1070                view.tag_literal = format!("{:?}", u.tag);
1071                view.tag_doc = code_span(&u.tag.escape_debug().to_string());
1072                view.fallback = u.fallback;
1073                view.parent_variant = u.parent.as_ref().and_then(|p| {
1074                    u.variants
1075                        .iter()
1076                        .position(|v| v.ty.direct_named() == Some(p))
1077                });
1078                let mut allocator = Allocator::default();
1079                for (index, variant) in u.variants.iter().enumerate() {
1080                    let name = allocator.allocate(legal(pascal(&variant.suggested_name)));
1081                    let ty = self.spell(&variant.ty)?;
1082                    // Beside a parent, a variant gated out leaves its tag to
1083                    // the fallback; the union itself carries the parent's
1084                    // gates.
1085                    let cfg = match variant.ty.direct_named() {
1086                        Some(id) if u.parent.is_some() => self
1087                            .type_gates(id, &view.raw_name)?
1088                            .into_iter()
1089                            .filter(|g| !view.cfg.contains(g))
1090                            .collect(),
1091                        _ => Vec::new(),
1092                    };
1093                    view.variants.push(VariantView {
1094                        name,
1095                        value: variant.value.clone(),
1096                        ty,
1097                        doc: vec![if !variant.synthetic {
1098                            std::iter::once(&variant.value)
1099                                .chain(&variant.aliases)
1100                                .map(|tag| code_span(&format!("{}: {tag:?}", u.tag.escape_debug())))
1101                                .collect::<Vec<_>>()
1102                                .join(" or ")
1103                        } else if u.fallback == Some(index) {
1104                            format!("Read when {} names no other variant.", view.tag_doc)
1105                        } else {
1106                            "No tag selects this variant: it is read only when the fallback is not available.".to_owned()
1107                        }],
1108                        attrs: cfg.clone(),
1109                        cfg,
1110                        literal: format!("{:?}", variant.value),
1111                        synthetic: variant.synthetic,
1112                        pattern: std::iter::once(&variant.value)
1113                            .chain(&variant.aliases)
1114                            .map(|tag| format!("{tag:?}"))
1115                            .collect::<Vec<_>>()
1116                            .join(" | "),
1117                    });
1118                }
1119            }
1120            TypeKind::UnionOpen(u) => {
1121                view.kind = "union_open";
1122                // The raw value has no `PartialEq`; the template compares text.
1123                view.derives.retain(|d| d != "PartialEq");
1124                view.derives
1125                    .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
1126                view.exclusive = u.exclusive;
1127                self.support.raw_holder = true;
1128                view.branches = self.branches(&u.branches)?;
1129            }
1130            TypeKind::ComposedOpen(branches) => {
1131                view.kind = "composed_open";
1132                // The raw value has no `PartialEq`; the template compares text.
1133                view.derives.retain(|d| d != "PartialEq");
1134                view.derives
1135                    .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
1136                self.support.raw_holder = true;
1137                view.branches = self.branches(branches)?;
1138            }
1139            TypeKind::Newtype(inner) => {
1140                view.kind = "newtype";
1141                view.derives
1142                    .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
1143                view.attrs.push("#[serde(transparent)]".to_owned());
1144                view.inner = self.spell(inner)?;
1145            }
1146            TypeKind::Alias(inner) => {
1147                view.inner = self.spell(inner)?;
1148                if view.attrs.is_empty() {
1149                    view.kind = "alias";
1150                    view.derives.clear();
1151                } else {
1152                    // A type alias cannot carry most attributes, and a derive
1153                    // on one does not compile; a transparent newtype carries
1154                    // them all.
1155                    view.kind = "newtype";
1156                    view.derives
1157                        .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
1158                    view.attrs.push("#[serde(transparent)]".to_owned());
1159                }
1160            }
1161        }
1162        Ok(true)
1163    }
1164
1165    fn branches(
1166        &mut self,
1167        branches: &[crate::ir::Branch],
1168    ) -> Result<Vec<BranchView>, GenerateError> {
1169        let mut allocator = Allocator::default();
1170        // `ComposedOpen` defines `fn raw(&self)` and `fn from_raw(...)` directly.
1171        allocator.reserve("raw");
1172        let mut out = Vec::new();
1173        for branch in branches {
1174            let base = snake(&branch.suggested_name);
1175            let name = allocator.allocate(base);
1176            let ty = self.spell(&branch.ty)?;
1177            out.push(BranchView {
1178                accessor: format!("as_{name}"),
1179                constructor: format!("from_{name}"),
1180                doc: vec![format!("The value read as `{ty}`, when it is one.")],
1181                ty,
1182            });
1183        }
1184        Ok(out)
1185    }
1186}
1187
1188/// `text` as a Markdown code span, fenced by more backticks than any run
1189/// in it.
1190fn code_span(text: &str) -> String {
1191    let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
1192    let fence = "`".repeat(longest + 1);
1193    let pad = if text.starts_with('`') || text.ends_with('`') {
1194        " "
1195    } else {
1196        ""
1197    };
1198    format!("{fence}{pad}{text}{pad}{fence}")
1199}