Skip to main content

roas_codegen/go/
view.rs

1//! The view model for Go: every type spelled, every name final, every
2//! literal quoted. A template lays this out and nothing more.
3//!
4//! The decisions are the Rust backend's, carried over: the four
5//! nullability cases, integers read from their tokens, tagged unions
6//! decoded by reading the tag and then the whole value, and open holders
7//! keeping the raw JSON. What differs is only how Go spells them — and
8//! that Go's decoder stores a zero value for a JSON null where Rust's
9//! refuses it, which the generated code turns back into an error.
10
11use crate::config::{Config, FieldConfig, Layout, TypeConfig};
12use crate::diagnostic::{Diagnostic, SchemaId};
13use crate::front::{FloatWidth, IntWidth};
14use crate::generate::GenerateError;
15use crate::go::naming::{
16    comment_text, exported, is_exported_ident, is_tag_key, quote, tag_name_ok,
17};
18use crate::ir::{Additional, Ir, TypeDef, TypeKind, TypeRef};
19use crate::rust::naming::Allocator;
20use crate::rust::view::{constraint_notes, select_check};
21use serde::Serialize;
22use std::collections::{BTreeMap, BTreeSet};
23
24/// The packages every generated file imports, by import path and the
25/// name they are used under.
26const BUILTIN_IMPORTS: &[(&str, &str)] = &[
27    ("encoding/json/jsontext", "jsontext"),
28    ("encoding/json/v2", "json"),
29    ("errors", "errors"),
30    ("fmt", "fmt"),
31];
32
33/// Lowercase names the templates declare, at package level or locally; an
34/// import used under one of them would not compile.
35/// The names generated validation adds, reserved only when it is on.
36const VALIDATION_NAMES: &[&str] = &[
37    "certain",
38    "uncertain",
39    "branch",
40    "repeated",
41    "childPointer",
42    "wideNumber",
43    "members",
44    "seen",
45    "item",
46    "p",
47    "x",
48    "f",
49    "zero",
50];
51
52/// Locals, receivers and parameters of the decoders and accessors that
53/// spell a substituted type, which a type of the package's own spelled
54/// the same would be shadowed by.
55const SPELLING_LOCALS: &[&str] = &[
56    "d", "e", "u", "v", "err", "name", "token", "value", "present",
57    // A tagged union's decoder, which spells a substituted variant.
58    "raw", "tag", "members", "member", "ok",
59];
60
61/// The package-level names the generated code declares besides its types.
62const HELPER_NAMES: &[&str] = &[
63    "decodeOptions",
64    "noUnmarshalers",
65    "isolatedNone",
66    "refuseNull",
67    "readTag",
68    "integerToken",
69    "matchPattern",
70    "patterns",
71    "memberMatches",
72    "decimalToken",
73    "decimalDigits",
74    "childPointer",
75    "wideNumber",
76];
77
78/// The names the generated code may import a package under.
79const BUILTIN_NAMES: &[&str] = &[
80    "jsontext", "json", "errors", "fmt", "maps", "slices", "math", "big", "strconv", "utf8",
81    "regexp", "sync",
82];
83
84/// Validation's loop variables, one per nesting depth: `i0`, `item0`,
85/// `k0`. A file under `layout = "file_per_type"` reads `item0.` as a use
86/// of a package of that name.
87fn depth_local(name: &str) -> bool {
88    ["item", "i", "k"].iter().any(|prefix| {
89        name.strip_prefix(prefix)
90            .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
91    })
92}
93
94/// The package-level names the pattern support declares, reserved only
95/// when it is generated.
96const PATTERN_NAMES: &[&str] = &["matchPattern", "patterns"];
97
98/// The names the `Decimal` support declares, at package level or locally,
99/// reserved only when it is generated.
100const DECIMAL_NAMES: &[&str] = &[
101    "decimalToken",
102    "decimalDigits",
103    "power",
104    "all",
105    "start",
106    "end",
107    "count",
108    "leading",
109    "sx",
110    "sy",
111    "lx",
112    "ly",
113    "dx",
114    "dy",
115    "c",
116    "b",
117    "shift",
118    "quotient",
119    "remainder",
120    "prime",
121    "taken",
122    "m",
123    "y",
124    "divisor",
125];
126
127const TEMPLATE_NAMES: &[&str] = &[
128    "decodeOptions",
129    "noUnmarshalers",
130    "isolatedNone",
131    "refuseNull",
132    "readTag",
133    "integerToken",
134    "v",
135    "u",
136    "d",
137    "e",
138    "n",
139    "raw",
140    "err",
141    "ok",
142    "zero",
143    "tag",
144    "typ",
145    "value",
146    "s",
147    "token",
148    "name",
149    "present",
150    "members",
151    "member",
152    "limit",
153    "text",
154    "negative",
155    "mantissa",
156    "exponent",
157    "digits",
158    "negativeExponent",
159    "whole",
160    "fraction",
161    "scale",
162    "ceiling",
163    "magnitude",
164    "digit",
165    "i",
166    "j",
167];
168
169#[derive(Debug, Clone, Serialize, Default)]
170pub(crate) struct SupportView {
171    pub nullable: bool,
172    pub int64: bool,
173    pub int32: bool,
174    /// A `number` held exactly, under `exact_numbers`: `Decimal`.
175    pub decimal: bool,
176    /// `exact_numbers` is on: the support reads numbers as decimals may.
177    pub exact_numbers: bool,
178    pub null: bool,
179    pub tagged: bool,
180    /// A self-writing struct has a catch-all, written in key order.
181    pub sorted_keys: bool,
182    /// Types a JSON null would silently set to their zero value, which
183    /// the generated decoders refuse.
184    pub refuse_null: Vec<String>,
185    /// Substituted types likewise, whose own decoding then runs without
186    /// the generated rules, as the substitution decides the rest itself.
187    pub refuse_null_isolated: Vec<String>,
188    /// Substituted types that hold null themselves: decoded without the
189    /// generated rules, null included.
190    pub isolated: Vec<String>,
191    /// Generated validation is on: the report types and `Validator`.
192    pub validation: bool,
193    /// A pattern is matched, by validation or at decode: `matchPattern`.
194    pub patterns: bool,
195    /// A struct lets in only members matching a pattern: `memberMatches`.
196    pub member_patterns: bool,
197}
198
199/// `type {name} = {ty}`.
200#[derive(Debug, Clone, Serialize)]
201pub(crate) struct AliasView {
202    pub name: String,
203    pub ty: String,
204}
205
206#[derive(Debug, Clone, Serialize)]
207pub(crate) struct FieldView {
208    pub name: String,
209    pub raw_name: String,
210    pub ty: String,
211    /// The whole struct tag, as a Go string literal.
212    pub tag: String,
213    pub doc: Vec<String>,
214    /// `raw_name` as a Go string literal.
215    pub literal: String,
216    /// The decoder refuses a `null` for this member.
217    pub non_null: bool,
218    /// The member's slot among the required ones, if it is required.
219    pub required_index: Option<usize>,
220    /// The embedded map collecting members no field names.
221    pub catch_all: bool,
222    /// For a member left out when absent, the Go condition under which
223    /// it is written; empty when it always is.
224    pub present: String,
225}
226
227#[derive(Debug, Clone, Serialize)]
228pub(crate) struct VariantView {
229    /// The constant, for a string enum; the variant's own name, for a
230    /// tagged union.
231    pub name: String,
232    pub value: String,
233    /// `value` as a Go string literal.
234    pub literal: String,
235    /// The payload type, for a tagged union; empty for a string enum.
236    pub ty: String,
237    pub accessor: String,
238    pub constructor: String,
239    /// The value is made up: no tag selects the variant.
240    pub synthetic: bool,
241    /// Every wire value selecting the variant, as a `case` list.
242    pub cases: String,
243}
244
245#[derive(Debug, Clone, Serialize)]
246pub(crate) struct BranchView {
247    pub accessor: String,
248    pub constructor: String,
249    pub ty: String,
250}
251
252#[derive(Debug, Clone, Serialize)]
253pub(crate) struct TypeView {
254    /// `struct`, `enum`, `union_tagged`, `union_open`, `composed_open`,
255    /// `newtype`, `alias`.
256    pub kind: &'static str,
257    pub name: String,
258    /// `name` as a Go string literal, for error messages.
259    pub name_literal: String,
260    pub raw_name: String,
261    pub doc: Vec<String>,
262    pub fields: Vec<FieldView>,
263    pub variants: Vec<VariantView>,
264    pub branches: Vec<BranchView>,
265    /// Inner type of a newtype or alias.
266    pub inner: String,
267    /// Discriminator property of a tagged union, and as a literal.
268    pub tag: String,
269    /// For a tagged union, the index of the variant an unknown or missing
270    /// tag is read as; `None` refuses such a value.
271    pub fallback: Option<usize>,
272    pub tag_literal: String,
273    /// `oneOf` rather than `anyOf`, for an open union's documentation.
274    pub exclusive: bool,
275    /// How many of a struct's members are required.
276    pub required_count: usize,
277    /// The value type of a struct's catch-all map; empty when members it
278    /// does not name are refused.
279    pub extra_ty: String,
280    /// The catch-all field's name.
281    pub extra_name: String,
282    /// Beside `additionalProperties: false`, the quoted patterns a member
283    /// no field reads must match.
284    pub member_patterns: Vec<String>,
285    /// The Go spelling of each `patternProperties` schema, in order.
286    #[serde(skip)]
287    pub pattern_tys: Vec<Option<String>>,
288    /// The Go spelling of the `additionalProperties` schema beside them.
289    #[serde(skip)]
290    pub others_ty: Option<String>,
291    /// Package-level aliases of the member types validation decodes into
292    /// that name a substitution's package or a lower-case type of the
293    /// package's own: inside `validateInto` a local, such as the report
294    /// `r`, may shadow either.
295    pub validate_aliases: Vec<AliasView>,
296    /// A member name no struct tag can carry: the struct writes itself.
297    pub marshal: bool,
298    /// The raw constructor of a composed holder.
299    pub from_raw: String,
300    /// The statements of `validateInto`, with validation on; `None` for
301    /// no methods of its own (an alias).
302    pub validate: Option<Vec<String>>,
303    /// The statements of `validateNull`; empty for none.
304    pub validate_null: Vec<String>,
305    /// Under `layout = "file_per_type"`, the stem of the file the type is
306    /// written to.
307    #[serde(skip_serializing_if = "Option::is_none")]
308    pub file: Option<String>,
309}
310
311#[derive(Debug, Clone, Serialize)]
312pub(crate) struct FileView {
313    /// The contract version this context follows.
314    pub template_api: u32,
315    pub source: String,
316    pub header: String,
317    pub package: String,
318    /// Import specs, each a quoted path.
319    pub imports: Vec<String>,
320    pub extra_imports: Vec<String>,
321    pub support: SupportView,
322    pub types: Vec<TypeView>,
323}
324
325/// A Go module the generated code imports from, beyond the standard
326/// library.
327#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
328#[non_exhaustive]
329pub struct GoDependency {
330    /// The import path, as the substitution gives it.
331    pub import: String,
332}
333
334impl GoDependency {
335    pub fn new(import: impl Into<String>) -> Self {
336        GoDependency {
337            import: import.into(),
338        }
339    }
340}
341
342pub(crate) struct Built {
343    pub file: FileView,
344    /// For each of `file.imports`, the names a file using it qualifies
345    /// with: what decides, under `layout = "file_per_type"`, which files
346    /// import it.
347    pub import_names: Vec<BTreeSet<String>>,
348    pub dependencies: Vec<GoDependency>,
349    pub diagnostics: Vec<Diagnostic>,
350}
351
352struct Builder<'a> {
353    /// Imports the validation checks need.
354    needs: super::validation::Needs,
355    ir: &'a Ir,
356    config: &'a Config,
357    names: BTreeMap<SchemaId, String>,
358    /// Package scope: types, constants and constructor functions.
359    package_names: Allocator,
360    suppressed: BTreeSet<SchemaId>,
361    support: SupportView,
362    refuse_null: BTreeSet<String>,
363    refuse_null_isolated: BTreeSet<String>,
364    isolated: BTreeSet<String>,
365    externs: BTreeSet<String>,
366    /// The substitution spellings the schema uses.
367    spellings: BTreeSet<String>,
368    /// For each substitution import, the qualifiers its spellings use.
369    extern_names: BTreeMap<String, BTreeSet<String>>,
370    diagnostics: Vec<Diagnostic>,
371}
372
373/// The package name an import path is used under, as far as the path
374/// says: its last element, skipping a `/vN` major-version suffix.
375pub(crate) fn package_of(import: &str) -> &str {
376    let mut elements = import.rsplit('/');
377    let last = elements.next().unwrap_or(import);
378    let major =
379        last.len() > 1 && last.starts_with('v') && last[1..].bytes().all(|b| b.is_ascii_digit());
380    match elements.next() {
381        Some(previous) if major => previous,
382        _ => last,
383    }
384}
385
386pub(crate) fn build(ir: &Ir, config: &Config, source: &str) -> Result<Built, GenerateError> {
387    let mut builder = Builder {
388        needs: Default::default(),
389        ir,
390        config,
391        names: BTreeMap::new(),
392        package_names: Allocator::default(),
393        suppressed: ir.suppressed.clone(),
394        support: SupportView {
395            exact_numbers: config.exact_numbers,
396            ..SupportView::default()
397        },
398        refuse_null: BTreeSet::new(),
399        refuse_null_isolated: BTreeSet::new(),
400        isolated: BTreeSet::new(),
401        externs: BTreeSet::new(),
402        spellings: BTreeSet::new(),
403        extern_names: BTreeMap::new(),
404        diagnostics: Vec::new(),
405    };
406    select_check(ir, config)?;
407    builder.allocate_type_names()?;
408    let mut types = Vec::new();
409    for id in &ir.order {
410        if builder.suppressed.contains(id) {
411            continue;
412        }
413        if let Some(view) = builder.type_view(&ir.types[id])? {
414            types.push(view);
415        }
416    }
417    builder.support.refuse_null = builder.refuse_null.iter().cloned().collect();
418    // A substitution spelled like a generated type (`string`, say) is
419    // refused like that type; the first registered function would win.
420    builder.support.refuse_null_isolated = builder
421        .refuse_null_isolated
422        .difference(&builder.refuse_null)
423        .cloned()
424        .collect();
425    builder.support.isolated = builder.isolated.iter().cloned().collect();
426    if config.layout == Layout::FilePerType {
427        assign_files(&mut types, config);
428    }
429    let mut imports = Vec::new();
430    let mut import_names = Vec::new();
431    let mut dependencies = Vec::new();
432    if !types.is_empty() {
433        let mut builtin = BUILTIN_IMPORTS.to_vec();
434        if builder.support.sorted_keys || builder.needs.sorted {
435            builtin.extend([("maps", "maps"), ("slices", "slices")]);
436        } else if builder.needs.slices {
437            builtin.push(("slices", "slices"));
438        }
439        if builder.needs.math {
440            builtin.push(("math", "math"));
441        }
442        if builder.support.decimal {
443            builtin.extend([("math/big", "big"), ("strconv", "strconv")]);
444        }
445        if builder.needs.utf8 {
446            builtin.push(("unicode/utf8", "utf8"));
447        }
448        if builder.needs.pattern {
449            builtin.extend([("regexp", "regexp"), ("sync", "sync")]);
450            builder.support.patterns = true;
451        }
452        imports.extend(builtin.iter().map(|(path, _)| quote(path)));
453        import_names.extend(
454            builtin
455                .iter()
456                .map(|(_, name)| BTreeSet::from([(*name).to_owned()])),
457        );
458        // Under `file_per_type` each substitution import goes to the files
459        // using it, so its name must be certain: the one package its
460        // spellings name that no builtin or extra import is used under.
461        // One an extra import already brings in needs no import here.
462        let file_per_type = config.layout == Layout::FilePerType;
463        let extra_names: BTreeSet<String> = config
464            .extra_imports
465            .iter()
466            .filter_map(|spec| match super::imports::spec_name(spec) {
467                super::imports::SpecName::Named(name) => Some(name),
468                _ => None,
469            })
470            .collect();
471        // A substitution import an extra import brings in under the name
472        // its spellings use: the extra import serves.
473        let extra_paths: BTreeMap<&str, String> = config
474            .extra_imports
475            .iter()
476            .filter_map(|spec| match super::imports::spec_name(spec) {
477                super::imports::SpecName::Named(name) => {
478                    Some((super::imports::spec_path(spec), name))
479                }
480                _ => None,
481            })
482            .collect();
483        let served = |import: &String| {
484            extra_paths.get(import.as_str()).is_some_and(|name| {
485                builder
486                    .extern_names
487                    .get(import)
488                    .is_some_and(|names| names.contains(name))
489            })
490        };
491        let mut certain: BTreeMap<&String, String> = BTreeMap::new();
492        if file_per_type {
493            for import in &builder.externs {
494                if builtin.iter().any(|(path, _)| path == import) || served(import) {
495                    continue;
496                }
497                let candidates: Vec<&String> = builder
498                    .extern_names
499                    .get(import)
500                    .into_iter()
501                    .flatten()
502                    .filter(|q| !builtin.iter().any(|(_, b)| b == q) && !extra_names.contains(*q))
503                    .collect();
504                let [name] = candidates.as_slice() else {
505                    return Err(GenerateError::Config(format!(
506                        "substitution import {import:?} is not the one package its spellings name beside the builtin and extra imports (they name {candidates:?}); under `layout = \"file_per_type\"` import the others through `extra_imports` with their names"
507                    )));
508                };
509                certain.insert(import, (*name).clone());
510            }
511        }
512        let mut used: BTreeMap<&str, &str> =
513            builtin.iter().map(|(path, name)| (*name, *path)).collect();
514        // A package named like a name the generated code declares would be
515        // shadowed by it, or clash with it.
516        for local in TEMPLATE_NAMES {
517            used.insert(local, "a name the generated code declares");
518        }
519        if builder.needs.pattern {
520            for local in PATTERN_NAMES {
521                used.insert(local, "a name the generated code declares");
522            }
523            // Locals of `matchPattern`, in the package file.
524            if config.layout == Layout::FilePerType {
525                for local in ["re", "c"] {
526                    used.insert(local, "a name the generated code declares");
527                }
528            }
529        }
530        if builder.support.member_patterns {
531            used.insert("memberMatches", "a name the generated code declares");
532        }
533        if builder.support.decimal {
534            for local in DECIMAL_NAMES {
535                used.insert(local, "a name the generated code declares");
536            }
537        }
538        if config.validation {
539            for local in VALIDATION_NAMES {
540                used.insert(local, "a name the generated validation declares");
541            }
542        }
543        let aliases: BTreeSet<&str> = types
544            .iter()
545            .flat_map(|t| &t.validate_aliases)
546            .map(|alias| alias.name.as_str())
547            .collect();
548        // A substitution spelled like an alias would name the alias, or
549        // the alias be declared as itself.
550        let spellings = config
551            .substitutions
552            .values()
553            .filter_map(|s| s.go.as_ref())
554            .map(|go| go.name.as_str());
555        for spelling in spellings {
556            // Unqualified, or a package qualifier: an import path need
557            // not say the package's name.
558            let qualifiers = super::imports::qualifiers(spelling);
559            let unqualified = unqualified_names(spelling);
560            if let Some(name) = unqualified
561                .iter()
562                .chain(&qualifiers)
563                .find(|name| aliases.contains(name.as_str()))
564            {
565                return Err(GenerateError::Config(format!(
566                    "substitution spelling {spelling:?} names `{name}`, which the generated validation declares"
567                )));
568            }
569        }
570        for alias in &aliases {
571            used.insert(alias, "a name the generated validation declares");
572        }
573        // The `Decimal` methods' receiver, in the package file.
574        if builder.support.decimal && config.layout == Layout::FilePerType {
575            used.insert("x", "a name the generated code declares");
576        }
577        // A file whose only `r.` is validation's report would import a
578        // package named `r`, which goes by its uses under `file_per_type`.
579        if config.validation && config.layout == Layout::FilePerType {
580            used.insert("r", "a name the generated validation declares");
581        }
582        for import in &builder.externs {
583            if builtin.iter().any(|(path, _)| path == import) {
584                continue;
585            }
586            // The standard library is no dependency to declare; a module
587            // path has a dot in its first element.
588            if import
589                .split('/')
590                .next()
591                .is_some_and(|first| first.contains('.'))
592            {
593                dependencies.push(GoDependency::new(import.clone()));
594            }
595            if file_per_type && served(import) {
596                continue;
597            }
598            let name = match certain.get(import) {
599                Some(name) => name.as_str(),
600                None => package_of(import),
601            };
602            // Under `file_per_type` the import goes to the files using its
603            // name, so it may not be a local the generated code declares.
604            let local = (file_per_type
605                && ((config.validation && depth_local(name))
606                    || used
607                        .get(name)
608                        .is_some_and(|what| what.starts_with("a name "))))
609            .then_some(name);
610            if let Some(q) = local {
611                return Err(GenerateError::Config(format!(
612                    "substitution import {import:?} is used as `{q}`, a name the generated code declares, which `layout = \"file_per_type\"` would read as its use; import it under another name"
613                )));
614            }
615            if let Some(path) = used.insert(name, import) {
616                return Err(GenerateError::Config(format!(
617                    "substitution import {import:?} is used as `{name}`, which the generated code already imports as {path:?}"
618                )));
619            }
620            imports.push(quote(import));
621            let names = BTreeSet::from([name.to_owned()]);
622            import_names.push(names);
623        }
624        // A type of the package's own spelled like a local of the code
625        // spelling it is shadowed by that local, and one spelled like a
626        // package-level name or an import clashes with it. Helpers and
627        // builtin imports are refused even where this run has none, so a
628        // config keeps working as the description grows.
629        for spelling in &builder.spellings {
630            let taken = type_names(spelling).into_iter().find_map(|name| {
631                let what = if SPELLING_LOCALS.contains(&name.as_str()) {
632                    "a local of the generated decoders, which would shadow it".to_owned()
633                } else if HELPER_NAMES.contains(&name.as_str()) {
634                    "a name the generated code may declare".to_owned()
635                } else if BUILTIN_NAMES.contains(&name.as_str()) {
636                    "the name the generated code may import a package under".to_owned()
637                } else {
638                    let path = used
639                        .get(name.as_str())
640                        .filter(|what| !what.starts_with("a name "))?;
641                    format!("the name the generated code imports {path:?} under")
642                };
643                Some((name, what))
644            });
645            if let Some((name, what)) = taken {
646                return Err(GenerateError::Config(format!(
647                    "substitution spelling {spelling:?} names `{name}`, {what}; rename the type, or spell it through a package"
648                )));
649            }
650        }
651        // Under `file_per_type` an extra import goes to the files naming it,
652        // and a name the generated code also declares, or imports, would
653        // send it to files that only use that.
654        if config.layout == Layout::FilePerType {
655            for spec in &config.extra_imports {
656                let name = match super::imports::spec_name(spec) {
657                    super::imports::SpecName::Named(name) => name,
658                    super::imports::SpecName::Unnamed => continue,
659                    super::imports::SpecName::Uncertain => {
660                        return Err(GenerateError::Config(format!(
661                            "`extra_imports` entry {spec:?} does not say the name its package is used under, which `layout = \"file_per_type\"` places it by; give it one, such as `name \"path\"`"
662                        )));
663                    }
664                };
665                let what = if config.validation && depth_local(&name) {
666                    Some("validation's loop variables")
667                } else {
668                    used.get(name.as_str()).copied()
669                };
670                if let Some(what) = what {
671                    return Err(GenerateError::Config(format!(
672                        "`extra_imports` entry {spec:?} is used as `{name}`, which is taken by {what}; under `layout = \"file_per_type\"` give it another name"
673                    )));
674                }
675            }
676        }
677    }
678    Ok(Built {
679        file: FileView {
680            template_api: crate::templates::TEMPLATE_API,
681            source: comment_text(source),
682            header: config.header.clone().unwrap_or_default(),
683            package: config.go.package.clone(),
684            imports,
685            extra_imports: config.extra_imports.clone(),
686            support: builder.support,
687            types,
688        },
689        import_names,
690        dependencies,
691        diagnostics: builder.diagnostics,
692    })
693}
694
695/// Names the file of every type under `layout = "file_per_type"`: its
696/// name in snake case, never the package file's, one `go build` would
697/// constrain, or one a file system resolves elsewhere.
698fn assign_files(types: &mut [TypeView], config: &Config) {
699    let mut taken = BTreeSet::from([config.go.file.clone()]);
700    for t in types {
701        let base = crate::write::capped_stem(super::naming::go_file_name(
702            &crate::rust::naming::snake(std::slice::from_ref(&t.name)),
703        ));
704        let file = (1u32..)
705            .map(|i| {
706                if i == 1 {
707                    base.clone()
708                } else {
709                    format!("{base}{i}")
710                }
711            })
712            .find(|candidate| !taken.contains(candidate) && super::naming::is_file_stem(candidate))
713            .expect("a free file name");
714        taken.insert(file.clone());
715        t.file = Some(file);
716    }
717}
718
719/// The names a Go type spelling uses unqualified: neither a package
720/// qualifier nor a selector after one, nor inside a literal (a tag).
721fn unqualified_names(ty: &str) -> Vec<String> {
722    scan_names(ty, false)
723}
724
725/// The unqualified names a Go type spelling uses as types: also not a
726/// field, parameter or method name.
727fn type_names(ty: &str) -> Vec<String> {
728    scan_names(ty, true)
729}
730
731/// A token of a Go type spelling.
732#[derive(Debug, Clone, Copy, PartialEq, Eq)]
733enum Token<'a> {
734    Ident(&'a str),
735    /// A string, rune or number.
736    Literal,
737    /// An explicit `;`, or one Go reads into a line break.
738    Semicolon,
739    Punct(&'a str),
740}
741
742/// The tokens of a Go type spelling, with the semicolons Go inserts at
743/// line breaks; comments are blanks, or line breaks when they hold one.
744fn tokens(ty: &str) -> Vec<Token<'_>> {
745    fn ends_line(last: Option<&Token<'_>>) -> bool {
746        match last {
747            Some(Token::Ident(word)) => {
748                !super::naming::is_keyword(word)
749                    || matches!(*word, "break" | "continue" | "fallthrough" | "return")
750            }
751            Some(Token::Literal) => true,
752            Some(Token::Punct(p)) => matches!(*p, ")" | "]" | "}"),
753            _ => false,
754        }
755    }
756    let ident = |c: char| c.is_alphanumeric() || c == '_';
757    let mut out = Vec::new();
758    let mut rest = ty;
759    while let Some(c) = rest.chars().next() {
760        let len = if c == '\n' {
761            if ends_line(out.last()) {
762                out.push(Token::Semicolon);
763            }
764            1
765        } else if c.is_whitespace() {
766            c.len_utf8()
767        } else if rest.starts_with("//") {
768            rest.find('\n').unwrap_or(rest.len())
769        } else if let Some(body) = rest.strip_prefix("/*") {
770            let len = body.find("*/").map_or(rest.len(), |end| end + 4);
771            if rest[..len].contains('\n') && ends_line(out.last()) {
772                out.push(Token::Semicolon);
773            }
774            len
775        } else if c.is_alphabetic() || c == '_' {
776            let len = rest.find(|c: char| !ident(c)).unwrap_or(rest.len());
777            out.push(Token::Ident(&rest[..len]));
778            len
779        } else if c.is_ascii_digit()
780            || (c == '.' && rest[1..].starts_with(|c: char| c.is_ascii_digit()))
781        {
782            // `e` is a hex digit: only `p` gives a hex literal's exponent.
783            let hex = rest.starts_with("0x") || rest.starts_with("0X");
784            let mut len = 0;
785            let mut prev = ' ';
786            for c in rest.chars() {
787                let exponent = if hex {
788                    matches!(prev, 'p' | 'P')
789                } else {
790                    matches!(prev, 'e' | 'E')
791                };
792                let exponent_sign = matches!(c, '+' | '-') && exponent;
793                if !(ident(c) || c == '.' || exponent_sign) {
794                    break;
795                }
796                len += c.len_utf8();
797                prev = c;
798            }
799            out.push(Token::Literal);
800            len
801        } else if matches!(c, '"' | '\'' | '`') {
802            let mut escaped = false;
803            let close = rest[1..].char_indices().find(|&(_, inner)| {
804                let closes = inner == c && !escaped;
805                escaped = c != '`' && inner == '\\' && !escaped;
806                closes
807            });
808            out.push(Token::Literal);
809            close.map_or(rest.len(), |(at, _)| at + 2)
810        } else if rest.starts_with("...") || rest.starts_with("<-") {
811            let len = if rest.starts_with("...") { 3 } else { 2 };
812            out.push(Token::Punct(&rest[..len]));
813            len
814        } else if c == ';' {
815            out.push(Token::Semicolon);
816            1
817        } else {
818            out.push(Token::Punct(&rest[..c.len_utf8()]));
819            c.len_utf8()
820        };
821        rest = &rest[len..];
822    }
823    out
824}
825
826fn scan_names(ty: &str, types_only: bool) -> Vec<String> {
827    let tokens = tokens(ty);
828    let at = |k: usize| tokens.get(k).copied();
829    // Where a type can begin, after a name: `x T`, `x *T`, `x []T`,
830    // `x ...T`, `x <-chan T`, `x (T)`.
831    let type_starts = |k: usize| {
832        matches!(
833            at(k),
834            Some(Token::Ident(_) | Token::Punct("*" | "[" | "(" | "..." | "<-"))
835        )
836    };
837    // The token after a bracketed `[…]` opening at `k`.
838    let after_brackets = |k: usize| {
839        let mut depth = 0usize;
840        for (j, token) in tokens.iter().enumerate().skip(k) {
841            match token {
842                Token::Punct("[") => depth += 1,
843                Token::Punct("]") => {
844                    depth -= 1;
845                    if depth == 0 {
846                        return j + 1;
847                    }
848                }
849                _ => {}
850            }
851        }
852        tokens.len()
853    };
854    // A type follows at `k`; `List[T]` instantiates, `x [N]T` declares.
855    let type_follows = |k: usize| match at(k) {
856        Some(Token::Punct("[")) => type_starts(after_brackets(k)),
857        _ => type_starts(k),
858    };
859    // A field, parameter or method name at `k`: `x T`, `x, y T`, `x()`.
860    let named = |k: usize| {
861        let entry = k > 0
862            && matches!(
863                at(k - 1),
864                Some(Token::Punct("(" | "," | "{") | Token::Semicolon)
865            );
866        if !entry {
867            return false;
868        }
869        let mut j = k + 1;
870        if at(j) == Some(Token::Punct("(")) {
871            return true;
872        }
873        // `a, b, c T`; `a, chan T` lists types, `chan` being no name.
874        while at(j) == Some(Token::Punct(",")) {
875            match at(j + 1) {
876                Some(Token::Ident(word)) if !super::naming::is_keyword(word) => j += 2,
877                _ => return false,
878            }
879        }
880        type_follows(j)
881    };
882    let mut out = Vec::new();
883    for (k, token) in tokens.iter().enumerate() {
884        let Token::Ident(word) = *token else {
885            continue;
886        };
887        let selector = k > 0 && at(k - 1) == Some(Token::Punct("."));
888        let qualifier = at(k + 1) == Some(Token::Punct("."));
889        if selector || qualifier {
890            continue;
891        }
892        if types_only && !super::naming::is_keyword(word) && named(k) {
893            continue;
894        }
895        out.push(word.to_owned());
896    }
897    out
898}
899
900/// Whether a Go type spelling names an unqualified, unexported type that
901/// Go does not predeclare: one a local may shadow.
902fn names_unexported_type(ty: &str) -> bool {
903    const PREDECLARED: &[&str] = &[
904        "any",
905        "bool",
906        "byte",
907        "comparable",
908        "complex64",
909        "complex128",
910        "error",
911        "float32",
912        "float64",
913        "int",
914        "int8",
915        "int16",
916        "int32",
917        "int64",
918        "rune",
919        "string",
920        "uint",
921        "uint8",
922        "uint16",
923        "uint32",
924        "uint64",
925        "uintptr",
926    ];
927    unqualified_names(ty).iter().any(|word| {
928        !word.starts_with(|c: char| c.is_uppercase())
929            && !PREDECLARED.contains(&word.as_str())
930            && !super::naming::is_keyword(word)
931    })
932}
933
934impl Builder<'_> {
935    /// The spelling validation decodes a member of `view` into: `ty`
936    /// itself, or, when it names a substitution's package or a type of
937    /// the package's own spelled in lower case, an alias
938    /// `{prefix}{view.name}` declared at package level, where no local of
939    /// `validateInto` shadows that name.
940    fn member_ty(&self, view: &mut TypeView, prefix: String, ty: String) -> String {
941        let substituted = super::imports::qualifiers(&ty)
942            .iter()
943            .any(|q| !BUILTIN_IMPORTS.iter().any(|(_, name)| name == q))
944            || names_unexported_type(&ty);
945        if !self.config.validation || !substituted {
946            return ty;
947        }
948        let name = format!("{prefix}{}", view.name);
949        view.validate_aliases.push(AliasView {
950            name: name.clone(),
951            ty,
952        });
953        name
954    }
955
956    fn allocate_type_names(&mut self) -> Result<(), GenerateError> {
957        // The helpers every file may declare.
958        for reserved in ["Nullable", "Int64", "Int32", "Null"] {
959            self.package_names.reserve(reserved);
960        }
961        if self.config.exact_numbers {
962            for reserved in ["Decimal", "DecimalMaxDigits", "ParseDecimal"] {
963                self.package_names.reserve(reserved);
964            }
965        }
966        if self.config.validation {
967            for reserved in [
968                "ValidationReport",
969                "Finding",
970                "FindingKind",
971                "Violation",
972                "Unevaluated",
973                "Validator",
974            ] {
975                self.package_names.reserve(reserved);
976            }
977        }
978        // Components first: a component keeps its name whatever an inline
979        // schema is titled or positioned to be called.
980        let ir = self.ir;
981        let order = ir
982            .order
983            .iter()
984            .filter(|id| ir.types[*id].component.is_some());
985        let rest = ir
986            .order
987            .iter()
988            .filter(|id| ir.types[*id].component.is_none());
989        for id in order.chain(rest) {
990            let def = &self.ir.types[id];
991            if matches!(def.kind, TypeKind::Extern) || self.suppressed.contains(id) {
992                continue;
993            }
994            let base = match self.type_config(def).and_then(|t| t.rename.clone()) {
995                Some(rename) => {
996                    if !is_exported_ident(&rename) {
997                        return Err(GenerateError::Config(format!(
998                            "`types.{}.rename = {rename:?}` must be an exported Go identifier: an ASCII capital, then letters, digits or `_`",
999                            def.component.as_deref().unwrap_or_default()
1000                        )));
1001                    }
1002                    rename
1003                }
1004                None => exported(&def.suggested_name),
1005            };
1006            let name = self.package_names.allocate(base);
1007            self.names.insert(id.clone(), name);
1008        }
1009        Ok(())
1010    }
1011
1012    fn type_config(&self, def: &TypeDef) -> Option<&TypeConfig> {
1013        def.component
1014            .as_ref()
1015            .and_then(|c| self.config.types.get(c))
1016    }
1017
1018    fn field_config<'c>(&'c self, def: &TypeDef, raw_name: &str) -> Option<&'c FieldConfig> {
1019        self.type_config(def).and_then(|t| t.fields.get(raw_name))
1020    }
1021
1022    /// Spell a type for Go.
1023    fn spell(&mut self, ty: &TypeRef) -> Result<String, GenerateError> {
1024        let spelled = match ty {
1025            TypeRef::Named(id) => {
1026                let def = &self.ir.types[id];
1027                if let TypeKind::Extern = def.kind {
1028                    let component = def.component.clone().unwrap_or_default();
1029                    let spelled = self.extern_spelling(&component)?;
1030                    self.refused_extern(&spelled)
1031                } else {
1032                    self.names[id].clone()
1033                }
1034            }
1035            // Go needs a pointer where a value would contain itself.
1036            TypeRef::Boxed(inner) => format!("*{}", self.spell(inner)?),
1037            TypeRef::Nullable(inner) => format!("*{}", self.spell(unboxed(inner))?),
1038            TypeRef::String => self.refused("string"),
1039            TypeRef::Integer(IntWidth::Int64) => {
1040                self.support.int64 = true;
1041                "Int64".into()
1042            }
1043            TypeRef::Integer(IntWidth::Int32) => {
1044                self.support.int32 = true;
1045                "Int32".into()
1046            }
1047            TypeRef::Number(FloatWidth::Double) => self.refused("float64"),
1048            TypeRef::Number(FloatWidth::Float) => self.refused("float32"),
1049            // Its own decoder refuses null.
1050            TypeRef::Decimal => {
1051                self.support.decimal = true;
1052                "Decimal".into()
1053            }
1054            TypeRef::Boolean => self.refused("bool"),
1055            TypeRef::Null => {
1056                self.support.null = true;
1057                "Null".into()
1058            }
1059            TypeRef::Any => "jsontext.Value".into(),
1060            TypeRef::Array(inner) => {
1061                let spelled = format!("[]{}", self.spell(unboxed(inner))?);
1062                self.refused(&spelled)
1063            }
1064            TypeRef::Map(inner) => {
1065                let spelled = format!("map[string]{}", self.spell(unboxed(inner))?);
1066                self.refused(&spelled)
1067            }
1068            TypeRef::Extern(key) => {
1069                let spelled = self.extern_spelling(key)?;
1070                self.refused_extern(&spelled)
1071            }
1072        };
1073        Ok(spelled)
1074    }
1075
1076    /// A type that stores its zero value for a JSON null, so the
1077    /// generated decoders refuse null for it explicitly.
1078    /// A substituted type, refused null like any other — unless it is
1079    /// spelled like a type the generator itself holds null in: a pointer,
1080    /// `jsontext.Value`, or an interface. The refusal is per Go type, so it
1081    /// would reach those positions too; such a substitution decides about
1082    /// null itself, as its Rust spelling does.
1083    fn refused_extern(&mut self, spelled: &str) -> String {
1084        if !null_holding_spelling(spelled) {
1085            self.refuse_null_isolated.insert(spelled.to_owned());
1086        } else if spelled != "jsontext.Value" {
1087            // Raw JSON has nothing inside to reach.
1088            self.isolated.insert(spelled.to_owned());
1089        }
1090        spelled.to_owned()
1091    }
1092
1093    fn refused(&mut self, spelled: &str) -> String {
1094        self.refuse_null.insert(spelled.to_owned());
1095        spelled.to_owned()
1096    }
1097
1098    fn extern_spelling(&mut self, key: &str) -> Result<String, GenerateError> {
1099        let spelling = self
1100            .config
1101            .substitutions
1102            .get(key)
1103            .and_then(|s| s.go.as_ref())
1104            .ok_or_else(|| {
1105                GenerateError::Config(format!("substitution `{key}` has no `go` spelling"))
1106            })?;
1107        if let Some(import) = &spelling.import {
1108            self.externs.insert(import.clone());
1109            self.extern_names
1110                .entry(import.clone())
1111                .or_default()
1112                .extend(super::imports::qualifiers(&spelling.name));
1113        }
1114        self.spellings.insert(spelling.name.clone());
1115        Ok(spelling.name.clone())
1116    }
1117
1118    fn doc(
1119        description: Option<&str>,
1120        default: Option<&serde_json::Value>,
1121        read_only: bool,
1122        write_only: bool,
1123        constraints: &crate::front::Constraints,
1124        deprecated: bool,
1125    ) -> Vec<String> {
1126        let mut lines: Vec<String> = description
1127            .map(|d| d.lines().map(|l| l.trim_end().to_owned()).collect())
1128            .unwrap_or_default();
1129        let mut notes = Vec::new();
1130        if let Some(default) = default {
1131            notes.push(format!("Default: `{default}`."));
1132        }
1133        if read_only {
1134            notes.push("Read only.".to_owned());
1135        }
1136        if write_only {
1137            notes.push("Write only.".to_owned());
1138        }
1139        notes.extend(constraint_notes(constraints));
1140        for paragraph in [notes, deprecation(deprecated)] {
1141            if !paragraph.is_empty() {
1142                if !lines.is_empty() {
1143                    lines.push(String::new());
1144                }
1145                lines.extend(paragraph);
1146            }
1147        }
1148        lines
1149            .into_iter()
1150            .flat_map(|l| l.split(['\n', '\r']).map(comment_text).collect::<Vec<_>>())
1151            .collect()
1152    }
1153
1154    fn type_view(&mut self, def: &TypeDef) -> Result<Option<TypeView>, GenerateError> {
1155        let Some(name) = self.names.get(&def.id).cloned() else {
1156            return Ok(None);
1157        };
1158        let raw_name = def
1159            .component
1160            .clone()
1161            .unwrap_or_else(|| def.id.pointer.clone());
1162        let mut doc = Vec::new();
1163        if let Some(title) = def
1164            .title
1165            .as_deref()
1166            .filter(|t| !t.trim().is_empty() && def.component.as_deref() != Some(t))
1167        {
1168            doc.extend(title.trim().lines().map(|l| comment_text(l.trim_end())));
1169            doc.push(String::new());
1170        }
1171        doc.extend(Self::doc(
1172            def.description.as_deref(),
1173            None,
1174            false,
1175            false,
1176            &def.constraints,
1177            false,
1178        ));
1179        if def.nullable {
1180            doc.push(
1181                "`null` is a valid instance; a position holding this type is a pointer or a `Nullable`."
1182                    .to_owned(),
1183            );
1184        }
1185        while doc.last().is_some_and(String::is_empty) {
1186            doc.pop();
1187        }
1188        let deprecated = deprecation(def.deprecated);
1189        if !deprecated.is_empty() {
1190            if !doc.is_empty() {
1191                doc.push(String::new());
1192            }
1193            doc.extend(deprecated);
1194        }
1195        let mut view = TypeView {
1196            kind: "struct",
1197            name_literal: quote(&name),
1198            name,
1199            raw_name,
1200            doc,
1201            fields: Vec::new(),
1202            variants: Vec::new(),
1203            branches: Vec::new(),
1204            inner: String::new(),
1205            tag: String::new(),
1206            fallback: None,
1207            tag_literal: String::new(),
1208            exclusive: false,
1209            required_count: 0,
1210            extra_ty: String::new(),
1211            extra_name: String::new(),
1212            member_patterns: Vec::new(),
1213            pattern_tys: Vec::new(),
1214            others_ty: None,
1215            validate_aliases: Vec::new(),
1216            marshal: false,
1217            from_raw: String::new(),
1218            validate: None,
1219            validate_null: Vec::new(),
1220            file: None,
1221        };
1222        if !self.fill_kind(def, &mut view)? {
1223            return Ok(None);
1224        }
1225        if self.config.validation {
1226            self.support.validation = true;
1227            // The validation support's number scan uses `math`.
1228            self.needs.math = true;
1229            let opted_out = self.type_config(def).and_then(|t| t.validation) == Some(false);
1230            let validates = |ty: &TypeRef| self.validates(ty);
1231            let nil_able = |ty: &TypeRef| match ty {
1232                TypeRef::Named(id) => matches!(
1233                    self.alias_target(id),
1234                    Some(TypeRef::Boxed(_) | TypeRef::Nullable(_))
1235                ),
1236                _ => false,
1237            };
1238            let names = &self.names;
1239            let ir = self.ir;
1240            // Through aliases, as `holds_null` sees them.
1241            let raw_holder = |ty: &TypeRef| {
1242                let mut id = ty.direct_named()?;
1243                for _ in 0..=ir.types.len() {
1244                    match &ir.types.get(id)?.kind {
1245                        // A JSON-value wrapper holds `null` itself.
1246                        TypeKind::Newtype(TypeRef::Any) => {
1247                            let name = names.get(id)?;
1248                            return Some(format!("{name}(jsontext.Value(\"null\"))"));
1249                        }
1250                        TypeKind::UnionOpen(_) | TypeKind::ComposedOpen(_) => {
1251                            let name = names.get(id)?;
1252                            return Some(format!("{name}{{raw: jsontext.Value(\"null\")}}"));
1253                        }
1254                        TypeKind::Alias(inner) | TypeKind::Newtype(inner) => {
1255                            id = inner.direct_named()?
1256                        }
1257                        _ => return None,
1258                    }
1259                }
1260                None
1261            };
1262            let holder_id = def.id.clone();
1263            let loops = |ty: &TypeRef| crate::checks::loops_back(ir, &holder_id, ty);
1264            // Through aliases, which share their target's methods.
1265            let null_name = |ty: &TypeRef| {
1266                let mut id = ty.direct_named()?;
1267                for _ in 0..=ir.types.len() {
1268                    let def = ir.types.get(id)?;
1269                    match &def.kind {
1270                        TypeKind::Alias(inner) => id = inner.direct_named()?,
1271                        // An opted-out type has no `validateNull`.
1272                        _ if !crate::checks::has_null_hook(def)
1273                            || self.type_config(def).and_then(|t| t.validation) == Some(false) =>
1274                        {
1275                            return None;
1276                        }
1277                        _ => return names.get(&def.id).cloned(),
1278                    }
1279                }
1280                None
1281            };
1282            let mut cx = super::validation::Context {
1283                validates: &validates,
1284                nil_able: &nil_able,
1285                raw_holder: &raw_holder,
1286                loops: &loops,
1287                null_name: &null_name,
1288                // A newtype over a substitution is an alias in Go, with no
1289                // validator of its own.
1290                extern_checks: &|ty: &TypeRef| {
1291                    crate::checks::extern_checks(ir, ty, !self.validates(ty))
1292                },
1293                ir,
1294                needs: self.needs,
1295            };
1296            view.validate = super::validation::body(def, &view, opted_out, &mut cx);
1297            if view.validate.is_some() && !opted_out {
1298                view.validate_null = super::validation::null_body(def, &view.name, &mut cx);
1299            }
1300            if opted_out && view.validate.is_none() {
1301                return Err(opt_out_on_alias(def));
1302            }
1303            self.needs = cx.needs;
1304        }
1305        Ok(Some(view))
1306    }
1307
1308    /// Fill the kind-specific parts of a view; `false` when the type is
1309    /// not emitted at all.
1310    fn fill_kind(&mut self, def: &TypeDef, view: &mut TypeView) -> Result<bool, GenerateError> {
1311        match &def.kind {
1312            TypeKind::Extern => return Ok(false),
1313            TypeKind::Struct(s) => {
1314                view.kind = "struct";
1315                let mut fields = Allocator::default();
1316                // The methods a generated struct has.
1317                fields.reserve("UnmarshalJSONFrom");
1318                if self.config.validation {
1319                    fields.reserve("Validate");
1320                }
1321                fields.reserve("MarshalJSONTo");
1322                let mut required_count = 0;
1323                for field in &s.fields {
1324                    let config = self.field_config(def, &field.raw_name);
1325                    let rename = config.and_then(|f| f.rename.clone());
1326                    let go_tags = config.map(|f| f.go_tags.clone()).unwrap_or_default();
1327                    let at = format!("types.{}.fields.{}", view.raw_name, field.raw_name);
1328                    let base = match rename {
1329                        Some(rename) if !is_exported_ident(&rename) => {
1330                            return Err(GenerateError::Config(format!(
1331                                "`{at}.rename = {rename:?}` must be an exported Go identifier: an ASCII capital, then letters, digits or `_`"
1332                            )));
1333                        }
1334                        Some(rename) => rename,
1335                        None => exported(std::slice::from_ref(&field.raw_name)),
1336                    };
1337                    let name = fields.allocate(base);
1338                    // A type that holds `null` as a value — `{}`, `type: null`,
1339                    // an open holder, or a reference to one — reads it as
1340                    // that value, as in Rust; an optional one keeps it apart
1341                    // from absence, so its member is nullable in Go's terms.
1342                    let holds_null = self.holds_null(&field.ty);
1343                    let (ty, omitzero) = match (field.required, field.nullable || holds_null) {
1344                        (true, false) => (self.spell(&field.ty)?, false),
1345                        (true, true) => {
1346                            self.support.nullable = true;
1347                            (
1348                                format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
1349                                false,
1350                            )
1351                        }
1352                        // `omitzero` asks a pointer's pointee `IsZero` when it
1353                        // has one — `time.Time` does — so a present zero value
1354                        // would be dropped; `Nullable` asks only for absence.
1355                        (false, false) if self.substituted(&field.ty) => {
1356                            self.support.nullable = true;
1357                            (
1358                                format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
1359                                true,
1360                            )
1361                        }
1362                        (false, false) => {
1363                            let inner = self.spell(&field.ty)?;
1364                            if inner.starts_with('*') {
1365                                (inner, true)
1366                            } else {
1367                                (format!("*{inner}"), true)
1368                            }
1369                        }
1370                        (false, true) => {
1371                            self.support.nullable = true;
1372                            (
1373                                format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
1374                                true,
1375                            )
1376                        }
1377                    };
1378                    let required_index = field.required.then(|| {
1379                        required_count += 1;
1380                        required_count - 1
1381                    });
1382                    let tag = struct_tag(&field.raw_name, omitzero, &go_tags, &at)?;
1383                    if !tag_name_ok(&field.raw_name) {
1384                        view.marshal = true;
1385                        self.support.sorted_keys |= matches!(s.additional, Additional::CatchAll(_));
1386                    }
1387                    let present = match (omitzero, ty.starts_with("Nullable[")) {
1388                        (false, _) => String::new(),
1389                        (true, true) => format!("v.{name}.Set"),
1390                        (true, false) => format!("v.{name} != nil"),
1391                    };
1392                    view.fields.push(FieldView {
1393                        present,
1394                        name,
1395                        raw_name: field.raw_name.clone(),
1396                        ty,
1397                        tag,
1398                        literal: quote(&field.raw_name),
1399                        non_null: !field.nullable && !holds_null,
1400                        required_index,
1401                        catch_all: false,
1402                        doc: Self::doc(
1403                            field.description.as_deref(),
1404                            field.default.as_ref(),
1405                            field.read_only,
1406                            field.write_only,
1407                            &field.constraints,
1408                            field.deprecated,
1409                        ),
1410                    });
1411                }
1412                view.required_count = required_count;
1413                if let Some(patterns) = &s.only_patterns {
1414                    self.needs.pattern = true;
1415                    self.support.member_patterns = true;
1416                    view.member_patterns = patterns.iter().map(|p| quote(p)).collect();
1417                }
1418                for (i, pattern) in s.patterns.iter().enumerate() {
1419                    let spelled = match pattern.branch() {
1420                        Some(b) => {
1421                            let ty = self.spell(unboxed(&b.ty))?;
1422                            Some(self.member_ty(view, format!("pattern{i}Of"), ty))
1423                        }
1424                        None => None,
1425                    };
1426                    view.pattern_tys.push(spelled);
1427                }
1428                if let crate::ir::Others::Schema(b) = &s.others {
1429                    let ty = self.spell(unboxed(&b.ty))?;
1430                    view.others_ty = Some(self.member_ty(view, "othersOf".to_owned(), ty));
1431                }
1432                if let Additional::CatchAll(ty) = &s.additional {
1433                    let inner = self.spell(unboxed(ty))?;
1434                    let name = fields.allocate("AdditionalProperties".to_owned());
1435                    view.extra_name = name.clone();
1436                    view.extra_ty = inner.clone();
1437                    view.fields.push(FieldView {
1438                        name,
1439                        raw_name: "additionalProperties".to_owned(),
1440                        ty: format!("map[string]{inner}"),
1441                        tag: "`json:\",embed\"`".to_owned(),
1442                        doc: vec!["Members not named above.".to_owned()],
1443                        literal: String::new(),
1444                        non_null: false,
1445                        required_index: None,
1446                        catch_all: true,
1447                        present: String::new(),
1448                    });
1449                }
1450            }
1451            TypeKind::StringEnum(values) => {
1452                view.kind = "enum";
1453                let mut seen = BTreeSet::new();
1454                // A repeated value is one member: a second constant would make
1455                // a duplicate `case`, which Go refuses.
1456                for value in values.iter().filter(|v| seen.insert(v.as_str())) {
1457                    let base = if value.trim().is_empty() {
1458                        "Empty".to_owned()
1459                    } else {
1460                        exported(std::slice::from_ref(value))
1461                    };
1462                    let name = self.package_names.allocate(format!("{}{base}", view.name));
1463                    view.variants.push(VariantView {
1464                        name,
1465                        literal: quote(value),
1466                        value: value.clone(),
1467                        ty: String::new(),
1468                        accessor: String::new(),
1469                        constructor: String::new(),
1470                        synthetic: false,
1471                        cases: String::new(),
1472                    });
1473                }
1474            }
1475            TypeKind::UnionTagged(u) => {
1476                view.kind = "union_tagged";
1477                self.support.tagged = true;
1478                view.tag = u.tag.clone();
1479                view.tag_literal = quote(&u.tag);
1480                view.fallback = u.fallback;
1481                let mut methods = Allocator::default();
1482                for reserved in ["Tag", "Value", "MarshalJSONTo", "UnmarshalJSONFrom"] {
1483                    methods.reserve(reserved);
1484                }
1485                if self.config.validation {
1486                    methods.reserve("Validate");
1487                }
1488                for variant in &u.variants {
1489                    let base = exported(&variant.suggested_name);
1490                    let accessor = methods.allocate(format!("As{base}"));
1491                    let constructor = self
1492                        .package_names
1493                        .allocate(format!("{}From{base}", view.name));
1494                    view.variants.push(VariantView {
1495                        name: base,
1496                        literal: quote(&variant.value),
1497                        value: variant.value.clone(),
1498                        ty: self.spell(&variant.ty)?,
1499                        accessor,
1500                        constructor,
1501                        synthetic: variant.synthetic,
1502                        cases: std::iter::once(&variant.value)
1503                            .chain(&variant.aliases)
1504                            .map(|tag| quote(tag))
1505                            .collect::<Vec<_>>()
1506                            .join(", "),
1507                    });
1508                }
1509            }
1510            TypeKind::UnionOpen(u) => {
1511                view.kind = "union_open";
1512                view.exclusive = u.exclusive;
1513                view.branches = self.branches(&view.name, &u.branches)?;
1514            }
1515            TypeKind::ComposedOpen(branches) => {
1516                view.kind = "composed_open";
1517                view.from_raw = self.package_names.allocate(format!("{}FromRaw", view.name));
1518                view.branches = self.branches(&view.name, branches)?;
1519            }
1520            TypeKind::Newtype(inner) | TypeKind::Alias(inner) => {
1521                view.inner = self.spell(inner)?;
1522                // Methods cannot be declared on a pointer type, nor on an
1523                // interface, which a substituted type may be: the generator
1524                // cannot tell. An alias keeps the methods of the type it
1525                // names, so a substitution keeps its own JSON behaviour.
1526                let substituted = match unboxed(inner) {
1527                    TypeRef::Extern(_) => true,
1528                    TypeRef::Named(id) => matches!(self.ir.types[id].kind, TypeKind::Extern),
1529                    _ => false,
1530                };
1531                view.kind = if matches!(def.kind, TypeKind::Alias(_))
1532                    || view.inner.starts_with('*')
1533                    || substituted
1534                {
1535                    "alias"
1536                } else {
1537                    "newtype"
1538                };
1539            }
1540        }
1541        Ok(true)
1542    }
1543
1544    /// Whether the type's own decoder takes `null` as one of its values:
1545    /// any JSON, `null` itself, or a holder of raw JSON.
1546    fn holds_null(&self, ty: &TypeRef) -> bool {
1547        let mut ty = ty;
1548        // A chain of aliases is at most every type long; one closing a cycle
1549        // generates nothing to hold anything.
1550        for _ in 0..=self.ir.types.len() {
1551            ty = match ty {
1552                TypeRef::Any | TypeRef::Null => return true,
1553                TypeRef::Boxed(inner) => inner,
1554                TypeRef::Extern(key) => return self.extern_holds_null(key),
1555                TypeRef::Named(id) => match &self.ir.types[id].kind {
1556                    TypeKind::Extern => {
1557                        let component = self.ir.types[id].component.as_deref();
1558                        return self.extern_holds_null(component.unwrap_or_default());
1559                    }
1560                    TypeKind::UnionOpen(_) | TypeKind::ComposedOpen(_) => return true,
1561                    TypeKind::Newtype(inner) | TypeKind::Alias(inner) => inner,
1562                    _ => return false,
1563                },
1564                _ => return false,
1565            };
1566        }
1567        false
1568    }
1569
1570    /// Whether the type is a substitution, directly or through aliases and
1571    /// newtypes over one (emitted as aliases).
1572    /// The type a named type is a Go alias of, if it is emitted as one:
1573    /// it then has no methods of its own.
1574    fn alias_target(&self, id: &SchemaId) -> Option<&TypeRef> {
1575        match &self.ir.types.get(id)?.kind {
1576            TypeKind::Alias(inner) => Some(inner),
1577            TypeKind::Newtype(inner)
1578                if matches!(inner, TypeRef::Boxed(_) | TypeRef::Nullable(_))
1579                    || self.substituted(inner) =>
1580            {
1581                Some(inner)
1582            }
1583            _ => None,
1584        }
1585    }
1586
1587    /// Whether `ty` holds a generated type with a `validateInto` of its own,
1588    /// seen through the aliases Go emits.
1589    fn validates(&self, ty: &TypeRef) -> bool {
1590        let mut ids = Vec::new();
1591        ty.named(&mut ids);
1592        ids.iter().any(|id| self.validates_named(id, 0))
1593    }
1594
1595    fn validates_named(&self, id: &SchemaId, depth: usize) -> bool {
1596        if depth > self.ir.types.len()
1597            || !self.names.contains_key(id)
1598            || matches!(self.ir.types[id].kind, TypeKind::Extern)
1599        {
1600            return false;
1601        }
1602        match self.alias_target(id) {
1603            Some(inner) => inner
1604                .direct_named()
1605                .is_some_and(|target| self.validates_named(target, depth + 1)),
1606            None => true,
1607        }
1608    }
1609
1610    fn substituted(&self, ty: &TypeRef) -> bool {
1611        let mut ty = ty;
1612        for _ in 0..=self.ir.types.len() {
1613            ty = match ty {
1614                TypeRef::Extern(_) => return true,
1615                TypeRef::Boxed(inner) => inner,
1616                TypeRef::Named(id) => match &self.ir.types[id].kind {
1617                    TypeKind::Extern => return true,
1618                    TypeKind::Newtype(inner) | TypeKind::Alias(inner) => inner,
1619                    _ => return false,
1620                },
1621                _ => return false,
1622            };
1623        }
1624        false
1625    }
1626
1627    /// A substituted type takes null as a value when it is spelled like
1628    /// one that does.
1629    fn extern_holds_null(&self, key: &str) -> bool {
1630        self.config
1631            .substitutions
1632            .get(key)
1633            .and_then(|s| s.go.as_ref())
1634            .is_some_and(|go| null_holding_spelling(&go.name))
1635    }
1636
1637    fn branches(
1638        &mut self,
1639        owner: &str,
1640        branches: &[crate::ir::Branch],
1641    ) -> Result<Vec<BranchView>, GenerateError> {
1642        let mut methods = Allocator::default();
1643        for reserved in ["Raw", "MarshalJSONTo", "UnmarshalJSONFrom"] {
1644            methods.reserve(reserved);
1645        }
1646        if self.config.validation {
1647            methods.reserve("Validate");
1648        }
1649        let mut out = Vec::new();
1650        for branch in branches {
1651            let base = exported(&branch.suggested_name);
1652            out.push(BranchView {
1653                accessor: methods.allocate(format!("As{base}")),
1654                constructor: self.package_names.allocate(format!("{owner}From{base}")),
1655                ty: self.spell(&branch.ty)?,
1656            });
1657        }
1658        Ok(out)
1659    }
1660}
1661
1662/// A Go spelling the generator itself holds null in — a pointer,
1663/// `jsontext.Value` — or an interface, which takes null as nil.
1664fn null_holding_spelling(spelled: &str) -> bool {
1665    spelled.starts_with('*')
1666        || spelled == "jsontext.Value"
1667        || spelled == "any"
1668        || spelled.starts_with("interface")
1669}
1670
1671/// A type that is an alias shares its target's validation, so a per-type
1672/// opt-out on it cannot be honoured: said rather than ignored.
1673pub(crate) fn opt_out_on_alias(def: &TypeDef) -> GenerateError {
1674    let name = def.component.as_deref().unwrap_or_default();
1675    GenerateError::Config(format!(
1676        "`types.{name}.validation = false` cannot apply: `{name}` is an alias, which validates as the type it names; opt that type out instead"
1677    ))
1678}
1679
1680/// The value type a pointer or a container already gives indirection to.
1681fn unboxed(ty: &TypeRef) -> &TypeRef {
1682    match ty {
1683        TypeRef::Boxed(inner) => inner,
1684        other => other,
1685    }
1686}
1687
1688fn deprecation(deprecated: bool) -> Vec<String> {
1689    if deprecated {
1690        vec!["Deprecated: the description marks this deprecated.".to_owned()]
1691    } else {
1692        Vec::new()
1693    }
1694}
1695
1696/// The struct tag for one member: the backend's `json` key, then the
1697/// configured keys, as one Go string literal.
1698fn struct_tag(
1699    raw_name: &str,
1700    omitzero: bool,
1701    extra: &BTreeMap<String, String>,
1702    at: &str,
1703) -> Result<String, GenerateError> {
1704    let mut json = raw_name.to_owned();
1705    if !tag_name_ok(raw_name) {
1706        // The struct's own MarshalJSONTo writes it; decoding goes by name.
1707        json = "-".to_owned();
1708    } else if omitzero {
1709        json.push_str(",omitzero");
1710    } else if raw_name == "-" {
1711        // `json:"-"` alone skips the field, and a trailing comma is
1712        // malformed, so `-` takes an option that changes nothing: strict
1713        // matching is the default.
1714        json.push_str(",case:strict");
1715    }
1716    let mut parts = vec![format!("json:{}", quote(&json))];
1717    for (key, value) in extra {
1718        if key == "json" {
1719            return Err(GenerateError::Config(format!(
1720                "`{at}.go_tags` sets `json`, which the generator owns: it carries the member name and the absent-versus-null contract"
1721            )));
1722        }
1723        if !is_tag_key(key) {
1724            return Err(GenerateError::Config(format!(
1725                "`{at}.go_tags` key {key:?} is not a struct-tag key: it must be printable ASCII without space, quote or colon"
1726            )));
1727        }
1728        parts.push(format!("{key}:{}", quote(value)));
1729    }
1730    let tag = parts.join(" ");
1731    Ok(if tag.contains('`') {
1732        quote(&tag)
1733    } else {
1734        format!("`{tag}`")
1735    })
1736}
1737
1738#[cfg(test)]
1739mod tests {
1740    use super::*;
1741
1742    #[test]
1743    fn struct_tags() {
1744        let none = BTreeMap::new();
1745        assert_eq!(
1746            struct_tag("name", false, &none, "x").unwrap(),
1747            "`json:\"name\"`"
1748        );
1749        assert_eq!(
1750            struct_tag("-", false, &none, "x").unwrap(),
1751            "`json:\"-,case:strict\"`"
1752        );
1753        assert_eq!(
1754            struct_tag("a b", true, &none, "x").unwrap(),
1755            "`json:\"a b,omitzero\"`"
1756        );
1757        let extra = BTreeMap::from([("db".to_owned(), "x`y".to_owned())]);
1758        assert_eq!(
1759            struct_tag("n", false, &extra, "x").unwrap(),
1760            "\"json:\\\"n\\\" db:\\\"x`y\\\"\""
1761        );
1762        let json = BTreeMap::from([("json".to_owned(), "x".to_owned())]);
1763        assert!(struct_tag("n", false, &json, "x").is_err());
1764        let bad = BTreeMap::from([("a b".to_owned(), "x".to_owned())]);
1765        assert!(struct_tag("n", false, &bad, "x").is_err());
1766    }
1767
1768    #[test]
1769    fn import_package_names() {
1770        assert_eq!(package_of("example.com/x/uuid"), "uuid");
1771        assert_eq!(package_of("encoding/json/v2"), "json");
1772        assert_eq!(package_of("time"), "time");
1773        assert_eq!(package_of("example.com/v"), "v");
1774    }
1775}