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    builder.allocate_type_names();
272    // Reset: only what this build renders counts.
273    super::validation::take_uses_regex();
274    let mut types = Vec::new();
275    for id in &ir.order {
276        if ir.suppressed.contains(id) {
277            continue;
278        }
279        let def = &ir.types[id];
280        if let Some(view) = builder.type_view(def)? {
281            types.push(view);
282        }
283    }
284    let uses_regex = super::validation::take_uses_regex();
285    let module = (config.layout == Layout::FilePerType).then(|| {
286        assign_files(&mut types);
287        config.rust.module.clone()
288    });
289    let mut dependencies = vec![
290        RustDependency {
291            name: "serde".into(),
292            features: vec!["derive".into()],
293        },
294        RustDependency {
295            name: "serde_json".into(),
296            // Validation compares a decoded number with a bound read
297            // exactly: the decoder must read it exactly too.
298            features: if builder.config.validation {
299                vec!["raw_value".into(), "float_roundtrip".into()]
300            } else {
301                vec!["raw_value".into()]
302            },
303        },
304    ];
305    // A checked `pattern` is matched with `regex`.
306    if uses_regex {
307        dependencies.push(RustDependency {
308            name: "regex".into(),
309            features: Vec::new(),
310        });
311    }
312    for import in builder.externs.values() {
313        let dependency = RustDependency {
314            name: import.clone(),
315            features: Vec::new(),
316        };
317        if !dependencies.contains(&dependency) {
318            dependencies.push(dependency);
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
394impl Builder<'_> {
395    fn allocate_type_names(&mut self) {
396        let mut allocator = Allocator::default();
397        // Names the generated code itself uses unqualified: its own
398        // helpers, the prelude types it spells, and its imports.
399        if self.config.exact_numbers {
400            allocator.reserve("Decimal");
401        }
402        for reserved in [
403            "Int64",
404            "Int32",
405            "Nullable",
406            "String",
407            "Option",
408            "Some",
409            "None",
410            "Vec",
411            "Box",
412            "Result",
413            "Ok",
414            "Err",
415            "Self",
416            "Serialize",
417            "Deserialize",
418            "Default",
419            "Clone",
420            "Debug",
421            "PartialEq",
422            "Eq",
423            "Hash",
424            "Copy",
425            "From",
426            "Into",
427            "double_option",
428            "reject_null",
429            "require_present",
430            "integer_token",
431        ] {
432            allocator.reserve(reserved);
433        }
434        // Generated only beside `patternProperties`.
435        if self
436            .ir
437            .types
438            .values()
439            .any(|def| matches!(&def.kind, TypeKind::Struct(s) if !s.patterns.is_empty()))
440        {
441            allocator.reserve("RawJson");
442        }
443        if self.config.validation {
444            for reserved in [
445                "Validate",
446                "ValidationReport",
447                "Finding",
448                "FindingKind",
449                "child_pointer",
450                "wide_number",
451            ] {
452                allocator.reserve(reserved);
453            }
454        }
455        // Components first: a component keeps its name whatever an inline
456        // schema is titled or positioned to be called.
457        let ir = self.ir;
458        let order = ir
459            .order
460            .iter()
461            .filter(|id| ir.types[*id].component.is_some());
462        let rest = ir
463            .order
464            .iter()
465            .filter(|id| ir.types[*id].component.is_none());
466        for id in order.chain(rest) {
467            let def = &self.ir.types[id];
468            if matches!(def.kind, TypeKind::Extern) {
469                continue;
470            }
471            let base = match def
472                .component
473                .as_ref()
474                .and_then(|c| self.config.types.get(c))
475                .and_then(|t| t.rename.clone())
476            {
477                Some(rename) => rename,
478                None => pascal(&def.suggested_name),
479            };
480            let name = allocator.allocate(legal(base));
481            self.names.insert(id.clone(), name);
482        }
483    }
484
485    /// The cfg gates a generated type carries: configured, or from the
486    /// description's `x-rust-attrs` as applied.
487    fn type_gates(&self, id: &SchemaId, at: &str) -> Result<Vec<String>, GenerateError> {
488        let Some(def) = self.ir.types.get(id) else {
489            return Ok(Vec::new());
490        };
491        let mut attrs: Vec<String> = self
492            .type_config(def)
493            .map(|t| t.attrs.clone())
494            .unwrap_or_default();
495        if self.config.allow_codegen_extensions {
496            let described: Vec<String> = match def.extensions.get("x-rust-attrs") {
497                Some(serde_json::Value::String(a)) => vec![a.clone()],
498                Some(serde_json::Value::Array(items)) => items
499                    .iter()
500                    .filter_map(|v| v.as_str().map(str::to_owned))
501                    .collect(),
502                _ => Vec::new(),
503            };
504            attrs.extend(
505                described
506                    .into_iter()
507                    .filter(|a| check_container_attrs(std::slice::from_ref(a), "").is_ok()),
508            );
509        }
510        cfg_gates(&attrs, at)
511    }
512
513    fn type_config(&self, def: &TypeDef) -> Option<&TypeConfig> {
514        def.component
515            .as_ref()
516            .and_then(|c| self.config.types.get(c))
517    }
518
519    /// Whether the struct `id` reads its members by other names than the
520    /// schema does: a field compiled out by a `cfg` gate (its member then
521    /// lands among the others) or read under a `serde(alias)`. A value
522    /// valid for the schema may then fail to decode. A configured
523    /// attribute that does not parse counts: generation fails on it anyway.
524    fn reshaped(&self, id: &SchemaId) -> bool {
525        let def = &self.ir.types[id];
526        let TypeKind::Struct(s) = &def.kind else {
527            return false;
528        };
529        s.fields.iter().any(|field| {
530            let mut attrs: Vec<String> = self
531                .field_config(def, &field.raw_name)
532                .map(|f| f.attrs.clone())
533                .unwrap_or_default();
534            if self.config.allow_codegen_extensions {
535                let described: Vec<String> = match field.extensions.get("x-rust-attrs") {
536                    Some(serde_json::Value::String(a)) => vec![a.clone()],
537                    Some(serde_json::Value::Array(items)) => items
538                        .iter()
539                        .filter_map(|v| v.as_str().map(str::to_owned))
540                        .collect(),
541                    _ => Vec::new(),
542                };
543                // Only the entries generation applies: a failing one is
544                // dropped there with a warning.
545                attrs.extend(
546                    described
547                        .into_iter()
548                        .filter(|a| check_field_attrs(std::slice::from_ref(a), "").is_ok()),
549                );
550            }
551            attrs.iter().any(|attr| {
552                let one = std::slice::from_ref(attr);
553                !matches!(cfg_gates(one, ""), Ok(g) if g.is_empty())
554                    || !matches!(serde_aliases(one, ""), Ok(a) if a.is_empty())
555            })
556        })
557    }
558
559    fn field_config<'c>(&'c self, def: &TypeDef, raw_name: &str) -> Option<&'c FieldConfig> {
560        self.type_config(def).and_then(|t| t.fields.get(raw_name))
561    }
562
563    /// Spell a type for Rust.
564    fn spell(&mut self, ty: &TypeRef) -> Result<String, GenerateError> {
565        Ok(match ty {
566            TypeRef::Named(id) => match &self.ir.types[id].kind {
567                TypeKind::Extern => {
568                    let component = self.ir.types[id].component.clone().unwrap_or_default();
569                    self.extern_spelling(&component)?
570                }
571                _ => self.names[id].clone(),
572            },
573            TypeRef::Boxed(inner) => format!("Box<{}>", self.spell(inner)?),
574            TypeRef::Nullable(inner) => format!("Option<{}>", self.spell(inner)?),
575            TypeRef::String => "String".into(),
576            TypeRef::Integer(IntWidth::Int64) => {
577                self.support.int64 = true;
578                "Int64".into()
579            }
580            TypeRef::Integer(IntWidth::Int32) => {
581                self.support.int32 = true;
582                "Int32".into()
583            }
584            TypeRef::Number(FloatWidth::Double) => "f64".into(),
585            TypeRef::Number(FloatWidth::Float) => "f32".into(),
586            TypeRef::Decimal => {
587                self.support.decimal = true;
588                "Decimal".into()
589            }
590            TypeRef::Boolean => "bool".into(),
591            TypeRef::Null => "()".into(),
592            TypeRef::Any => "serde_json::Value".into(),
593            TypeRef::Array(inner) => format!("Vec<{}>", self.spell(inner)?),
594            TypeRef::Map(inner) => {
595                format!("std::collections::BTreeMap<String, {}>", self.spell(inner)?)
596            }
597            TypeRef::Extern(key) => self.extern_spelling(key)?,
598        })
599    }
600
601    fn extern_spelling(&mut self, key: &str) -> Result<String, GenerateError> {
602        let spelling = self
603            .config
604            .substitutions
605            .get(key)
606            .and_then(|s| s.rust.as_ref())
607            .ok_or_else(|| {
608                GenerateError::Config(format!("substitution `{key}` has no `rust` spelling"))
609            })?;
610        if let Some(import) = &spelling.import {
611            self.externs.insert(key.to_owned(), import.clone());
612        }
613        Ok(spelling.name.clone())
614    }
615
616    fn doc(
617        description: Option<&str>,
618        default: Option<&serde_json::Value>,
619        read_only: bool,
620        write_only: bool,
621        constraints: &Constraints,
622    ) -> Vec<String> {
623        let mut lines: Vec<String> = description
624            .map(|d| d.lines().map(|l| l.trim_end().to_owned()).collect())
625            .unwrap_or_default();
626        let mut notes = Vec::new();
627        if let Some(default) = default {
628            notes.push(format!("Default: `{default}`."));
629        }
630        if read_only {
631            notes.push("Read only.".to_owned());
632        }
633        if write_only {
634            notes.push("Write only.".to_owned());
635        }
636        notes.extend(constraint_notes(constraints));
637        if !notes.is_empty() {
638            if !lines.is_empty() {
639                lines.push(String::new());
640            }
641            lines.extend(notes);
642        }
643        // Every entry becomes exactly one `///` line.
644        lines
645            .into_iter()
646            .flat_map(|l| l.split(['\n', '\r']).map(str::to_owned).collect::<Vec<_>>())
647            .collect()
648    }
649
650    fn codegen_attrs(
651        &mut self,
652        extensions: &BTreeMap<String, serde_json::Value>,
653        at: &SchemaId,
654        field: bool,
655    ) -> Vec<String> {
656        let Some(value) = extensions.get("x-rust-attrs") else {
657            return Vec::new();
658        };
659        if !self.config.allow_codegen_extensions {
660            self.diagnostics.push(Diagnostic {
661                severity: Severity::Warning,
662                kind: DiagnosticKind::IgnoredExtension { keyword: "x-rust-attrs".into() },
663                schema_id: at.clone(),
664                pointer: crate::diagnostic::source_of(&format!("{}/x-rust-attrs", at.pointer)),
665                message: "`x-rust-attrs` is code from the description and is not applied unless `allow_codegen_extensions` is set".into(),
666            });
667            return Vec::new();
668        }
669        let attrs: Vec<String> = match value {
670            serde_json::Value::String(s) => vec![s.clone()],
671            serde_json::Value::Array(items) => items
672                .iter()
673                .filter_map(|v| v.as_str().map(str::to_owned))
674                .collect(),
675            _ => Vec::new(),
676        };
677        // Code from the description passes the same checks as code from
678        // the configuration: valid Rust, and no backend-owned serde key.
679        // A failing one is dropped with a warning rather than failing the
680        // whole generation, since the description is not the user's file.
681        let mut kept = Vec::new();
682        for attr in attrs {
683            let one = std::slice::from_ref(&attr);
684            let checked = if field {
685                check_field_attrs(one, &crate::diagnostic::source_of(&at.pointer))
686            } else {
687                check_container_attrs(one, &crate::diagnostic::source_of(&at.pointer))
688            };
689            match checked {
690                Ok(()) => kept.push(attr),
691                Err(error) => self.diagnostics.push(Diagnostic {
692                    severity: Severity::Warning,
693                    kind: DiagnosticKind::IgnoredExtension {
694                        keyword: "x-rust-attrs".into(),
695                    },
696                    schema_id: at.clone(),
697                    pointer: crate::diagnostic::source_of(&format!("{}/x-rust-attrs", at.pointer)),
698                    message: format!("`x-rust-attrs` entry not applied: {error}"),
699                }),
700            }
701        }
702        kept
703    }
704
705    fn type_view(&mut self, def: &TypeDef) -> Result<Option<TypeView>, GenerateError> {
706        let name = match self.names.get(&def.id) {
707            Some(name) => name.clone(),
708            None => return Ok(None),
709        };
710        let raw_name = def
711            .component
712            .clone()
713            .unwrap_or_else(|| def.id.pointer.clone());
714        let mut doc = Vec::new();
715        if let Some(title) = def
716            .title
717            .as_deref()
718            .filter(|t| !t.trim().is_empty() && def.component.as_deref() != Some(t))
719        {
720            doc.extend(title.trim().lines().map(|l| l.trim_end().to_owned()));
721            doc.push(String::new());
722        }
723        doc.extend(Self::doc(
724            def.description.as_deref(),
725            None,
726            false,
727            false,
728            &def.constraints,
729        ));
730        if def.nullable {
731            doc.push(
732                "`null` is a valid instance; a position holding this type is an `Option`."
733                    .to_owned(),
734            );
735        }
736        while doc.last().is_some_and(String::is_empty) {
737            doc.pop();
738        }
739        let mut attrs = Vec::new();
740        if def.deprecated {
741            attrs.push("#[deprecated]".to_owned());
742        }
743        let user_attrs: Vec<String> = self
744            .type_config(def)
745            .map(|t| t.attrs.clone())
746            .unwrap_or_default();
747        check_container_attrs(&user_attrs, &raw_name)?;
748        attrs.extend(user_attrs);
749        attrs.extend(self.codegen_attrs(&def.extensions, &def.id, false));
750        // A union read by a parent's discriminator exists only where the
751        // parent does; each other variant is gated on its own.
752        if let TypeKind::UnionTagged(u) = &def.kind
753            && let Some(parent) = &u.parent
754        {
755            for gate in self.type_gates(parent, &raw_name)? {
756                if !attrs.contains(&gate) {
757                    attrs.push(gate);
758                }
759            }
760        }
761        let cfg = cfg_gates(&attrs, &raw_name)?;
762        let mut derives: Vec<String> = ["Debug", "Clone", "PartialEq"]
763            .iter()
764            .map(|s| (*s).to_owned())
765            .collect();
766        derives.extend(self.config.rust.derives.iter().cloned());
767        let mut view = TypeView {
768            kind: "struct",
769            name,
770            raw_name,
771            doc,
772            derives,
773            attrs,
774            fields: Vec::new(),
775            variants: Vec::new(),
776            branches: Vec::new(),
777            inner: String::new(),
778            tag: String::new(),
779            fallback: None,
780            parent_variant: None,
781            tag_literal: String::new(),
782            tag_doc: String::new(),
783            exclusive: false,
784            validate: None,
785            validate_null: Vec::new(),
786            object_only: false,
787            string_only: false,
788            catch_all: None,
789            pattern_tys: Vec::new(),
790            others_ty: None,
791            cfg,
792            file: None,
793        };
794        let result = self.fill_kind(def, &mut view)?;
795        if !result {
796            return Ok(None);
797        }
798        if self.config.validation {
799            self.support.validation = true;
800            let opted_out = self.type_config(def).and_then(|t| t.validation) == Some(false);
801            let emitted = |id: &SchemaId| self.names.contains_key(id);
802            let generated = |ty: &TypeRef| crate::checks::validates(self.ir, &emitted, ty);
803            let reshaped = |id: &SchemaId| self.reshaped(id);
804            view.validate =
805                super::validation::body(self.ir, def, &view, &generated, &reshaped, opted_out);
806            if view.validate.is_some() && !opted_out {
807                view.validate_null = super::validation::null_body(def);
808                // An alias spelled as a newtype has its target's null.
809                if let TypeKind::Alias(inner) = &def.kind
810                    && generated(inner)
811                {
812                    view.validate_null = vec![format!(
813                        "<{} as Validate>::validate_null(pointer, report);",
814                        view.inner
815                    )];
816                }
817            }
818            if opted_out && view.validate.is_none() {
819                return Err(crate::go::view::opt_out_on_alias(def));
820            }
821        }
822        let mut seen = std::collections::BTreeSet::new();
823        view.derives.retain(|d| seen.insert(d.clone()));
824        Ok(Some(view))
825    }
826
827    /// Fill the kind-specific parts of a view; `false` when the type is
828    /// not emitted at all.
829    fn fill_kind(&mut self, def: &TypeDef, view: &mut TypeView) -> Result<bool, GenerateError> {
830        match &def.kind {
831            TypeKind::Extern => return Ok(false),
832            TypeKind::Struct(s) => {
833                view.kind = "struct";
834                view.derives
835                    .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
836                let mut allocator = Allocator::default();
837                let mut declared = Vec::new();
838                for field in &s.fields {
839                    let rename = self
840                        .field_config(def, &field.raw_name)
841                        .and_then(|f| f.rename.clone());
842                    let base =
843                        rename.unwrap_or_else(|| snake(std::slice::from_ref(&field.raw_name)));
844                    let name = allocator.allocate(legal(base));
845                    let inner = self.spell(&field.ty)?;
846                    let (ty, mut attrs) = match (field.required, field.nullable) {
847                        (true, false) => (inner, vec![]),
848                        (true, true) => {
849                            self.support.require_present = true;
850                            (
851                                format!("Option<{inner}>"),
852                                vec![
853                                    "#[serde(deserialize_with = \"require_present::deserialize\")]"
854                                        .to_owned(),
855                                ],
856                            )
857                        }
858                        (false, false) => {
859                            self.support.reject_null = true;
860                            (
861                                format!("Option<{inner}>"),
862                                vec!["#[serde(default, skip_serializing_if = \"Option::is_none\", deserialize_with = \"reject_null::deserialize\")]".to_owned()],
863                            )
864                        }
865                        (false, true) => {
866                            self.support.double_option = true;
867                            (
868                                format!("Option<Option<{inner}>>"),
869                                vec!["#[serde(default, skip_serializing_if = \"Option::is_none\", deserialize_with = \"double_option::deserialize\")]".to_owned()],
870                            )
871                        }
872                    };
873                    if name.trim_start_matches("r#") != field.raw_name {
874                        attrs.insert(0, format!("#[serde(rename = {:?})]", field.raw_name));
875                    }
876                    if field.deprecated {
877                        attrs.push("#[deprecated]".to_owned());
878                    }
879                    let user_attrs: Vec<String> = self
880                        .field_config(def, &field.raw_name)
881                        .map(|f| f.attrs.clone())
882                        .unwrap_or_default();
883                    check_field_attrs(
884                        &user_attrs,
885                        &format!("{}.{}", view.raw_name, field.raw_name),
886                    )?;
887                    attrs.extend(user_attrs);
888                    let mut at = def.id.clone();
889                    at.pointer = field.pointer.clone();
890                    attrs.extend(self.codegen_attrs(&field.extensions, &at, true));
891                    let cfg = cfg_gates(&attrs, &format!("{}.{}", view.raw_name, field.raw_name))?;
892                    if matches!(s.additional, Additional::CatchAll(_)) {
893                        let mut names = vec![field.raw_name.clone()];
894                        names.extend(serde_aliases(
895                            &attrs,
896                            &format!("{}.{}", view.raw_name, field.raw_name),
897                        )?);
898                        declared.push(DeclaredView {
899                            cfg: cfg.clone(),
900                            names: names
901                                .iter()
902                                .map(|n| format!("{n:?}"))
903                                .collect::<Vec<_>>()
904                                .join(" | "),
905                        });
906                    }
907                    view.fields.push(FieldView {
908                        cfg,
909                        name,
910                        raw_name: field.raw_name.clone(),
911                        ty,
912                        doc: Self::doc(
913                            field.description.as_deref(),
914                            field.default.as_ref(),
915                            field.read_only,
916                            field.write_only,
917                            &field.constraints,
918                        ),
919                        attrs,
920                    });
921                }
922                match &s.additional {
923                    // With no catch-all to flatten, serde's derive reads a
924                    // sequence too: the derived code becomes inherent and a
925                    // guard decodes an object only.
926                    Additional::Denied => {
927                        view.attrs.push("#[serde(deny_unknown_fields)]".to_owned());
928                        view.attrs.push("#[serde(remote = \"Self\")]".to_owned());
929                        view.object_only = true;
930                        self.support.object_only = true;
931                    }
932                    Additional::CatchAll(ty) => {
933                        // Beside `patternProperties`, a member is held as
934                        // the text it was read from, to be read again as
935                        // each schema it is checked against.
936                        let inner = if s.patterns.is_empty() {
937                            self.spell(ty)?
938                        } else {
939                            self.support.raw_json = true;
940                            "RawJson".to_owned()
941                        };
942                        for pattern in &s.patterns {
943                            let spelled = match pattern.branch() {
944                                Some(b) => Some(self.spell(&b.ty)?),
945                                None => None,
946                            };
947                            view.pattern_tys.push(spelled);
948                        }
949                        if let crate::ir::Others::Schema(b) = &s.others {
950                            view.others_ty = Some(self.spell(&b.ty)?);
951                        }
952                        let name = allocator.allocate("additional_properties".to_owned());
953                        view.fields.push(FieldView {
954                            name: name.clone(),
955                            raw_name: "additionalProperties".to_owned(),
956                            ty: format!("std::collections::BTreeMap<String, {inner}>"),
957                            doc: vec!["Members not named above.".to_owned()],
958                            // Serialized inline; read by the impls in
959                            // `rust/catch_all.rs.jinja`, not by `flatten`.
960                            attrs: vec!["#[serde(flatten, skip_deserializing)]".to_owned()],
961                            cfg: Vec::new(),
962                        });
963                        // serde's `flatten` buffers the members it does not
964                        // know, and an integer or a raw holder cannot be read
965                        // from the buffer: the derived code becomes inherent,
966                        // and the declared members are handed to it while the
967                        // rest decode into the catch-all as they stream by.
968                        view.attrs.push("#[serde(remote = \"Self\")]".to_owned());
969                        let allowed = match &s.only_patterns {
970                            None => "|_: &str| true".to_owned(),
971                            Some(patterns) => {
972                                super::validation::mark_uses_regex();
973                                let list = patterns
974                                    .iter()
975                                    .map(|p| format!("{p:?}"))
976                                    .collect::<Vec<_>>()
977                                    .join(", ");
978                                // A pattern the engine cannot compile lets
979                                // every member in rather than refuse one it
980                                // allows.
981                                format!(
982                                    "|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))) }}"
983                                )
984                            }
985                        };
986                        view.catch_all = Some(CatchAllView {
987                            field: name,
988                            ty: inner,
989                            declared,
990                            allowed,
991                        });
992                        self.support.catch_all = true;
993                    }
994                }
995            }
996            TypeKind::StringEnum(values) => {
997                view.kind = "enum";
998                // serde's derive also reads a single-member object as a
999                // variant: the derived code becomes inherent and a guard
1000                // reads a JSON string only.
1001                view.attrs.push("#[serde(remote = \"Self\")]".to_owned());
1002                view.string_only = true;
1003                self.support.string_only = true;
1004                view.derives.extend([
1005                    "Eq".to_owned(),
1006                    "Hash".to_owned(),
1007                    "Serialize".to_owned(),
1008                    "Deserialize".to_owned(),
1009                ]);
1010                let mut allocator = Allocator::default();
1011                for value in values {
1012                    let base = if value.trim().is_empty() {
1013                        "Empty".to_owned()
1014                    } else {
1015                        pascal(std::slice::from_ref(value))
1016                    };
1017                    let name = allocator.allocate(legal(base));
1018                    view.variants.push(VariantView {
1019                        name,
1020                        value: value.clone(),
1021                        ty: String::new(),
1022                        doc: Vec::new(),
1023                        attrs: vec![format!("#[serde(rename = {value:?})]")],
1024                        cfg: Vec::new(),
1025                        literal: format!("{value:?}"),
1026                        synthetic: false,
1027                        pattern: format!("{value:?}"),
1028                    });
1029                }
1030            }
1031            TypeKind::UnionTagged(u) => {
1032                view.kind = "union_tagged";
1033                view.derives.push("Serialize".to_owned());
1034                view.tag = u.tag.clone();
1035                view.tag_literal = format!("{:?}", u.tag);
1036                view.tag_doc = code_span(&u.tag.escape_debug().to_string());
1037                view.fallback = u.fallback;
1038                view.parent_variant = u.parent.as_ref().and_then(|p| {
1039                    u.variants
1040                        .iter()
1041                        .position(|v| v.ty.direct_named() == Some(p))
1042                });
1043                let mut allocator = Allocator::default();
1044                for (index, variant) in u.variants.iter().enumerate() {
1045                    let name = allocator.allocate(legal(pascal(&variant.suggested_name)));
1046                    let ty = self.spell(&variant.ty)?;
1047                    // Beside a parent, a variant gated out leaves its tag to
1048                    // the fallback; the union itself carries the parent's
1049                    // gates.
1050                    let cfg = match variant.ty.direct_named() {
1051                        Some(id) if u.parent.is_some() => self
1052                            .type_gates(id, &view.raw_name)?
1053                            .into_iter()
1054                            .filter(|g| !view.cfg.contains(g))
1055                            .collect(),
1056                        _ => Vec::new(),
1057                    };
1058                    view.variants.push(VariantView {
1059                        name,
1060                        value: variant.value.clone(),
1061                        ty,
1062                        doc: vec![if !variant.synthetic {
1063                            std::iter::once(&variant.value)
1064                                .chain(&variant.aliases)
1065                                .map(|tag| code_span(&format!("{}: {tag:?}", u.tag.escape_debug())))
1066                                .collect::<Vec<_>>()
1067                                .join(" or ")
1068                        } else if u.fallback == Some(index) {
1069                            format!("Read when {} names no other variant.", view.tag_doc)
1070                        } else {
1071                            "No tag selects this variant: it is read only when the fallback is not available.".to_owned()
1072                        }],
1073                        attrs: cfg.clone(),
1074                        cfg,
1075                        literal: format!("{:?}", variant.value),
1076                        synthetic: variant.synthetic,
1077                        pattern: std::iter::once(&variant.value)
1078                            .chain(&variant.aliases)
1079                            .map(|tag| format!("{tag:?}"))
1080                            .collect::<Vec<_>>()
1081                            .join(" | "),
1082                    });
1083                }
1084            }
1085            TypeKind::UnionOpen(u) => {
1086                view.kind = "union_open";
1087                // The raw value has no `PartialEq`; the template compares text.
1088                view.derives.retain(|d| d != "PartialEq");
1089                view.derives
1090                    .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
1091                view.exclusive = u.exclusive;
1092                self.support.raw_holder = true;
1093                view.branches = self.branches(&u.branches)?;
1094            }
1095            TypeKind::ComposedOpen(branches) => {
1096                view.kind = "composed_open";
1097                // The raw value has no `PartialEq`; the template compares text.
1098                view.derives.retain(|d| d != "PartialEq");
1099                view.derives
1100                    .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
1101                self.support.raw_holder = true;
1102                view.branches = self.branches(branches)?;
1103            }
1104            TypeKind::Newtype(inner) => {
1105                view.kind = "newtype";
1106                view.derives
1107                    .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
1108                view.attrs.push("#[serde(transparent)]".to_owned());
1109                view.inner = self.spell(inner)?;
1110            }
1111            TypeKind::Alias(inner) => {
1112                view.inner = self.spell(inner)?;
1113                if view.attrs.is_empty() {
1114                    view.kind = "alias";
1115                    view.derives.clear();
1116                } else {
1117                    // A type alias cannot carry most attributes, and a derive
1118                    // on one does not compile; a transparent newtype carries
1119                    // them all.
1120                    view.kind = "newtype";
1121                    view.derives
1122                        .extend(["Serialize".to_owned(), "Deserialize".to_owned()]);
1123                    view.attrs.push("#[serde(transparent)]".to_owned());
1124                }
1125            }
1126        }
1127        Ok(true)
1128    }
1129
1130    fn branches(
1131        &mut self,
1132        branches: &[crate::ir::Branch],
1133    ) -> Result<Vec<BranchView>, GenerateError> {
1134        let mut allocator = Allocator::default();
1135        let mut out = Vec::new();
1136        for branch in branches {
1137            let base = snake(&branch.suggested_name);
1138            let name = allocator.allocate(base);
1139            let ty = self.spell(&branch.ty)?;
1140            out.push(BranchView {
1141                accessor: format!("as_{name}"),
1142                constructor: format!("from_{name}"),
1143                doc: vec![format!("The value read as `{ty}`, when it is one.")],
1144                ty,
1145            });
1146        }
1147        Ok(out)
1148    }
1149}
1150
1151/// `text` as a Markdown code span, fenced by more backticks than any run
1152/// in it.
1153fn code_span(text: &str) -> String {
1154    let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
1155    let fence = "`".repeat(longest + 1);
1156    let pad = if text.starts_with('`') || text.ends_with('`') {
1157        " "
1158    } else {
1159        ""
1160    };
1161    format!("{fence}{pad}{text}{pad}{fence}")
1162}