use crate::config::{Config, FieldConfig, Layout, TypeConfig};
use crate::diagnostic::{Diagnostic, SchemaId};
use crate::front::{FloatWidth, IntWidth};
use crate::generate::GenerateError;
use crate::go::naming::{
comment_text, exported, is_exported_ident, is_tag_key, quote, tag_name_ok,
};
use crate::ir::{Additional, Ir, TypeDef, TypeKind, TypeRef};
use crate::rust::naming::Allocator;
use crate::rust::view::{constraint_notes, select_check};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
const BUILTIN_IMPORTS: &[(&str, &str)] = &[
("encoding/json/jsontext", "jsontext"),
("encoding/json/v2", "json"),
("errors", "errors"),
("fmt", "fmt"),
];
const VALIDATION_NAMES: &[&str] = &[
"certain",
"uncertain",
"branch",
"repeated",
"childPointer",
"wideNumber",
"members",
"seen",
"item",
"p",
"x",
"f",
"zero",
];
const SPELLING_LOCALS: &[&str] = &[
"d", "e", "u", "v", "err", "name", "token", "value", "present",
"raw", "tag", "members", "member", "ok",
];
const HELPER_NAMES: &[&str] = &[
"decodeOptions",
"noUnmarshalers",
"isolatedNone",
"refuseNull",
"readTag",
"integerToken",
"matchPattern",
"patterns",
"memberMatches",
"decimalToken",
"decimalDigits",
"childPointer",
"wideNumber",
];
const BUILTIN_NAMES: &[&str] = &[
"jsontext", "json", "errors", "fmt", "maps", "slices", "math", "big", "strconv", "utf8",
"regexp", "sync",
];
fn depth_local(name: &str) -> bool {
["item", "i", "k"].iter().any(|prefix| {
name.strip_prefix(prefix)
.is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
})
}
const PATTERN_NAMES: &[&str] = &["matchPattern", "patterns"];
const DECIMAL_NAMES: &[&str] = &[
"decimalToken",
"decimalDigits",
"power",
"all",
"start",
"end",
"count",
"leading",
"sx",
"sy",
"lx",
"ly",
"dx",
"dy",
"c",
"b",
"shift",
"quotient",
"remainder",
"prime",
"taken",
"m",
"y",
"divisor",
];
const TEMPLATE_NAMES: &[&str] = &[
"decodeOptions",
"noUnmarshalers",
"isolatedNone",
"refuseNull",
"readTag",
"integerToken",
"v",
"u",
"d",
"e",
"n",
"raw",
"err",
"ok",
"zero",
"tag",
"typ",
"value",
"s",
"token",
"name",
"present",
"members",
"member",
"limit",
"text",
"negative",
"mantissa",
"exponent",
"digits",
"negativeExponent",
"whole",
"fraction",
"scale",
"ceiling",
"magnitude",
"digit",
"i",
"j",
];
#[derive(Debug, Clone, Serialize, Default)]
pub(crate) struct SupportView {
pub nullable: bool,
pub int64: bool,
pub int32: bool,
pub decimal: bool,
pub exact_numbers: bool,
pub null: bool,
pub tagged: bool,
pub sorted_keys: bool,
pub refuse_null: Vec<String>,
pub refuse_null_isolated: Vec<String>,
pub isolated: Vec<String>,
pub validation: bool,
pub patterns: bool,
pub member_patterns: bool,
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct AliasView {
pub name: String,
pub ty: String,
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct FieldView {
pub name: String,
pub raw_name: String,
pub ty: String,
pub tag: String,
pub doc: Vec<String>,
pub literal: String,
pub non_null: bool,
pub required_index: Option<usize>,
pub catch_all: bool,
pub present: String,
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct VariantView {
pub name: String,
pub value: String,
pub literal: String,
pub ty: String,
pub accessor: String,
pub constructor: String,
pub synthetic: bool,
pub cases: String,
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct BranchView {
pub accessor: String,
pub constructor: String,
pub ty: String,
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct TypeView {
pub kind: &'static str,
pub name: String,
pub name_literal: String,
pub raw_name: String,
pub doc: Vec<String>,
pub fields: Vec<FieldView>,
pub variants: Vec<VariantView>,
pub branches: Vec<BranchView>,
pub inner: String,
pub tag: String,
pub fallback: Option<usize>,
pub tag_literal: String,
pub exclusive: bool,
pub required_count: usize,
pub extra_ty: String,
pub extra_name: String,
pub member_patterns: Vec<String>,
#[serde(skip)]
pub pattern_tys: Vec<Option<String>>,
#[serde(skip)]
pub others_ty: Option<String>,
pub validate_aliases: Vec<AliasView>,
pub marshal: bool,
pub from_raw: String,
pub validate: Option<Vec<String>>,
pub validate_null: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub file: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct FileView {
pub template_api: u32,
pub source: String,
pub header: String,
pub package: String,
pub imports: Vec<String>,
pub extra_imports: Vec<String>,
pub support: SupportView,
pub types: Vec<TypeView>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub struct GoDependency {
pub import: String,
}
impl GoDependency {
pub fn new(import: impl Into<String>) -> Self {
GoDependency {
import: import.into(),
}
}
}
pub(crate) struct Built {
pub file: FileView,
pub import_names: Vec<BTreeSet<String>>,
pub dependencies: Vec<GoDependency>,
pub diagnostics: Vec<Diagnostic>,
}
struct Builder<'a> {
needs: super::validation::Needs,
ir: &'a Ir,
config: &'a Config,
names: BTreeMap<SchemaId, String>,
package_names: Allocator,
suppressed: BTreeSet<SchemaId>,
support: SupportView,
refuse_null: BTreeSet<String>,
refuse_null_isolated: BTreeSet<String>,
isolated: BTreeSet<String>,
externs: BTreeSet<String>,
spellings: BTreeSet<String>,
extern_names: BTreeMap<String, BTreeSet<String>>,
diagnostics: Vec<Diagnostic>,
}
pub(crate) fn package_of(import: &str) -> &str {
let mut elements = import.rsplit('/');
let last = elements.next().unwrap_or(import);
let major =
last.len() > 1 && last.starts_with('v') && last[1..].bytes().all(|b| b.is_ascii_digit());
match elements.next() {
Some(previous) if major => previous,
_ => last,
}
}
pub(crate) fn build(ir: &Ir, config: &Config, source: &str) -> Result<Built, GenerateError> {
let mut builder = Builder {
needs: Default::default(),
ir,
config,
names: BTreeMap::new(),
package_names: Allocator::default(),
suppressed: ir.suppressed.clone(),
support: SupportView {
exact_numbers: config.exact_numbers,
..SupportView::default()
},
refuse_null: BTreeSet::new(),
refuse_null_isolated: BTreeSet::new(),
isolated: BTreeSet::new(),
externs: BTreeSet::new(),
spellings: BTreeSet::new(),
extern_names: BTreeMap::new(),
diagnostics: Vec::new(),
};
select_check(ir, config)?;
builder.allocate_type_names()?;
let mut types = Vec::new();
for id in &ir.order {
if builder.suppressed.contains(id) {
continue;
}
if let Some(view) = builder.type_view(&ir.types[id])? {
types.push(view);
}
}
builder.support.refuse_null = builder.refuse_null.iter().cloned().collect();
builder.support.refuse_null_isolated = builder
.refuse_null_isolated
.difference(&builder.refuse_null)
.cloned()
.collect();
builder.support.isolated = builder.isolated.iter().cloned().collect();
if config.layout == Layout::FilePerType {
assign_files(&mut types, config);
}
let mut imports = Vec::new();
let mut import_names = Vec::new();
let mut dependencies = Vec::new();
if !types.is_empty() {
let mut builtin = BUILTIN_IMPORTS.to_vec();
if builder.support.sorted_keys || builder.needs.sorted {
builtin.extend([("maps", "maps"), ("slices", "slices")]);
} else if builder.needs.slices {
builtin.push(("slices", "slices"));
}
if builder.needs.math {
builtin.push(("math", "math"));
}
if builder.support.decimal {
builtin.extend([("math/big", "big"), ("strconv", "strconv")]);
}
if builder.needs.utf8 {
builtin.push(("unicode/utf8", "utf8"));
}
if builder.needs.pattern {
builtin.extend([("regexp", "regexp"), ("sync", "sync")]);
builder.support.patterns = true;
}
imports.extend(builtin.iter().map(|(path, _)| quote(path)));
import_names.extend(
builtin
.iter()
.map(|(_, name)| BTreeSet::from([(*name).to_owned()])),
);
let file_per_type = config.layout == Layout::FilePerType;
let extra_names: BTreeSet<String> = config
.extra_imports
.iter()
.filter_map(|spec| match super::imports::spec_name(spec) {
super::imports::SpecName::Named(name) => Some(name),
_ => None,
})
.collect();
let extra_paths: BTreeMap<&str, String> = config
.extra_imports
.iter()
.filter_map(|spec| match super::imports::spec_name(spec) {
super::imports::SpecName::Named(name) => {
Some((super::imports::spec_path(spec), name))
}
_ => None,
})
.collect();
let served = |import: &String| {
extra_paths.get(import.as_str()).is_some_and(|name| {
builder
.extern_names
.get(import)
.is_some_and(|names| names.contains(name))
})
};
let mut certain: BTreeMap<&String, String> = BTreeMap::new();
if file_per_type {
for import in &builder.externs {
if builtin.iter().any(|(path, _)| path == import) || served(import) {
continue;
}
let candidates: Vec<&String> = builder
.extern_names
.get(import)
.into_iter()
.flatten()
.filter(|q| !builtin.iter().any(|(_, b)| b == q) && !extra_names.contains(*q))
.collect();
let [name] = candidates.as_slice() else {
return Err(GenerateError::Config(format!(
"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"
)));
};
certain.insert(import, (*name).clone());
}
}
let mut used: BTreeMap<&str, &str> =
builtin.iter().map(|(path, name)| (*name, *path)).collect();
for local in TEMPLATE_NAMES {
used.insert(local, "a name the generated code declares");
}
if builder.needs.pattern {
for local in PATTERN_NAMES {
used.insert(local, "a name the generated code declares");
}
if config.layout == Layout::FilePerType {
for local in ["re", "c"] {
used.insert(local, "a name the generated code declares");
}
}
}
if builder.support.member_patterns {
used.insert("memberMatches", "a name the generated code declares");
}
if builder.support.decimal {
for local in DECIMAL_NAMES {
used.insert(local, "a name the generated code declares");
}
}
if config.validation {
for local in VALIDATION_NAMES {
used.insert(local, "a name the generated validation declares");
}
}
let aliases: BTreeSet<&str> = types
.iter()
.flat_map(|t| &t.validate_aliases)
.map(|alias| alias.name.as_str())
.collect();
let spellings = config
.substitutions
.values()
.filter_map(|s| s.go.as_ref())
.map(|go| go.name.as_str());
for spelling in spellings {
let qualifiers = super::imports::qualifiers(spelling);
let unqualified = unqualified_names(spelling);
if let Some(name) = unqualified
.iter()
.chain(&qualifiers)
.find(|name| aliases.contains(name.as_str()))
{
return Err(GenerateError::Config(format!(
"substitution spelling {spelling:?} names `{name}`, which the generated validation declares"
)));
}
}
for alias in &aliases {
used.insert(alias, "a name the generated validation declares");
}
if builder.support.decimal && config.layout == Layout::FilePerType {
used.insert("x", "a name the generated code declares");
}
if config.validation && config.layout == Layout::FilePerType {
used.insert("r", "a name the generated validation declares");
}
for import in &builder.externs {
if builtin.iter().any(|(path, _)| path == import) {
continue;
}
if import
.split('/')
.next()
.is_some_and(|first| first.contains('.'))
{
dependencies.push(GoDependency::new(import.clone()));
}
if file_per_type && served(import) {
continue;
}
let name = match certain.get(import) {
Some(name) => name.as_str(),
None => package_of(import),
};
let local = (file_per_type
&& ((config.validation && depth_local(name))
|| used
.get(name)
.is_some_and(|what| what.starts_with("a name "))))
.then_some(name);
if let Some(q) = local {
return Err(GenerateError::Config(format!(
"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"
)));
}
if let Some(path) = used.insert(name, import) {
return Err(GenerateError::Config(format!(
"substitution import {import:?} is used as `{name}`, which the generated code already imports as {path:?}"
)));
}
imports.push(quote(import));
let names = BTreeSet::from([name.to_owned()]);
import_names.push(names);
}
for spelling in &builder.spellings {
let taken = type_names(spelling).into_iter().find_map(|name| {
let what = if SPELLING_LOCALS.contains(&name.as_str()) {
"a local of the generated decoders, which would shadow it".to_owned()
} else if HELPER_NAMES.contains(&name.as_str()) {
"a name the generated code may declare".to_owned()
} else if BUILTIN_NAMES.contains(&name.as_str()) {
"the name the generated code may import a package under".to_owned()
} else {
let path = used
.get(name.as_str())
.filter(|what| !what.starts_with("a name "))?;
format!("the name the generated code imports {path:?} under")
};
Some((name, what))
});
if let Some((name, what)) = taken {
return Err(GenerateError::Config(format!(
"substitution spelling {spelling:?} names `{name}`, {what}; rename the type, or spell it through a package"
)));
}
}
if config.layout == Layout::FilePerType {
for spec in &config.extra_imports {
let name = match super::imports::spec_name(spec) {
super::imports::SpecName::Named(name) => name,
super::imports::SpecName::Unnamed => continue,
super::imports::SpecName::Uncertain => {
return Err(GenerateError::Config(format!(
"`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\"`"
)));
}
};
let what = if config.validation && depth_local(&name) {
Some("validation's loop variables")
} else {
used.get(name.as_str()).copied()
};
if let Some(what) = what {
return Err(GenerateError::Config(format!(
"`extra_imports` entry {spec:?} is used as `{name}`, which is taken by {what}; under `layout = \"file_per_type\"` give it another name"
)));
}
}
}
}
Ok(Built {
file: FileView {
template_api: crate::templates::TEMPLATE_API,
source: comment_text(source),
header: config.header.clone().unwrap_or_default(),
package: config.go.package.clone(),
imports,
extra_imports: config.extra_imports.clone(),
support: builder.support,
types,
},
import_names,
dependencies,
diagnostics: builder.diagnostics,
})
}
fn assign_files(types: &mut [TypeView], config: &Config) {
let mut taken = BTreeSet::from([config.go.file.clone()]);
for t in types {
let base = crate::write::capped_stem(super::naming::go_file_name(
&crate::rust::naming::snake(std::slice::from_ref(&t.name)),
));
let file = (1u32..)
.map(|i| {
if i == 1 {
base.clone()
} else {
format!("{base}{i}")
}
})
.find(|candidate| !taken.contains(candidate) && super::naming::is_file_stem(candidate))
.expect("a free file name");
taken.insert(file.clone());
t.file = Some(file);
}
}
fn unqualified_names(ty: &str) -> Vec<String> {
scan_names(ty, false)
}
fn type_names(ty: &str) -> Vec<String> {
scan_names(ty, true)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Token<'a> {
Ident(&'a str),
Literal,
Semicolon,
Punct(&'a str),
}
fn tokens(ty: &str) -> Vec<Token<'_>> {
fn ends_line(last: Option<&Token<'_>>) -> bool {
match last {
Some(Token::Ident(word)) => {
!super::naming::is_keyword(word)
|| matches!(*word, "break" | "continue" | "fallthrough" | "return")
}
Some(Token::Literal) => true,
Some(Token::Punct(p)) => matches!(*p, ")" | "]" | "}"),
_ => false,
}
}
let ident = |c: char| c.is_alphanumeric() || c == '_';
let mut out = Vec::new();
let mut rest = ty;
while let Some(c) = rest.chars().next() {
let len = if c == '\n' {
if ends_line(out.last()) {
out.push(Token::Semicolon);
}
1
} else if c.is_whitespace() {
c.len_utf8()
} else if rest.starts_with("//") {
rest.find('\n').unwrap_or(rest.len())
} else if let Some(body) = rest.strip_prefix("/*") {
let len = body.find("*/").map_or(rest.len(), |end| end + 4);
if rest[..len].contains('\n') && ends_line(out.last()) {
out.push(Token::Semicolon);
}
len
} else if c.is_alphabetic() || c == '_' {
let len = rest.find(|c: char| !ident(c)).unwrap_or(rest.len());
out.push(Token::Ident(&rest[..len]));
len
} else if c.is_ascii_digit()
|| (c == '.' && rest[1..].starts_with(|c: char| c.is_ascii_digit()))
{
let hex = rest.starts_with("0x") || rest.starts_with("0X");
let mut len = 0;
let mut prev = ' ';
for c in rest.chars() {
let exponent = if hex {
matches!(prev, 'p' | 'P')
} else {
matches!(prev, 'e' | 'E')
};
let exponent_sign = matches!(c, '+' | '-') && exponent;
if !(ident(c) || c == '.' || exponent_sign) {
break;
}
len += c.len_utf8();
prev = c;
}
out.push(Token::Literal);
len
} else if matches!(c, '"' | '\'' | '`') {
let mut escaped = false;
let close = rest[1..].char_indices().find(|&(_, inner)| {
let closes = inner == c && !escaped;
escaped = c != '`' && inner == '\\' && !escaped;
closes
});
out.push(Token::Literal);
close.map_or(rest.len(), |(at, _)| at + 2)
} else if rest.starts_with("...") || rest.starts_with("<-") {
let len = if rest.starts_with("...") { 3 } else { 2 };
out.push(Token::Punct(&rest[..len]));
len
} else if c == ';' {
out.push(Token::Semicolon);
1
} else {
out.push(Token::Punct(&rest[..c.len_utf8()]));
c.len_utf8()
};
rest = &rest[len..];
}
out
}
fn scan_names(ty: &str, types_only: bool) -> Vec<String> {
let tokens = tokens(ty);
let at = |k: usize| tokens.get(k).copied();
let type_starts = |k: usize| {
matches!(
at(k),
Some(Token::Ident(_) | Token::Punct("*" | "[" | "(" | "..." | "<-"))
)
};
let after_brackets = |k: usize| {
let mut depth = 0usize;
for (j, token) in tokens.iter().enumerate().skip(k) {
match token {
Token::Punct("[") => depth += 1,
Token::Punct("]") => {
depth -= 1;
if depth == 0 {
return j + 1;
}
}
_ => {}
}
}
tokens.len()
};
let type_follows = |k: usize| match at(k) {
Some(Token::Punct("[")) => type_starts(after_brackets(k)),
_ => type_starts(k),
};
let named = |k: usize| {
let entry = k > 0
&& matches!(
at(k - 1),
Some(Token::Punct("(" | "," | "{") | Token::Semicolon)
);
if !entry {
return false;
}
let mut j = k + 1;
if at(j) == Some(Token::Punct("(")) {
return true;
}
while at(j) == Some(Token::Punct(",")) {
match at(j + 1) {
Some(Token::Ident(word)) if !super::naming::is_keyword(word) => j += 2,
_ => return false,
}
}
type_follows(j)
};
let mut out = Vec::new();
for (k, token) in tokens.iter().enumerate() {
let Token::Ident(word) = *token else {
continue;
};
let selector = k > 0 && at(k - 1) == Some(Token::Punct("."));
let qualifier = at(k + 1) == Some(Token::Punct("."));
if selector || qualifier {
continue;
}
if types_only && !super::naming::is_keyword(word) && named(k) {
continue;
}
out.push(word.to_owned());
}
out
}
fn names_unexported_type(ty: &str) -> bool {
const PREDECLARED: &[&str] = &[
"any",
"bool",
"byte",
"comparable",
"complex64",
"complex128",
"error",
"float32",
"float64",
"int",
"int8",
"int16",
"int32",
"int64",
"rune",
"string",
"uint",
"uint8",
"uint16",
"uint32",
"uint64",
"uintptr",
];
unqualified_names(ty).iter().any(|word| {
!word.starts_with(|c: char| c.is_uppercase())
&& !PREDECLARED.contains(&word.as_str())
&& !super::naming::is_keyword(word)
})
}
impl Builder<'_> {
fn member_ty(&self, view: &mut TypeView, prefix: String, ty: String) -> String {
let substituted = super::imports::qualifiers(&ty)
.iter()
.any(|q| !BUILTIN_IMPORTS.iter().any(|(_, name)| name == q))
|| names_unexported_type(&ty);
if !self.config.validation || !substituted {
return ty;
}
let name = format!("{prefix}{}", view.name);
view.validate_aliases.push(AliasView {
name: name.clone(),
ty,
});
name
}
fn allocate_type_names(&mut self) -> Result<(), GenerateError> {
for reserved in ["Nullable", "Int64", "Int32", "Null"] {
self.package_names.reserve(reserved);
}
if self.config.exact_numbers {
for reserved in ["Decimal", "DecimalMaxDigits", "ParseDecimal"] {
self.package_names.reserve(reserved);
}
}
if self.config.validation {
for reserved in [
"ValidationReport",
"Finding",
"FindingKind",
"Violation",
"Unevaluated",
"Validator",
] {
self.package_names.reserve(reserved);
}
}
let ir = self.ir;
let order = ir
.order
.iter()
.filter(|id| ir.types[*id].component.is_some());
let rest = ir
.order
.iter()
.filter(|id| ir.types[*id].component.is_none());
for id in order.chain(rest) {
let def = &self.ir.types[id];
if matches!(def.kind, TypeKind::Extern) || self.suppressed.contains(id) {
continue;
}
let base = match self.type_config(def).and_then(|t| t.rename.clone()) {
Some(rename) => {
if !is_exported_ident(&rename) {
return Err(GenerateError::Config(format!(
"`types.{}.rename = {rename:?}` must be an exported Go identifier: an ASCII capital, then letters, digits or `_`",
def.component.as_deref().unwrap_or_default()
)));
}
rename
}
None => exported(&def.suggested_name),
};
let name = self.package_names.allocate(base);
self.names.insert(id.clone(), name);
}
Ok(())
}
fn type_config(&self, def: &TypeDef) -> Option<&TypeConfig> {
def.component
.as_ref()
.and_then(|c| self.config.types.get(c))
}
fn field_config<'c>(&'c self, def: &TypeDef, raw_name: &str) -> Option<&'c FieldConfig> {
self.type_config(def).and_then(|t| t.fields.get(raw_name))
}
fn spell(&mut self, ty: &TypeRef) -> Result<String, GenerateError> {
let spelled = match ty {
TypeRef::Named(id) => {
let def = &self.ir.types[id];
if let TypeKind::Extern = def.kind {
let component = def.component.clone().unwrap_or_default();
let spelled = self.extern_spelling(&component)?;
self.refused_extern(&spelled)
} else {
self.names[id].clone()
}
}
TypeRef::Boxed(inner) => format!("*{}", self.spell(inner)?),
TypeRef::Nullable(inner) => format!("*{}", self.spell(unboxed(inner))?),
TypeRef::String => self.refused("string"),
TypeRef::Integer(IntWidth::Int64) => {
self.support.int64 = true;
"Int64".into()
}
TypeRef::Integer(IntWidth::Int32) => {
self.support.int32 = true;
"Int32".into()
}
TypeRef::Number(FloatWidth::Double) => self.refused("float64"),
TypeRef::Number(FloatWidth::Float) => self.refused("float32"),
TypeRef::Decimal => {
self.support.decimal = true;
"Decimal".into()
}
TypeRef::Boolean => self.refused("bool"),
TypeRef::Null => {
self.support.null = true;
"Null".into()
}
TypeRef::Any => "jsontext.Value".into(),
TypeRef::Array(inner) => {
let spelled = format!("[]{}", self.spell(unboxed(inner))?);
self.refused(&spelled)
}
TypeRef::Map(inner) => {
let spelled = format!("map[string]{}", self.spell(unboxed(inner))?);
self.refused(&spelled)
}
TypeRef::Extern(key) => {
let spelled = self.extern_spelling(key)?;
self.refused_extern(&spelled)
}
};
Ok(spelled)
}
fn refused_extern(&mut self, spelled: &str) -> String {
if !null_holding_spelling(spelled) {
self.refuse_null_isolated.insert(spelled.to_owned());
} else if spelled != "jsontext.Value" {
self.isolated.insert(spelled.to_owned());
}
spelled.to_owned()
}
fn refused(&mut self, spelled: &str) -> String {
self.refuse_null.insert(spelled.to_owned());
spelled.to_owned()
}
fn extern_spelling(&mut self, key: &str) -> Result<String, GenerateError> {
let spelling = self
.config
.substitutions
.get(key)
.and_then(|s| s.go.as_ref())
.ok_or_else(|| {
GenerateError::Config(format!("substitution `{key}` has no `go` spelling"))
})?;
if let Some(import) = &spelling.import {
self.externs.insert(import.clone());
self.extern_names
.entry(import.clone())
.or_default()
.extend(super::imports::qualifiers(&spelling.name));
}
self.spellings.insert(spelling.name.clone());
Ok(spelling.name.clone())
}
fn doc(
description: Option<&str>,
default: Option<&serde_json::Value>,
read_only: bool,
write_only: bool,
constraints: &crate::front::Constraints,
deprecated: bool,
) -> Vec<String> {
let mut lines: Vec<String> = description
.map(|d| d.lines().map(|l| l.trim_end().to_owned()).collect())
.unwrap_or_default();
let mut notes = Vec::new();
if let Some(default) = default {
notes.push(format!("Default: `{default}`."));
}
if read_only {
notes.push("Read only.".to_owned());
}
if write_only {
notes.push("Write only.".to_owned());
}
notes.extend(constraint_notes(constraints));
for paragraph in [notes, deprecation(deprecated)] {
if !paragraph.is_empty() {
if !lines.is_empty() {
lines.push(String::new());
}
lines.extend(paragraph);
}
}
lines
.into_iter()
.flat_map(|l| l.split(['\n', '\r']).map(comment_text).collect::<Vec<_>>())
.collect()
}
fn type_view(&mut self, def: &TypeDef) -> Result<Option<TypeView>, GenerateError> {
let Some(name) = self.names.get(&def.id).cloned() else {
return Ok(None);
};
let raw_name = def
.component
.clone()
.unwrap_or_else(|| def.id.pointer.clone());
let mut doc = Vec::new();
if let Some(title) = def
.title
.as_deref()
.filter(|t| !t.trim().is_empty() && def.component.as_deref() != Some(t))
{
doc.extend(title.trim().lines().map(|l| comment_text(l.trim_end())));
doc.push(String::new());
}
doc.extend(Self::doc(
def.description.as_deref(),
None,
false,
false,
&def.constraints,
false,
));
if def.nullable {
doc.push(
"`null` is a valid instance; a position holding this type is a pointer or a `Nullable`."
.to_owned(),
);
}
while doc.last().is_some_and(String::is_empty) {
doc.pop();
}
let deprecated = deprecation(def.deprecated);
if !deprecated.is_empty() {
if !doc.is_empty() {
doc.push(String::new());
}
doc.extend(deprecated);
}
let mut view = TypeView {
kind: "struct",
name_literal: quote(&name),
name,
raw_name,
doc,
fields: Vec::new(),
variants: Vec::new(),
branches: Vec::new(),
inner: String::new(),
tag: String::new(),
fallback: None,
tag_literal: String::new(),
exclusive: false,
required_count: 0,
extra_ty: String::new(),
extra_name: String::new(),
member_patterns: Vec::new(),
pattern_tys: Vec::new(),
others_ty: None,
validate_aliases: Vec::new(),
marshal: false,
from_raw: String::new(),
validate: None,
validate_null: Vec::new(),
file: None,
};
if !self.fill_kind(def, &mut view)? {
return Ok(None);
}
if self.config.validation {
self.support.validation = true;
self.needs.math = true;
let opted_out = self.type_config(def).and_then(|t| t.validation) == Some(false);
let validates = |ty: &TypeRef| self.validates(ty);
let nil_able = |ty: &TypeRef| match ty {
TypeRef::Named(id) => matches!(
self.alias_target(id),
Some(TypeRef::Boxed(_) | TypeRef::Nullable(_))
),
_ => false,
};
let names = &self.names;
let ir = self.ir;
let raw_holder = |ty: &TypeRef| {
let mut id = ty.direct_named()?;
for _ in 0..=ir.types.len() {
match &ir.types.get(id)?.kind {
TypeKind::Newtype(TypeRef::Any) => {
let name = names.get(id)?;
return Some(format!("{name}(jsontext.Value(\"null\"))"));
}
TypeKind::UnionOpen(_) | TypeKind::ComposedOpen(_) => {
let name = names.get(id)?;
return Some(format!("{name}{{raw: jsontext.Value(\"null\")}}"));
}
TypeKind::Alias(inner) | TypeKind::Newtype(inner) => {
id = inner.direct_named()?
}
_ => return None,
}
}
None
};
let holder_id = def.id.clone();
let loops = |ty: &TypeRef| crate::checks::loops_back(ir, &holder_id, ty);
let null_name = |ty: &TypeRef| {
let mut id = ty.direct_named()?;
for _ in 0..=ir.types.len() {
let def = ir.types.get(id)?;
match &def.kind {
TypeKind::Alias(inner) => id = inner.direct_named()?,
_ if !crate::checks::has_null_hook(def)
|| self.type_config(def).and_then(|t| t.validation) == Some(false) =>
{
return None;
}
_ => return names.get(&def.id).cloned(),
}
}
None
};
let mut cx = super::validation::Context {
validates: &validates,
nil_able: &nil_able,
raw_holder: &raw_holder,
loops: &loops,
null_name: &null_name,
extern_checks: &|ty: &TypeRef| {
crate::checks::extern_checks(ir, ty, !self.validates(ty))
},
ir,
needs: self.needs,
};
view.validate = super::validation::body(def, &view, opted_out, &mut cx);
if view.validate.is_some() && !opted_out {
view.validate_null = super::validation::null_body(def, &view.name, &mut cx);
}
if opted_out && view.validate.is_none() {
return Err(opt_out_on_alias(def));
}
self.needs = cx.needs;
}
Ok(Some(view))
}
fn fill_kind(&mut self, def: &TypeDef, view: &mut TypeView) -> Result<bool, GenerateError> {
match &def.kind {
TypeKind::Extern => return Ok(false),
TypeKind::Struct(s) => {
view.kind = "struct";
let mut fields = Allocator::default();
fields.reserve("UnmarshalJSONFrom");
if self.config.validation {
fields.reserve("Validate");
}
fields.reserve("MarshalJSONTo");
let mut required_count = 0;
for field in &s.fields {
let config = self.field_config(def, &field.raw_name);
let rename = config.and_then(|f| f.rename.clone());
let go_tags = config.map(|f| f.go_tags.clone()).unwrap_or_default();
let at = format!("types.{}.fields.{}", view.raw_name, field.raw_name);
let base = match rename {
Some(rename) if !is_exported_ident(&rename) => {
return Err(GenerateError::Config(format!(
"`{at}.rename = {rename:?}` must be an exported Go identifier: an ASCII capital, then letters, digits or `_`"
)));
}
Some(rename) => rename,
None => exported(std::slice::from_ref(&field.raw_name)),
};
let name = fields.allocate(base);
let holds_null = self.holds_null(&field.ty);
let (ty, omitzero) = match (field.required, field.nullable || holds_null) {
(true, false) => (self.spell(&field.ty)?, false),
(true, true) => {
self.support.nullable = true;
(
format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
false,
)
}
(false, false) if self.substituted(&field.ty) => {
self.support.nullable = true;
(
format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
true,
)
}
(false, false) => {
let inner = self.spell(&field.ty)?;
if inner.starts_with('*') {
(inner, true)
} else {
(format!("*{inner}"), true)
}
}
(false, true) => {
self.support.nullable = true;
(
format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
true,
)
}
};
let required_index = field.required.then(|| {
required_count += 1;
required_count - 1
});
let tag = struct_tag(&field.raw_name, omitzero, &go_tags, &at)?;
if !tag_name_ok(&field.raw_name) {
view.marshal = true;
self.support.sorted_keys |= matches!(s.additional, Additional::CatchAll(_));
}
let present = match (omitzero, ty.starts_with("Nullable[")) {
(false, _) => String::new(),
(true, true) => format!("v.{name}.Set"),
(true, false) => format!("v.{name} != nil"),
};
view.fields.push(FieldView {
present,
name,
raw_name: field.raw_name.clone(),
ty,
tag,
literal: quote(&field.raw_name),
non_null: !field.nullable && !holds_null,
required_index,
catch_all: false,
doc: Self::doc(
field.description.as_deref(),
field.default.as_ref(),
field.read_only,
field.write_only,
&field.constraints,
field.deprecated,
),
});
}
view.required_count = required_count;
if let Some(patterns) = &s.only_patterns {
self.needs.pattern = true;
self.support.member_patterns = true;
view.member_patterns = patterns.iter().map(|p| quote(p)).collect();
}
for (i, pattern) in s.patterns.iter().enumerate() {
let spelled = match pattern.branch() {
Some(b) => {
let ty = self.spell(unboxed(&b.ty))?;
Some(self.member_ty(view, format!("pattern{i}Of"), ty))
}
None => None,
};
view.pattern_tys.push(spelled);
}
if let crate::ir::Others::Schema(b) = &s.others {
let ty = self.spell(unboxed(&b.ty))?;
view.others_ty = Some(self.member_ty(view, "othersOf".to_owned(), ty));
}
if let Additional::CatchAll(ty) = &s.additional {
let inner = self.spell(unboxed(ty))?;
let name = fields.allocate("AdditionalProperties".to_owned());
view.extra_name = name.clone();
view.extra_ty = inner.clone();
view.fields.push(FieldView {
name,
raw_name: "additionalProperties".to_owned(),
ty: format!("map[string]{inner}"),
tag: "`json:\",embed\"`".to_owned(),
doc: vec!["Members not named above.".to_owned()],
literal: String::new(),
non_null: false,
required_index: None,
catch_all: true,
present: String::new(),
});
}
}
TypeKind::StringEnum(values) => {
view.kind = "enum";
let mut seen = BTreeSet::new();
for value in values.iter().filter(|v| seen.insert(v.as_str())) {
let base = if value.trim().is_empty() {
"Empty".to_owned()
} else {
exported(std::slice::from_ref(value))
};
let name = self.package_names.allocate(format!("{}{base}", view.name));
view.variants.push(VariantView {
name,
literal: quote(value),
value: value.clone(),
ty: String::new(),
accessor: String::new(),
constructor: String::new(),
synthetic: false,
cases: String::new(),
});
}
}
TypeKind::UnionTagged(u) => {
view.kind = "union_tagged";
self.support.tagged = true;
view.tag = u.tag.clone();
view.tag_literal = quote(&u.tag);
view.fallback = u.fallback;
let mut methods = Allocator::default();
for reserved in ["Tag", "Value", "MarshalJSONTo", "UnmarshalJSONFrom"] {
methods.reserve(reserved);
}
if self.config.validation {
methods.reserve("Validate");
}
for variant in &u.variants {
let base = exported(&variant.suggested_name);
let accessor = methods.allocate(format!("As{base}"));
let constructor = self
.package_names
.allocate(format!("{}From{base}", view.name));
view.variants.push(VariantView {
name: base,
literal: quote(&variant.value),
value: variant.value.clone(),
ty: self.spell(&variant.ty)?,
accessor,
constructor,
synthetic: variant.synthetic,
cases: std::iter::once(&variant.value)
.chain(&variant.aliases)
.map(|tag| quote(tag))
.collect::<Vec<_>>()
.join(", "),
});
}
}
TypeKind::UnionOpen(u) => {
view.kind = "union_open";
view.exclusive = u.exclusive;
view.branches = self.branches(&view.name, &u.branches)?;
}
TypeKind::ComposedOpen(branches) => {
view.kind = "composed_open";
view.from_raw = self.package_names.allocate(format!("{}FromRaw", view.name));
view.branches = self.branches(&view.name, branches)?;
}
TypeKind::Newtype(inner) | TypeKind::Alias(inner) => {
view.inner = self.spell(inner)?;
let substituted = match unboxed(inner) {
TypeRef::Extern(_) => true,
TypeRef::Named(id) => matches!(self.ir.types[id].kind, TypeKind::Extern),
_ => false,
};
view.kind = if matches!(def.kind, TypeKind::Alias(_))
|| view.inner.starts_with('*')
|| substituted
{
"alias"
} else {
"newtype"
};
}
}
Ok(true)
}
fn holds_null(&self, ty: &TypeRef) -> bool {
let mut ty = ty;
for _ in 0..=self.ir.types.len() {
ty = match ty {
TypeRef::Any | TypeRef::Null => return true,
TypeRef::Boxed(inner) => inner,
TypeRef::Extern(key) => return self.extern_holds_null(key),
TypeRef::Named(id) => match &self.ir.types[id].kind {
TypeKind::Extern => {
let component = self.ir.types[id].component.as_deref();
return self.extern_holds_null(component.unwrap_or_default());
}
TypeKind::UnionOpen(_) | TypeKind::ComposedOpen(_) => return true,
TypeKind::Newtype(inner) | TypeKind::Alias(inner) => inner,
_ => return false,
},
_ => return false,
};
}
false
}
fn alias_target(&self, id: &SchemaId) -> Option<&TypeRef> {
match &self.ir.types.get(id)?.kind {
TypeKind::Alias(inner) => Some(inner),
TypeKind::Newtype(inner)
if matches!(inner, TypeRef::Boxed(_) | TypeRef::Nullable(_))
|| self.substituted(inner) =>
{
Some(inner)
}
_ => None,
}
}
fn validates(&self, ty: &TypeRef) -> bool {
let mut ids = Vec::new();
ty.named(&mut ids);
ids.iter().any(|id| self.validates_named(id, 0))
}
fn validates_named(&self, id: &SchemaId, depth: usize) -> bool {
if depth > self.ir.types.len()
|| !self.names.contains_key(id)
|| matches!(self.ir.types[id].kind, TypeKind::Extern)
{
return false;
}
match self.alias_target(id) {
Some(inner) => inner
.direct_named()
.is_some_and(|target| self.validates_named(target, depth + 1)),
None => true,
}
}
fn substituted(&self, ty: &TypeRef) -> bool {
let mut ty = ty;
for _ in 0..=self.ir.types.len() {
ty = match ty {
TypeRef::Extern(_) => return true,
TypeRef::Boxed(inner) => inner,
TypeRef::Named(id) => match &self.ir.types[id].kind {
TypeKind::Extern => return true,
TypeKind::Newtype(inner) | TypeKind::Alias(inner) => inner,
_ => return false,
},
_ => return false,
};
}
false
}
fn extern_holds_null(&self, key: &str) -> bool {
self.config
.substitutions
.get(key)
.and_then(|s| s.go.as_ref())
.is_some_and(|go| null_holding_spelling(&go.name))
}
fn branches(
&mut self,
owner: &str,
branches: &[crate::ir::Branch],
) -> Result<Vec<BranchView>, GenerateError> {
let mut methods = Allocator::default();
for reserved in ["Raw", "MarshalJSONTo", "UnmarshalJSONFrom"] {
methods.reserve(reserved);
}
if self.config.validation {
methods.reserve("Validate");
}
let mut out = Vec::new();
for branch in branches {
let base = exported(&branch.suggested_name);
out.push(BranchView {
accessor: methods.allocate(format!("As{base}")),
constructor: self.package_names.allocate(format!("{owner}From{base}")),
ty: self.spell(&branch.ty)?,
});
}
Ok(out)
}
}
fn null_holding_spelling(spelled: &str) -> bool {
spelled.starts_with('*')
|| spelled == "jsontext.Value"
|| spelled == "any"
|| spelled.starts_with("interface")
}
pub(crate) fn opt_out_on_alias(def: &TypeDef) -> GenerateError {
let name = def.component.as_deref().unwrap_or_default();
GenerateError::Config(format!(
"`types.{name}.validation = false` cannot apply: `{name}` is an alias, which validates as the type it names; opt that type out instead"
))
}
fn unboxed(ty: &TypeRef) -> &TypeRef {
match ty {
TypeRef::Boxed(inner) => inner,
other => other,
}
}
fn deprecation(deprecated: bool) -> Vec<String> {
if deprecated {
vec!["Deprecated: the description marks this deprecated.".to_owned()]
} else {
Vec::new()
}
}
fn struct_tag(
raw_name: &str,
omitzero: bool,
extra: &BTreeMap<String, String>,
at: &str,
) -> Result<String, GenerateError> {
let mut json = raw_name.to_owned();
if !tag_name_ok(raw_name) {
json = "-".to_owned();
} else if omitzero {
json.push_str(",omitzero");
} else if raw_name == "-" {
json.push_str(",case:strict");
}
let mut parts = vec![format!("json:{}", quote(&json))];
for (key, value) in extra {
if key == "json" {
return Err(GenerateError::Config(format!(
"`{at}.go_tags` sets `json`, which the generator owns: it carries the member name and the absent-versus-null contract"
)));
}
if !is_tag_key(key) {
return Err(GenerateError::Config(format!(
"`{at}.go_tags` key {key:?} is not a struct-tag key: it must be printable ASCII without space, quote or colon"
)));
}
parts.push(format!("{key}:{}", quote(value)));
}
let tag = parts.join(" ");
Ok(if tag.contains('`') {
quote(&tag)
} else {
format!("`{tag}`")
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn struct_tags() {
let none = BTreeMap::new();
assert_eq!(
struct_tag("name", false, &none, "x").unwrap(),
"`json:\"name\"`"
);
assert_eq!(
struct_tag("-", false, &none, "x").unwrap(),
"`json:\"-,case:strict\"`"
);
assert_eq!(
struct_tag("a b", true, &none, "x").unwrap(),
"`json:\"a b,omitzero\"`"
);
let extra = BTreeMap::from([("db".to_owned(), "x`y".to_owned())]);
assert_eq!(
struct_tag("n", false, &extra, "x").unwrap(),
"\"json:\\\"n\\\" db:\\\"x`y\\\"\""
);
let json = BTreeMap::from([("json".to_owned(), "x".to_owned())]);
assert!(struct_tag("n", false, &json, "x").is_err());
let bad = BTreeMap::from([("a b".to_owned(), "x".to_owned())]);
assert!(struct_tag("n", false, &bad, "x").is_err());
}
#[test]
fn import_package_names() {
assert_eq!(package_of("example.com/x/uuid"), "uuid");
assert_eq!(package_of("encoding/json/v2"), "json");
assert_eq!(package_of("time"), "time");
assert_eq!(package_of("example.com/v"), "v");
}
}