1use std::collections::BTreeSet;
24
25use proc_macro::TokenStream;
26use proc_macro2::{Span, TokenStream as TokenStream2};
27use quote::{quote, quote_spanned};
28use syn::ext::IdentExt;
29use syn::spanned::Spanned;
30use syn::{
31 Attribute, Data, DeriveInput, Expr, ExprLit, ExprUnary, Fields, FieldsNamed, Ident, Lit,
32 LitStr, Meta, Token, Type, UnOp, Variant, parse_macro_input,
33};
34
35use trilean_json_shape_pattern as pattern;
38
39#[proc_macro_derive(Shape, attributes(shape, serde))]
40pub fn derive_shape(input: TokenStream) -> TokenStream {
41 let input = parse_macro_input!(input as DeriveInput);
42 expand(&input)
43 .unwrap_or_else(syn::Error::into_compile_error)
44 .into()
45}
46
47type Result<T> = syn::Result<T>;
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50enum Case {
51 Lower,
52 Upper,
53 Camel,
54 Pascal,
55 Snake,
56 ScreamingSnake,
57 Kebab,
58 ScreamingKebab,
59}
60
61fn parse_case(text: &LitStr) -> Result<Case> {
62 match text.value().as_str() {
63 "lowercase" => Ok(Case::Lower),
64 "UPPERCASE" => Ok(Case::Upper),
65 "camelCase" => Ok(Case::Camel),
66 "PascalCase" => Ok(Case::Pascal),
67 "snake_case" => Ok(Case::Snake),
68 "SCREAMING_SNAKE_CASE" => Ok(Case::ScreamingSnake),
69 "kebab-case" => Ok(Case::Kebab),
70 "SCREAMING-KEBAB-CASE" => Ok(Case::ScreamingKebab),
71 other => Err(syn::Error::new(
72 text.span(),
73 format!("rename_all = \"{other}\" is not supported by trilean_json_shape::Shape"),
74 )),
75 }
76}
77
78fn variant_name(name: &str, case: Option<Case>) -> String {
80 fn snake(name: &str) -> String {
81 let mut snake = String::new();
82 for (position, letter) in name.char_indices() {
83 if position > 0 && letter.is_uppercase() {
84 snake.push('_');
85 }
86 snake.push(letter.to_ascii_lowercase());
87 }
88 snake
89 }
90 match case {
91 None | Some(Case::Pascal) => name.to_owned(),
92 Some(Case::Lower) => name.to_ascii_lowercase(),
93 Some(Case::Upper) => name.to_ascii_uppercase(),
94 Some(Case::Camel) => name[..1].to_ascii_lowercase() + &name[1..],
95 Some(Case::Snake) => snake(name),
96 Some(Case::ScreamingSnake) => snake(name).to_ascii_uppercase(),
97 Some(Case::Kebab) => snake(name).replace('_', "-"),
98 Some(Case::ScreamingKebab) => snake(name).to_ascii_uppercase().replace('_', "-"),
99 }
100}
101
102fn field_name(name: &str, case: Option<Case>) -> String {
105 fn pascal(name: &str) -> String {
106 let mut pascal = String::new();
107 let mut capitalise = true;
108 for letter in name.chars() {
109 if letter == '_' {
110 capitalise = true;
111 } else if capitalise {
112 pascal.push(letter.to_ascii_uppercase());
113 capitalise = false;
114 } else {
115 pascal.push(letter);
116 }
117 }
118 pascal
119 }
120 match case {
121 None | Some(Case::Snake | Case::Lower) => name.to_owned(),
123 Some(Case::Upper | Case::ScreamingSnake) => name.to_ascii_uppercase(),
124 Some(Case::Pascal) => pascal(name),
125 Some(Case::Camel) => {
126 let pascal = pascal(name);
127 if pascal.is_empty() {
128 pascal
129 } else {
130 pascal[..1].to_ascii_lowercase() + &pascal[1..]
131 }
132 }
133 Some(Case::Kebab) => name.replace('_', "-"),
134 Some(Case::ScreamingKebab) => name.to_ascii_uppercase().replace('_', "-"),
135 }
136}
137
138fn name_of(ident: &Ident) -> String {
139 ident.unraw().to_string()
140}
141
142fn description(attributes: &[Attribute]) -> Option<String> {
144 let lines: Vec<String> = attributes
145 .iter()
146 .filter(|attribute| attribute.path().is_ident("doc"))
147 .filter_map(|attribute| match &attribute.meta {
148 Meta::NameValue(pair) => match &pair.value {
149 Expr::Lit(ExprLit {
150 lit: Lit::Str(text),
151 ..
152 }) => Some(text.value().trim().to_owned()),
153 _ => None,
154 },
155 _ => None,
156 })
157 .filter(|line| !line.is_empty())
158 .collect();
159 if lines.is_empty() {
160 None
161 } else {
162 Some(lines.join(" "))
163 }
164}
165
166#[derive(Clone, Copy, PartialEq, Eq)]
168enum Position {
169 Container,
170 Variant,
171 Field,
172 TupleField,
173}
174
175impl Position {
176 fn describe(self) -> &'static str {
177 match self {
178 Position::Container => "a struct or enum",
179 Position::Variant => "a variant",
180 Position::Field => "a named field",
181 Position::TupleField => "the field of a tuple variant",
182 }
183 }
184}
185
186#[derive(Clone)]
188enum Spec {
189 Min(f64),
190 ExclusiveMin(f64),
191 Max(f64),
192 MinLength(usize),
193 Pattern(String),
194 MinItems(usize),
195 MaxItems(usize),
196 UniqueItems,
197 MinProperties(usize),
198 KeyPattern(String),
199}
200
201impl Spec {
202 fn name(&self) -> &'static str {
203 match self {
204 Spec::Min(_) => "min",
205 Spec::ExclusiveMin(_) => "exclusive_min",
206 Spec::Max(_) => "max",
207 Spec::MinLength(_) => "min_length",
208 Spec::Pattern(_) => "pattern",
209 Spec::MinItems(_) => "min_items",
210 Spec::MaxItems(_) => "max_items",
211 Spec::UniqueItems => "unique_items",
212 Spec::MinProperties(_) => "min_properties",
213 Spec::KeyPattern(_) => "property_names",
214 }
215 }
216
217 fn classes(&self) -> &'static [&'static str] {
219 match self {
220 Spec::Min(_) | Spec::ExclusiveMin(_) | Spec::Max(_) => &["Integer", "Number"],
221 Spec::MinLength(_) | Spec::Pattern(_) => &["String"],
222 Spec::MinItems(_) | Spec::MaxItems(_) | Spec::UniqueItems => &["Array"],
223 Spec::MinProperties(_) => &["Map", "OpenObject"],
224 Spec::KeyPattern(_) => &["Map"],
225 }
226 }
227
228 fn tokens(&self) -> TokenStream2 {
229 match self {
230 Spec::Min(bound) => quote! { ::trilean_json_shape::Constraint::Min(#bound) },
231 Spec::ExclusiveMin(bound) => {
232 quote! { ::trilean_json_shape::Constraint::ExclusiveMin(#bound) }
233 }
234 Spec::Max(bound) => quote! { ::trilean_json_shape::Constraint::Max(#bound) },
235 Spec::MinLength(length) => {
236 quote! { ::trilean_json_shape::Constraint::MinLength(#length) }
237 }
238 Spec::Pattern(source) => {
239 quote! { ::trilean_json_shape::Constraint::Pattern(#source.to_owned()) }
240 }
241 Spec::MinItems(count) => quote! { ::trilean_json_shape::Constraint::MinItems(#count) },
242 Spec::MaxItems(count) => quote! { ::trilean_json_shape::Constraint::MaxItems(#count) },
243 Spec::UniqueItems => quote! { ::trilean_json_shape::Constraint::UniqueItems },
244 Spec::MinProperties(count) => {
245 quote! { ::trilean_json_shape::Constraint::MinProperties(#count) }
246 }
247 Spec::KeyPattern(source) => {
248 quote! { ::trilean_json_shape::Constraint::KeyPattern(#source.to_owned()) }
249 }
250 }
251 }
252}
253
254#[derive(Clone)]
255struct Constrained {
256 span: Span,
257 spec: Spec,
258}
259
260type Located = (Span, Constant);
262
263#[derive(Clone)]
264enum Constant {
265 Bool(bool),
266 Text(String),
267}
268
269#[derive(Default)]
272struct Attrs {
273 tag: Option<String>,
274 untagged: bool,
275 rename_all: Option<Case>,
276 strict: bool,
277 name: Option<String>,
278 together: Vec<(Span, Vec<Ident>)>,
279 any_of: Vec<(Span, Vec<Ident>)>,
280 one_of: Vec<(Span, Vec<Ident>)>,
281 container_min_properties: Option<usize>,
282 rename: Option<String>,
283 default: bool,
284 flatten: bool,
285 constraints: Vec<Constrained>,
286 constant: Option<Located>,
287}
288
289fn number_of(expression: &Expr) -> Result<f64> {
290 match expression {
291 Expr::Lit(ExprLit {
292 lit: Lit::Int(number),
293 ..
294 }) => number.base10_parse(),
295 Expr::Lit(ExprLit {
296 lit: Lit::Float(number),
297 ..
298 }) => number.base10_parse(),
299 Expr::Unary(ExprUnary {
300 op: UnOp::Neg(_),
301 expr,
302 ..
303 }) => number_of(expr).map(|number| -number),
304 other => Err(syn::Error::new(other.span(), "expected a number")),
305 }
306}
307
308fn count_of(literal: &Lit) -> Result<usize> {
309 match literal {
310 Lit::Int(number) => number.base10_parse(),
311 other => Err(syn::Error::new(other.span(), "expected a whole number")),
312 }
313}
314
315fn pattern_of(literal: &LitStr) -> Result<String> {
317 let source = literal.value();
318 pattern::Pattern::new(&source)
319 .map_err(|error| syn::Error::new(literal.span(), error.to_string()))?;
320 Ok(source)
321}
322
323fn read(attributes: &[Attribute], position: Position) -> Result<Attrs> {
326 let mut attrs = Attrs::default();
327 let mut seen = BTreeSet::new();
328 for attribute in attributes {
329 let from_serde = attribute.path().is_ident("serde");
330 if !from_serde && !attribute.path().is_ident("shape") {
331 continue;
332 }
333 attribute.parse_nested_meta(|meta| {
334 let Some(ident) = meta.path.get_ident() else {
335 return Err(meta.error("expected an attribute name"));
336 };
337 let key = name_of(ident);
338 let source = if from_serde { "serde" } else { "shape" };
339 if !matches!(key.as_str(), "together" | "any_of" | "one_of") && !seen.insert(format!("{source}:{key}")) {
340 return Err(meta.error(format!("`{key}` is given twice")));
341 }
342 let span = meta.path.span();
343 let applies_to = |positions: &[Position]| -> Result<()> {
344 if positions.contains(&position) {
345 Ok(())
346 } else {
347 Err(meta.error(format!("`{key}` does not apply to {}", position.describe())))
348 }
349 };
350 let constrained = |spec: Spec| Constrained { span, spec };
351 let on_member = [Position::Variant, Position::Field, Position::TupleField];
352 if from_serde {
353 match key.as_str() {
354 "tag" => {
355 applies_to(&[Position::Container])?;
356 attrs.tag = Some(meta.value()?.parse::<LitStr>()?.value());
357 }
358 "untagged" => {
359 applies_to(&[Position::Container])?;
360 attrs.untagged = true;
361 }
362 "rename_all" => {
363 applies_to(&[Position::Container])?;
364 attrs.rename_all = Some(parse_case(&meta.value()?.parse::<LitStr>()?)?);
365 }
366 "deny_unknown_fields" => {
367 applies_to(&[Position::Container])?;
368 attrs.strict = true;
369 }
370 "rename" => {
371 applies_to(&[Position::Variant, Position::Field])?;
372 attrs.rename = Some(meta.value()?.parse::<LitStr>()?.value());
373 }
374 "default" => {
375 applies_to(&[Position::Field])?;
376 if meta.input.peek(Token![=]) {
377 return Err(meta.error("default = \"path\" is not supported; use a type that implements Default"));
378 }
379 attrs.default = true;
380 }
381 "flatten" => {
382 applies_to(&[Position::Field])?;
383 attrs.flatten = true;
384 }
385 "skip_serializing_if" => {
386 applies_to(&[Position::Field])?;
387 meta.value()?.parse::<LitStr>()?;
388 }
389 _ => return Err(meta.error(format!("the serde attribute `{key}` is not supported by trilean_json_shape::Shape"))),
390 }
391 return Ok(());
392 }
393 match key.as_str() {
394 "strict" => {
395 applies_to(&[Position::Container])?;
396 attrs.strict = true;
397 }
398 "name" => {
399 applies_to(&[Position::Container])?;
400 attrs.name = Some(meta.value()?.parse::<LitStr>()?.value());
401 }
402 "together" | "any_of" | "one_of" => {
403 applies_to(&[Position::Container])?;
404 let mut names = Vec::new();
405 meta.parse_nested_meta(|inner| {
406 let ident = inner
407 .path
408 .get_ident()
409 .ok_or_else(|| inner.error("expected a field name"))?;
410 names.push(ident.clone());
411 Ok(())
412 })?;
413 match key.as_str() {
414 "together" => attrs.together.push((span, names)),
415 "any_of" => attrs.any_of.push((span, names)),
416 _ => attrs.one_of.push((span, names)),
417 }
418 }
419 "min_properties" if position == Position::Container => {
420 attrs.container_min_properties = Some(count_of(&meta.value()?.parse::<Lit>()?)?);
421 }
422 "min_properties" => {
423 applies_to(&on_member)?;
424 let count = count_of(&meta.value()?.parse::<Lit>()?)?;
425 attrs.constraints.push(constrained(Spec::MinProperties(count)));
426 }
427 "min" | "max" | "exclusive_min" => {
428 applies_to(&on_member)?;
429 let bound = number_of(&meta.value()?.parse::<Expr>()?)?;
430 attrs.constraints.push(constrained(match key.as_str() {
431 "min" => Spec::Min(bound),
432 "max" => Spec::Max(bound),
433 _ => Spec::ExclusiveMin(bound),
434 }));
435 }
436 "min_length" | "min_items" | "max_items" => {
437 applies_to(&on_member)?;
438 let count = count_of(&meta.value()?.parse::<Lit>()?)?;
439 attrs.constraints.push(constrained(match key.as_str() {
440 "min_length" => Spec::MinLength(count),
441 "min_items" => Spec::MinItems(count),
442 _ => Spec::MaxItems(count),
443 }));
444 }
445 "unique_items" => {
446 applies_to(&on_member)?;
447 attrs.constraints.push(constrained(Spec::UniqueItems));
448 }
449 "pattern" | "property_names" => {
450 applies_to(&on_member)?;
451 let source = pattern_of(&meta.value()?.parse::<LitStr>()?)?;
452 attrs.constraints.push(constrained(if key == "pattern" {
453 Spec::Pattern(source)
454 } else {
455 Spec::KeyPattern(source)
456 }));
457 }
458 "constant" => {
459 applies_to(&on_member)?;
460 attrs.constant = Some((
461 span,
462 match meta.value()?.parse::<Lit>()? {
463 Lit::Bool(flag) => Constant::Bool(flag.value),
464 Lit::Str(text) => Constant::Text(text.value()),
465 other => return Err(syn::Error::new(other.span(), "constant takes a boolean or a string")),
466 },
467 ));
468 }
469 _ => return Err(meta.error(format!("the `{key}` attribute is not supported by trilean_json_shape::Shape"))),
470 }
471 Ok(())
472 })?;
473 }
474 Ok(attrs)
475}
476
477struct Member {
479 ident: Ident,
480 key: String,
481 ty: Type,
482 attrs: Attrs,
483 description: Option<String>,
484 span: Span,
485}
486
487fn members(fields: &FieldsNamed, rename_all: Option<Case>) -> Result<Vec<Member>> {
488 let mut found = Vec::new();
489 for field in &fields.named {
490 let Some(ident) = &field.ident else {
491 return Err(syn::Error::new(field.span(), "a field must be named"));
492 };
493 let attrs = read(&field.attrs, Position::Field)?;
494 if attrs.flatten
495 && (attrs.rename.is_some()
496 || attrs.default
497 || !attrs.constraints.is_empty()
498 || attrs.constant.is_some())
499 {
500 return Err(syn::Error::new(
501 ident.span(),
502 "a flattened field takes no other attribute: its fields are the object's own",
503 ));
504 }
505 let key = attrs
506 .rename
507 .clone()
508 .unwrap_or_else(|| field_name(&name_of(ident), rename_all));
509 found.push(Member {
510 ident: ident.clone(),
511 key,
512 ty: field.ty.clone(),
513 attrs,
514 description: description(&field.attrs),
515 span: field.span(),
516 });
517 }
518 let mut keys = BTreeSet::new();
519 for member in &found {
520 if !member.attrs.flatten && !keys.insert(member.key.clone()) {
521 return Err(syn::Error::new(
522 member.ident.span(),
523 format!("the key \"{}\" is used by two fields", member.key),
524 ));
525 }
526 }
527 Ok(found)
528}
529
530fn constraint_assertions(
532 ty: &Type,
533 constraints: &[Constrained],
534 constant: Option<&Located>,
535) -> TokenStream2 {
536 let mut assertions = Vec::new();
537 for constrained in constraints {
538 let classes: Vec<Ident> = constrained
539 .spec
540 .classes()
541 .iter()
542 .map(|class| Ident::new(class, constrained.span))
543 .collect();
544 let message = format!(
545 "#[shape({})] applies only to a type whose shape is {}",
546 constrained.spec.name(),
547 constrained.spec.classes().join(" or ").to_lowercase()
548 );
549 assertions.push(quote_spanned! { constrained.span =>
550 const _: () = ::core::assert!(
551 ::trilean_json_shape::private::class_in(<#ty as ::trilean_json_shape::Shape>::CLASS, &[#(::trilean_json_shape::Class::#classes),*]),
552 #message
553 );
554 });
555 }
556 if let Some((span, constant)) = constant {
557 let (class, message) = match constant {
558 Constant::Bool(_) => (
559 "Bool",
560 "#[shape(constant = true or false)] applies only to a boolean",
561 ),
562 Constant::Text(_) => (
563 "String",
564 "#[shape(constant = \"text\")] applies only to a string",
565 ),
566 };
567 let class = Ident::new(class, *span);
568 assertions.push(quote_spanned! { *span =>
569 const _: () = ::core::assert!(
570 ::trilean_json_shape::private::class_in(<#ty as ::trilean_json_shape::Shape>::CLASS, &[::trilean_json_shape::Class::#class]),
571 #message
572 );
573 });
574 }
575 quote! { #(#assertions)* }
576}
577
578fn key_parts(head: Option<&str>, members: &[Member]) -> Vec<TokenStream2> {
581 let own: Vec<&String> = members
582 .iter()
583 .filter(|member| !member.attrs.flatten)
584 .map(|member| &member.key)
585 .collect();
586 let mut parts = Vec::new();
587 if let Some(tag) = head {
588 parts.push(quote! { (&[#tag] as &[&str]) });
589 }
590 parts.push(quote! { (&[#(#own),*] as &[&str]) });
591 for member in members.iter().filter(|member| member.attrs.flatten) {
592 let ty = &member.ty;
593 parts.push(quote! { <#ty as ::trilean_json_shape::Shape>::KEYS });
594 }
595 parts
596}
597
598fn member_assertions(members: &[Member]) -> TokenStream2 {
599 let assertions = members.iter().map(|member| {
600 let ty = &member.ty;
601 if member.attrs.flatten {
602 let span = member.span;
603 quote_spanned! { span =>
604 const _: () = ::core::assert!(
605 <#ty as ::trilean_json_shape::Shape>::IS_OBJECT || <#ty as ::trilean_json_shape::Shape>::CATCH_ALL,
606 "a flattened field must be a struct that derives Shape, or a Map or OpenObject that takes the other members"
607 );
608 }
609 } else {
610 constraint_assertions(
611 ty,
612 &member.attrs.constraints,
613 member.attrs.constant.as_ref(),
614 )
615 }
616 });
617 quote! { #(#assertions)* }
618}
619
620fn unique_keys_assertion(head: Option<&str>, members: &[Member], span: Span) -> TokenStream2 {
621 let parts = key_parts(head, members);
622 quote_spanned! { span =>
623 const _: () = ::core::assert!(
624 ::trilean_json_shape::private::keys_unique(&[#(#parts),*]),
625 "a property key is used twice, counting the tag and the flattened fields"
626 );
627 }
628}
629
630fn fields_definition(members: &[Member]) -> TokenStream2 {
632 let steps = members.iter().map(|member| {
633 let ty = &member.ty;
634 let key = &member.key;
635 if member.attrs.flatten {
636 return quote! {
637 if <#ty as ::trilean_json_shape::Shape>::CATCH_ALL {
638 __additional = <#ty as ::trilean_json_shape::Shape>::catch_all_shape().map(::std::boxed::Box::new);
639 } else {
640 match <#ty as ::trilean_json_shape::Shape>::definition().kind {
641 ::trilean_json_shape::Kind::Object(__inner) => {
642 __fields.extend(__inner.fields);
643 __dependent.extend(__inner.dependent_required);
644 }
645 _ => ::core::unreachable!("a flattened field is checked to be a struct at compile time"),
646 }
647 }
648 };
649 }
650 let constraints: Vec<TokenStream2> = member
651 .attrs
652 .constraints
653 .iter()
654 .map(|constrained| constrained.spec.tokens())
655 .collect();
656 let described = member
657 .description
658 .as_ref()
659 .map(|text| quote! { __shape = __shape.described(#text); });
660 let constant = match &member.attrs.constant {
661 Some((_, Constant::Bool(flag))) => Some(quote! { __shape = __shape.constant_bool(#flag); }),
662 Some((_, Constant::Text(text))) => Some(quote! { __shape = __shape.constant_string(#text); }),
663 None => None,
664 };
665 let optional = member.attrs.default;
666 quote! {
667 {
668 let mut __shape = <#ty as ::trilean_json_shape::Shape>::reference();
669 #( __shape = __shape.constrained(#constraints); )*
670 #constant
671 #described
672 __fields.push(::trilean_json_shape::FieldDef {
673 name: #key.to_owned(),
674 shape: __shape,
675 required: !<#ty as ::trilean_json_shape::Shape>::OPTIONAL && !#optional,
676 });
677 }
678 }
679 });
680 quote! { #(#steps)* }
681}
682
683#[derive(Clone, Copy)]
685struct Groups<'a> {
686 together: &'a [(Span, Vec<Ident>)],
687 any_of: &'a [(Span, Vec<Ident>)],
688 one_of: &'a [(Span, Vec<Ident>)],
689}
690
691impl<'a> Groups<'a> {
692 const NONE: Groups<'static> = Groups {
693 together: &[],
694 any_of: &[],
695 one_of: &[],
696 };
697
698 fn of(attrs: &'a Attrs) -> Self {
699 Groups {
700 together: &attrs.together,
701 any_of: &attrs.any_of,
702 one_of: &attrs.one_of,
703 }
704 }
705}
706
707fn group_keys(
709 groups: &[(Span, Vec<Ident>)],
710 what: &str,
711 members: &[Member],
712) -> Result<Vec<Vec<String>>> {
713 let mut found = Vec::new();
714 for (span, names) in groups {
715 let mut keys = Vec::new();
716 for name in names {
717 let Some(member) = members.iter().find(|member| member.ident == *name) else {
718 return Err(syn::Error::new(
719 name.span(),
720 format!("{what} names {name}, which is not a field"),
721 ));
722 };
723 if member.attrs.flatten {
724 return Err(syn::Error::new(
725 name.span(),
726 format!("{what} names {name}, which is flattened"),
727 ));
728 }
729 keys.push(member.key.clone());
730 }
731 if keys.len() < 2 {
732 return Err(syn::Error::new(
733 *span,
734 format!("{what} needs at least two fields"),
735 ));
736 }
737 found.push(keys);
738 }
739 Ok(found)
740}
741
742fn object_definition(
744 strict: bool,
745 min_properties: Option<usize>,
746 groups: Groups<'_>,
747 members: &[Member],
748) -> Result<TokenStream2> {
749 let together_groups = group_keys(groups.together, "together", members)?;
750 let any_of = group_keys(groups.any_of, "any_of", members)?;
751 let one_of = group_keys(groups.one_of, "one_of", members)?;
752 if any_of.len() > 1 || one_of.len() > 1 {
753 return Err(syn::Error::new(
754 Span::call_site(),
755 "any_of and one_of each name one group of fields",
756 ));
757 }
758 let any_of_keys = any_of.into_iter().next().unwrap_or_default();
759 let one_of_keys = one_of.into_iter().next().unwrap_or_default();
760 let minimum = match min_properties {
761 Some(count) => quote! { ::core::option::Option::Some(#count) },
762 None => quote! { ::core::option::Option::None },
763 };
764 let together = together_groups.iter().map(|keys| {
765 let entries = keys.iter().map(|key| {
766 let others: Vec<&String> = keys.iter().filter(|other| *other != key).collect();
767 quote! { __dependent.push((#key.to_owned(), vec![#(#others.to_owned()),*])); }
768 });
769 quote! { #(#entries)* }
770 });
771 Ok(quote! {
774 {
775 #(#together)*
776 ::trilean_json_shape::ObjectDef {
777 fields: __fields,
778 closed: #strict && __additional.is_none(),
779 strips: false,
780 additional: __additional,
781 any_of_keys: ::std::vec![#(#any_of_keys.to_owned()),*],
782 one_of_keys: ::std::vec![#(#one_of_keys.to_owned()),*],
783 min_properties: #minimum,
784 dependent_required: __dependent,
785 }
786 }
787 })
788}
789
790fn member_builds(members: &[Member], tag: Option<&str>) -> Vec<TokenStream2> {
792 let own: Vec<&String> = members
793 .iter()
794 .filter(|member| !member.attrs.flatten)
795 .map(|member| &member.key)
796 .collect();
797 let flattened: Vec<&Type> = members
798 .iter()
799 .filter(|member| member.attrs.flatten)
800 .map(|member| &member.ty)
801 .collect();
802 let tag: Vec<&str> = tag.into_iter().collect();
803 members
804 .iter()
805 .map(|member| {
806 let ident = &member.ident;
807 let ty = &member.ty;
808 let key = &member.key;
809 if member.attrs.flatten {
810 return quote! {
811 #ident: if <#ty as ::trilean_json_shape::Shape>::CATCH_ALL {
812 let mut __known: ::std::vec::Vec<&str> = ::std::vec![#(#tag,)* #(#own,)*];
813 #( __known.extend(<#flattened as ::trilean_json_shape::Shape>::KEYS.iter().copied()); )*
814 <#ty as ::trilean_json_shape::Shape>::build_rest(__value, __path, &__known)?
815 } else {
816 <#ty as ::trilean_json_shape::Shape>::build(__value, __path)?
817 }
818 };
819 }
820 let missing = if member.attrs.default {
821 quote! { ::core::default::Default::default() }
822 } else {
823 quote! {
824 return ::core::result::Result::Err(::trilean_json_shape::Issues::at(
825 __path,
826 ::std::format!("missing the required property {}", #key),
827 ))
828 }
829 };
830 quote! {
831 #ident: match __value.get(#key) {
832 ::core::option::Option::Some(__entry) => {
833 __path.push_key(#key);
834 let __built = <#ty as ::trilean_json_shape::Shape>::build(__entry, __path);
835 __path.pop();
836 __built?
837 }
838 ::core::option::Option::None => match <#ty as ::trilean_json_shape::Shape>::absent() {
839 ::core::option::Option::Some(__absent) => __absent,
840 ::core::option::Option::None => #missing,
841 },
842 }
843 }
844 })
845 .collect()
846}
847
848fn member_registers(members: &[Member]) -> Vec<TokenStream2> {
849 members
850 .iter()
851 .map(|member| {
852 let ty = &member.ty;
853 if member.attrs.flatten {
854 quote! { <#ty as ::trilean_json_shape::Shape>::register_members(__registry); }
855 } else {
856 quote! { <#ty as ::trilean_json_shape::Shape>::register(__registry); }
857 }
858 })
859 .collect()
860}
861
862fn object_shape(
864 strict: bool,
865 min_properties: Option<usize>,
866 groups: Groups<'_>,
867 members: &[Member],
868 doc: Option<&String>,
869 head: Option<TokenStream2>,
870) -> Result<TokenStream2> {
871 let steps = fields_definition(members);
872 let object = object_definition(strict, min_properties, groups, members)?;
873 let described = doc.map(|text| quote! { .described(#text) });
874 Ok(quote! {
875 {
876 let mut __fields: ::std::vec::Vec<::trilean_json_shape::FieldDef> = ::std::vec::Vec::new();
877 let mut __dependent: ::std::vec::Vec<(::std::string::String, ::std::vec::Vec<::std::string::String>)> =
878 ::std::vec::Vec::new();
879 let mut __additional: ::core::option::Option<::std::boxed::Box<::trilean_json_shape::ShapeDef>> =
880 ::core::option::Option::None;
881 #head
882 #steps
883 ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Object(#object)) #described
884 }
885 })
886}
887
888struct Parts {
890 definition: TokenStream2,
891 register_members: TokenStream2,
892 build: TokenStream2,
893 constants: TokenStream2,
894 assertions: TokenStream2,
895}
896
897fn expand(input: &DeriveInput) -> Result<TokenStream2> {
898 if !input.generics.params.is_empty() {
899 return Err(syn::Error::new(
900 input.generics.span(),
901 "trilean_json_shape::Shape does not support generic types",
902 ));
903 }
904 let container = read(&input.attrs, Position::Container)?;
905 let name = &input.ident;
906 let label = container.name.clone().unwrap_or_else(|| name_of(name));
907 let doc = description(&input.attrs);
908 let parts = match &input.data {
909 Data::Struct(data) => {
910 let Fields::Named(fields) = &data.fields else {
911 return Err(syn::Error::new(
912 input.span(),
913 "trilean_json_shape::Shape needs a struct with named fields",
914 ));
915 };
916 if container.tag.is_some() || container.untagged {
917 return Err(syn::Error::new(
918 input.span(),
919 "tag and untagged apply to enums",
920 ));
921 }
922 expand_struct(&container, fields, doc.as_ref(), input.span())?
923 }
924 Data::Enum(data) => expand_enum(
925 &container,
926 doc.as_ref(),
927 name,
928 &data.variants.iter().collect::<Vec<_>>(),
929 )?,
930 Data::Union(_) => {
931 return Err(syn::Error::new(
932 input.span(),
933 "trilean_json_shape::Shape does not support unions",
934 ));
935 }
936 };
937 let Parts {
938 definition,
939 register_members,
940 build,
941 constants,
942 assertions,
943 } = parts;
944 Ok(quote! {
945 #assertions
946
947 impl ::trilean_json_shape::Shape for #name {
948 #constants
949
950 fn reference() -> ::trilean_json_shape::ShapeDef {
951 ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Ref(#label.to_owned()))
952 }
953
954 fn definition() -> ::trilean_json_shape::ShapeDef {
955 #definition
956 }
957
958 fn register(__registry: &mut ::trilean_json_shape::Registry) {
959 if __registry.reserve(
960 #label,
961 ::std::any::TypeId::of::<Self>(),
962 ::std::any::type_name::<Self>(),
963 ) {
964 __registry.define(#label, <Self as ::trilean_json_shape::Shape>::definition());
965 <Self as ::trilean_json_shape::Shape>::register_members(__registry);
966 }
967 }
968
969 fn register_members(__registry: &mut ::trilean_json_shape::Registry) {
970 #register_members
971 }
972
973 fn definitions() -> ::std::borrow::Cow<'static, ::trilean_json_shape::Definitions> {
974 static DEFINITIONS: ::std::sync::OnceLock<::trilean_json_shape::Definitions> = ::std::sync::OnceLock::new();
975 ::std::borrow::Cow::Borrowed(DEFINITIONS.get_or_init(::trilean_json_shape::Definitions::of::<Self>))
976 }
977
978 fn build(
979 __value: &::trilean_json_shape::Value,
980 __path: &mut ::trilean_json_shape::Path,
981 ) -> ::core::result::Result<Self, ::trilean_json_shape::Issues> {
982 #build
983 }
984 }
985
986 impl<'de> ::trilean_json_shape::private::serde::Deserialize<'de> for #name {
987 fn deserialize<D>(__deserializer: D) -> ::core::result::Result<Self, D::Error>
988 where
989 D: ::trilean_json_shape::private::serde::Deserializer<'de>,
990 {
991 let __value = <::trilean_json_shape::Value as ::trilean_json_shape::private::serde::Deserialize>::deserialize(
992 __deserializer,
993 )?;
994 <Self as ::trilean_json_shape::Shape>::from_json(&__value)
995 .map_err(<D::Error as ::trilean_json_shape::private::serde::de::Error>::custom)
996 }
997 }
998 })
999}
1000
1001fn expand_struct(
1002 container: &Attrs,
1003 fields: &FieldsNamed,
1004 doc: Option<&String>,
1005 span: Span,
1006) -> Result<Parts> {
1007 let members = members(fields, container.rename_all)?;
1008 let definition = object_shape(
1009 container.strict,
1010 container.container_min_properties,
1011 Groups::of(container),
1012 &members,
1013 doc,
1014 None,
1015 )?;
1016 let registers = member_registers(&members);
1017 let builds = member_builds(&members, None);
1018 let parts = key_parts(None, &members);
1019 let own = members
1020 .iter()
1021 .filter(|member| !member.attrs.flatten)
1022 .count();
1023 let flattened_lengths: Vec<TokenStream2> = members
1024 .iter()
1025 .filter(|member| member.attrs.flatten)
1026 .map(|member| {
1027 let ty = &member.ty;
1028 quote! { <#ty as ::trilean_json_shape::Shape>::KEYS.len() }
1029 })
1030 .collect();
1031 let mut assertions = vec![
1032 member_assertions(&members),
1033 unique_keys_assertion(None, &members, span),
1034 ];
1035 if container.strict {
1036 for member in members.iter().filter(|member| member.attrs.flatten) {
1037 let ty = &member.ty;
1038 assertions.push(quote_spanned! { member.span =>
1039 const _: () = ::core::assert!(
1040 !<#ty as ::trilean_json_shape::Shape>::CATCH_ALL,
1041 "a flattened Map or OpenObject takes the other members, so the struct cannot also deny unknown fields"
1042 );
1043 });
1044 }
1045 }
1046 assertions.retain(|assertion| !assertion.is_empty());
1047 Ok(Parts {
1048 definition,
1049 register_members: quote! { #(#registers)* },
1050 build: quote! { ::core::result::Result::Ok(Self { #(#builds),* }) },
1051 constants: quote! {
1052 const CLASS: ::trilean_json_shape::Class = ::trilean_json_shape::Class::Named;
1053 const IS_OBJECT: bool = true;
1054 const KEYS: &'static [&'static str] = {
1055 const LENGTH: usize = #own #( + #flattened_lengths )*;
1056 const JOINED: [&'static str; LENGTH] = ::trilean_json_shape::private::concat_keys::<LENGTH>(&[#(#parts),*]);
1057 &JOINED
1058 };
1059 },
1060 assertions: quote! { #(#assertions)* },
1061 })
1062}
1063
1064struct VariantInfo<'a> {
1066 variant: &'a Variant,
1067 key: String,
1068 attrs: Attrs,
1069 description: Option<String>,
1070}
1071
1072fn variant_info<'a>(variant: &'a Variant, rename_all: Option<Case>) -> Result<VariantInfo<'a>> {
1073 let attrs = read(&variant.attrs, Position::Variant)?;
1074 let key = attrs
1075 .rename
1076 .clone()
1077 .unwrap_or_else(|| variant_name(&name_of(&variant.ident), rename_all));
1078 Ok(VariantInfo {
1079 variant,
1080 key,
1081 attrs,
1082 description: description(&variant.attrs),
1083 })
1084}
1085
1086fn newtype(variant: &Variant) -> Result<Option<(&Type, Attrs)>> {
1088 match &variant.fields {
1089 Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
1090 let field = &fields.unnamed[0];
1091 Ok(Some((&field.ty, read(&field.attrs, Position::TupleField)?)))
1092 }
1093 Fields::Unnamed(_) => Err(syn::Error::new(
1094 variant.span(),
1095 "a tuple variant must hold exactly one field",
1096 )),
1097 _ => Ok(None),
1098 }
1099}
1100
1101fn newtype_constraints(
1103 info: &VariantInfo<'_>,
1104 field: &Attrs,
1105) -> Result<(Vec<Constrained>, Option<Located>)> {
1106 let mut constraints = info.attrs.constraints.clone();
1107 for constrained in &field.constraints {
1108 if constraints
1109 .iter()
1110 .any(|known| known.spec.name() == constrained.spec.name())
1111 {
1112 return Err(syn::Error::new(
1113 constrained.span,
1114 format!("`{}` is given twice", constrained.spec.name()),
1115 ));
1116 }
1117 constraints.push(constrained.clone());
1118 }
1119 if info.attrs.constant.is_some() && field.constant.is_some() {
1120 return Err(syn::Error::new(
1121 info.variant.span(),
1122 "`constant` is given twice",
1123 ));
1124 }
1125 Ok((
1126 constraints,
1127 info.attrs
1128 .constant
1129 .clone()
1130 .or_else(|| field.constant.clone()),
1131 ))
1132}
1133
1134fn tagged_variant(
1136 info: &VariantInfo<'_>,
1137 tag: &str,
1138 strict: bool,
1139 parts: &mut VariantParts,
1140) -> Result<TokenStream2> {
1141 let span = info.variant.span();
1142 let info_key = &info.key;
1143 let tag_field = quote! {
1144 __fields.push(::trilean_json_shape::FieldDef {
1145 name: #tag.to_owned(),
1146 shape: ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::ConstString(#info_key.to_owned())),
1147 required: true,
1148 });
1149 };
1150 let doc = info.description.as_ref();
1151 match &info.variant.fields {
1152 Fields::Unit => {
1153 let described = doc.map(|text| quote! { .described(#text) });
1154 Ok(quote! {
1155 {
1156 let mut __fields: ::std::vec::Vec<::trilean_json_shape::FieldDef> = ::std::vec::Vec::new();
1157 #tag_field
1158 ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Object(::trilean_json_shape::ObjectDef {
1159 fields: __fields,
1160 closed: #strict,
1161 strips: false,
1162 additional: ::core::option::Option::None,
1163 any_of_keys: ::std::vec::Vec::new(),
1164 one_of_keys: ::std::vec::Vec::new(),
1165 min_properties: ::core::option::Option::None,
1166 dependent_required: ::std::vec::Vec::new(),
1167 })) #described
1168 }
1169 })
1170 }
1171 Fields::Named(fields) => {
1172 let members = members(fields, None)?;
1173 parts.assertions.push(member_assertions(&members));
1174 parts
1175 .assertions
1176 .push(unique_keys_assertion(Some(tag), &members, span));
1177 parts.registers.extend(member_registers(&members));
1178 object_shape(strict, None, Groups::NONE, &members, doc, Some(tag_field))
1179 }
1180 Fields::Unnamed(_) => {
1181 let Some((ty, field)) = newtype(info.variant)? else {
1182 return Err(syn::Error::new(span, "unreachable"));
1183 };
1184 if !info.attrs.constraints.is_empty()
1185 || info.attrs.constant.is_some()
1186 || !field.constraints.is_empty()
1187 || field.constant.is_some()
1188 {
1189 return Err(syn::Error::new(
1190 span,
1191 "no constraint applies to a newtype variant of a tagged enum: its struct carries its own",
1192 ));
1193 }
1194 parts.assertions.push(quote_spanned! { span =>
1195 const _: () = ::core::assert!(
1196 <#ty as ::trilean_json_shape::Shape>::IS_OBJECT,
1197 "a newtype variant of a tagged enum must hold a struct that derives Shape"
1198 );
1199 const _: () = ::core::assert!(
1200 ::trilean_json_shape::private::keys_unique(&[(&[#tag] as &[&str]), <#ty as ::trilean_json_shape::Shape>::KEYS]),
1201 "a property key is used twice, counting the tag and the flattened fields"
1202 );
1203 });
1204 parts.registers.push(
1205 quote! { <#ty as ::trilean_json_shape::Shape>::register_members(__registry); },
1206 );
1207 let described = doc.map(|text| quote! { __shape = __shape.described(#text); });
1208 Ok(quote! {
1209 {
1210 let mut __shape = <#ty as ::trilean_json_shape::Shape>::definition();
1211 match &mut __shape.kind {
1212 ::trilean_json_shape::Kind::Object(__object) => {
1213 __object.closed = __object.closed || #strict;
1214 let __rest = ::std::mem::take(&mut __object.fields);
1215 let mut __fields: ::std::vec::Vec<::trilean_json_shape::FieldDef> = ::std::vec::Vec::new();
1216 #tag_field
1217 __fields.extend(__rest);
1218 __object.fields = __fields;
1219 }
1220 _ => ::core::unreachable!("a newtype variant is checked to hold a struct at compile time"),
1221 }
1222 #described
1223 __shape
1224 }
1225 })
1226 }
1227 }
1228}
1229
1230#[derive(Default)]
1231struct VariantParts {
1232 registers: Vec<TokenStream2>,
1233 assertions: Vec<TokenStream2>,
1234}
1235
1236fn expand_enum(
1238 container: &Attrs,
1239 doc: Option<&String>,
1240 name: &Ident,
1241 variants: &[&Variant],
1242) -> Result<Parts> {
1243 let described = doc.map(|text| quote! { .described(#text) });
1244 if !container.together.is_empty()
1245 || !container.any_of.is_empty()
1246 || !container.one_of.is_empty()
1247 || container.container_min_properties.is_some()
1248 {
1249 return Err(syn::Error::new(
1250 name.span(),
1251 "together, any_of, one_of and min_properties describe one object, so they apply to structs",
1252 ));
1253 }
1254 if variants.is_empty() {
1255 return Err(syn::Error::new(
1256 name.span(),
1257 "an enum needs at least one variant",
1258 ));
1259 }
1260 if container.tag.is_some() && container.untagged {
1261 return Err(syn::Error::new(
1262 name.span(),
1263 "tag and untagged cannot be combined",
1264 ));
1265 }
1266 let mut infos = Vec::new();
1267 let mut keys = BTreeSet::new();
1268 for variant in variants {
1269 let info = variant_info(variant, container.rename_all)?;
1270 if !keys.insert(info.key.clone()) {
1271 return Err(syn::Error::new(
1272 variant.span(),
1273 format!("the variant key \"{}\" is used twice", info.key),
1274 ));
1275 }
1276 infos.push(info);
1277 }
1278 let constants = quote! {
1279 const CLASS: ::trilean_json_shape::Class = ::trilean_json_shape::Class::Named;
1280 };
1281 let all_unit = variants
1282 .iter()
1283 .all(|variant| matches!(variant.fields, Fields::Unit));
1284 if all_unit && container.tag.is_none() && !container.untagged {
1285 for info in &infos {
1286 if !info.attrs.constraints.is_empty() || info.attrs.constant.is_some() {
1287 return Err(syn::Error::new(
1288 info.variant.span(),
1289 "no constraint applies to a unit variant",
1290 ));
1291 }
1292 }
1293 let idents: Vec<&Ident> = variants.iter().map(|variant| &variant.ident).collect();
1294 let texts: Vec<&String> = infos.iter().map(|info| &info.key).collect();
1295 return Ok(Parts {
1296 definition: quote! {
1297 ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Enum(::std::vec![#(#texts.to_owned()),*])) #described
1298 },
1299 register_members: quote! {},
1300 build: quote! {
1301 match __value.as_str() {
1302 #( ::core::option::Option::Some(#texts) => ::core::result::Result::Ok(Self::#idents), )*
1303 _ => ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "not one of the variants")),
1304 }
1305 },
1306 constants,
1307 assertions: quote! {},
1308 });
1309 }
1310 let mut parts = VariantParts::default();
1311 if let Some(tag) = &container.tag {
1312 let mut definitions = Vec::new();
1313 let mut arms = Vec::new();
1314 for info in &infos {
1315 if !info.attrs.constraints.is_empty() || info.attrs.constant.is_some() {
1316 return Err(syn::Error::new(
1317 info.variant.span(),
1318 "#[shape] constraints on a variant apply only to a newtype variant of an untagged enum",
1319 ));
1320 }
1321 definitions.push(tagged_variant(info, tag, container.strict, &mut parts)?);
1322 let (ident, key) = (&info.variant.ident, &info.key);
1323 match &info.variant.fields {
1324 Fields::Unit => {
1325 arms.push(quote! { #key => ::core::result::Result::Ok(Self::#ident), })
1326 }
1327 Fields::Named(fields) => {
1328 let members = members(fields, None)?;
1329 let builds = member_builds(&members, Some(tag));
1330 arms.push(quote! { #key => ::core::result::Result::Ok(Self::#ident { #(#builds),* }), });
1331 }
1332 Fields::Unnamed(_) => {
1333 let Some((ty, _)) = newtype(info.variant)? else {
1334 return Err(syn::Error::new(info.variant.span(), "unreachable"));
1335 };
1336 arms.push(quote! {
1337 #key => <#ty as ::trilean_json_shape::Shape>::build(__value, __path).map(Self::#ident),
1338 });
1339 }
1340 }
1341 }
1342 let keys: Vec<&String> = infos.iter().map(|info| &info.key).collect();
1343 let registers = &parts.registers;
1344 let assertions = &parts.assertions;
1345 return Ok(Parts {
1346 definition: quote! {
1347 ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Tagged {
1348 tag: #tag.to_owned(),
1349 variants: ::std::vec![#( (#keys.to_owned(), #definitions) ),*],
1350 }) #described
1351 },
1352 register_members: quote! { #(#registers)* },
1353 build: quote! {
1354 let ::core::option::Option::Some(__kind) = __value.get(#tag).and_then(::trilean_json_shape::Value::as_str) else {
1355 return ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "expected a string naming the kind"));
1356 };
1357 match __kind {
1358 #(#arms)*
1359 _ => ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "not a known kind")),
1360 }
1361 },
1362 constants,
1363 assertions: quote! { #(#assertions)* },
1364 });
1365 }
1366 if container.untagged {
1367 let units = variants
1368 .iter()
1369 .filter(|variant| matches!(variant.fields, Fields::Unit))
1370 .count();
1371 if units > 1 {
1372 return Err(syn::Error::new(
1373 name.span(),
1374 "an untagged enum can have one unit variant, which is null: with two, null matches both",
1375 ));
1376 }
1377 let mut alternatives = Vec::new();
1378 let mut arms = Vec::new();
1379 for (position, info) in infos.iter().enumerate() {
1380 let (ident, doc) = (&info.variant.ident, info.description.as_ref());
1381 let described = doc.map(|text| quote! { .described(#text) });
1382 match &info.variant.fields {
1383 Fields::Unit => {
1384 if !info.attrs.constraints.is_empty() || info.attrs.constant.is_some() {
1385 return Err(syn::Error::new(
1386 info.variant.span(),
1387 "no constraint applies to a unit variant",
1388 ));
1389 }
1390 alternatives.push(
1391 quote! { ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::Null) #described },
1392 );
1393 arms.push(quote! { #position => ::core::result::Result::Ok(Self::#ident), });
1394 }
1395 Fields::Named(fields) => {
1396 if !info.attrs.constraints.is_empty() || info.attrs.constant.is_some() {
1397 return Err(syn::Error::new(
1398 info.variant.span(),
1399 "#[shape] constraints on a variant apply only to a newtype variant",
1400 ));
1401 }
1402 let members = members(fields, None)?;
1403 parts.assertions.push(member_assertions(&members));
1404 parts.assertions.push(unique_keys_assertion(
1405 None,
1406 &members,
1407 info.variant.span(),
1408 ));
1409 parts.registers.extend(member_registers(&members));
1410 alternatives.push(object_shape(
1411 container.strict,
1412 None,
1413 Groups::NONE,
1414 &members,
1415 doc,
1416 None,
1417 )?);
1418 let builds = member_builds(&members, None);
1419 arms.push(quote! { #position => ::core::result::Result::Ok(Self::#ident { #(#builds),* }), });
1420 }
1421 Fields::Unnamed(_) => {
1422 let Some((ty, field)) = newtype(info.variant)? else {
1423 return Err(syn::Error::new(info.variant.span(), "unreachable"));
1424 };
1425 let (constraints, constant) = newtype_constraints(info, &field)?;
1426 parts.assertions.push(constraint_assertions(
1427 ty,
1428 &constraints,
1429 constant.as_ref(),
1430 ));
1431 let tokens: Vec<TokenStream2> = constraints
1432 .iter()
1433 .map(|constrained| constrained.spec.tokens())
1434 .collect();
1435 let constant = match constant {
1436 Some((_, Constant::Bool(flag))) => {
1437 Some(quote! { __shape = __shape.constant_bool(#flag); })
1438 }
1439 Some((_, Constant::Text(text))) => {
1440 Some(quote! { __shape = __shape.constant_string(#text); })
1441 }
1442 None => None,
1443 };
1444 alternatives.push(quote! {
1445 {
1446 let mut __shape = <#ty as ::trilean_json_shape::Shape>::reference();
1447 #( __shape = __shape.constrained(#tokens); )*
1448 #constant
1449 __shape #described
1450 }
1451 });
1452 parts.registers.push(
1453 quote! { <#ty as ::trilean_json_shape::Shape>::register(__registry); },
1454 );
1455 arms.push(quote! {
1456 #position => <#ty as ::trilean_json_shape::Shape>::build(__value, __path).map(Self::#ident),
1457 });
1458 }
1459 }
1460 }
1461 let registers = &parts.registers;
1462 let assertions = &parts.assertions;
1463 return Ok(Parts {
1464 definition: quote! {
1465 ::trilean_json_shape::ShapeDef::new(::trilean_json_shape::Kind::OneOf(::std::vec![#(#alternatives),*])) #described
1466 },
1467 register_members: quote! { #(#registers)* },
1468 build: quote! {
1469 static ALTERNATIVES: ::std::sync::OnceLock<::std::vec::Vec<::trilean_json_shape::ShapeDef>> =
1470 ::std::sync::OnceLock::new();
1471 let __alternatives = ALTERNATIVES.get_or_init(|| match <Self as ::trilean_json_shape::Shape>::definition().kind {
1472 ::trilean_json_shape::Kind::OneOf(__alternatives) => __alternatives,
1473 _ => ::core::unreachable!("an untagged enum is a union"),
1474 });
1475 let __definitions = <Self as ::trilean_json_shape::Shape>::definitions();
1476 for (__index, __alternative) in __alternatives.iter().enumerate() {
1477 if ::trilean_json_shape::private::decide(__path, &__definitions, __alternative, __value) {
1478 return match __index {
1479 #(#arms)*
1480 _ => ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "no such alternative")),
1481 };
1482 }
1483 }
1484 ::core::result::Result::Err(::trilean_json_shape::Issues::at(__path, "matches no alternative"))
1485 },
1486 constants,
1487 assertions: quote! { #(#assertions)* },
1488 });
1489 }
1490 Err(syn::Error::new(
1491 name.span(),
1492 "an enum with data needs #[serde(tag = \"...\")] or #[serde(untagged)]; trilean_json_shape::Shape does not support externally tagged enums",
1493 ))
1494}
1495
1496#[cfg(test)]
1497mod tests {
1498 use syn::DeriveInput;
1499
1500 use super::{Case, expand, field_name, variant_name};
1501
1502 fn parse(source: &str) -> DeriveInput {
1503 syn::parse_str(source).unwrap_or_else(|error| panic!("{source}: {error}"))
1504 }
1505
1506 fn refusal(source: &str) -> String {
1507 match expand(&parse(source)) {
1508 Ok(_) => panic!("{source} was accepted"),
1509 Err(error) => error.to_string(),
1510 }
1511 }
1512
1513 #[test]
1514 fn every_position_refuses_what_it_does_not_read() {
1515 let cases = [
1516 (
1518 "#[shape(bogus)] struct A { a: u8 }",
1519 "the `bogus` attribute is not supported",
1520 ),
1521 (
1522 "#[shape(min = 1)] struct A { a: u8 }",
1523 "`min` does not apply to a struct or enum",
1524 ),
1525 (
1526 "#[serde(rename = \"X\")] struct A { a: u8 }",
1527 "`rename` does not apply to a struct or enum",
1528 ),
1529 (
1530 "#[serde(alias = \"X\")] struct A { a: u8 }",
1531 "the serde attribute `alias` is not supported",
1532 ),
1533 (
1534 "#[serde(rename_all = \"weird\")] struct A { a: u8 }",
1535 "rename_all = \"weird\" is not supported",
1536 ),
1537 (
1538 "#[serde(deny_unknown_fields, deny_unknown_fields)] struct A { a: u8 }",
1539 "`deny_unknown_fields` is given twice",
1540 ),
1541 (
1542 "#[serde(tag = \"k\")] struct A { a: u8 }",
1543 "tag and untagged apply to enums",
1544 ),
1545 (
1546 "#[shape(together(a))] struct A { a: u8 }",
1547 "together needs at least two fields",
1548 ),
1549 (
1550 "#[shape(together(a, z))] struct A { a: u8 }",
1551 "together names z, which is not a field",
1552 ),
1553 (
1554 "#[shape(together(a, b))] enum E { A { a: u8, b: u8 } }",
1555 "apply to structs",
1556 ),
1557 (
1558 "#[shape(any_of(a, b))] enum E { A { a: u8, b: u8 } }",
1559 "apply to structs",
1560 ),
1561 (
1562 "#[shape(any_of(a))] struct A { a: u8 }",
1563 "any_of needs at least two fields",
1564 ),
1565 (
1566 "#[shape(one_of(a, z))] struct A { a: u8 }",
1567 "one_of names z, which is not a field",
1568 ),
1569 (
1570 "#[shape(any_of(a, b), any_of(a, b))] struct A { a: u8, b: u8 }",
1571 "any_of and one_of each name one group of fields",
1572 ),
1573 (
1574 "#[shape(any_of(a, b))] struct A { a: u8, #[serde(flatten)] b: B }",
1575 "any_of names b, which is flattened",
1576 ),
1577 (
1578 "struct A { #[shape(exclusive_min = 1, exclusive_min = 2)] a: u8 }",
1579 "`exclusive_min` is given twice",
1580 ),
1581 (
1582 "struct A { #[shape(exclusive_min = \"x\")] a: u8 }",
1583 "expected a number",
1584 ),
1585 (
1586 "#[shape(one_of(a, z))] struct A { a: u8 }",
1587 "one_of names z, which is not a field",
1588 ),
1589 (
1590 "#[shape(any_of(a, b), any_of(a, b))] struct A { a: u8, b: u8 }",
1591 "any_of and one_of each name one group of fields",
1592 ),
1593 (
1594 "#[shape(any_of(a, b))] struct A { a: u8, #[serde(flatten)] b: B }",
1595 "any_of names b, which is flattened",
1596 ),
1597 (
1598 "struct A { #[shape(exclusive_min = 1, exclusive_min = 2)] a: u8 }",
1599 "`exclusive_min` is given twice",
1600 ),
1601 (
1602 "struct A { #[shape(exclusive_min = \"x\")] a: u8 }",
1603 "expected a number",
1604 ),
1605 (
1607 "struct A { #[shape(strict)] a: u8 }",
1608 "`strict` does not apply to a named field",
1609 ),
1610 (
1611 "struct A { #[serde(tag = \"x\")] a: u8 }",
1612 "`tag` does not apply to a named field",
1613 ),
1614 (
1615 "struct A { #[serde(alias = \"x\")] a: u8 }",
1616 "the serde attribute `alias` is not supported",
1617 ),
1618 (
1619 "struct A { #[serde(default = \"f\")] a: u8 }",
1620 "default = \"path\" is not supported",
1621 ),
1622 (
1623 "struct A { #[shape(min = 1, min = 2)] a: u8 }",
1624 "`min` is given twice",
1625 ),
1626 (
1627 "struct A { #[shape(constant = true)] #[shape(constant = false)] a: bool }",
1628 "`constant` is given twice",
1629 ),
1630 (
1631 "struct A { #[serde(rename = \"a\", rename = \"b\")] a: u8 }",
1632 "`rename` is given twice",
1633 ),
1634 (
1635 "struct A { #[shape(pattern = \"a{2}\")] a: String }",
1636 "is not supported",
1637 ),
1638 (
1639 "struct A { #[shape(property_names = \"(\")] a: u8 }",
1640 "a group is not closed",
1641 ),
1642 (
1643 "struct A { #[shape(constant = 1)] a: u8 }",
1644 "constant takes a boolean or a string",
1645 ),
1646 (
1647 "struct A { #[shape(min = \"x\")] a: u8 }",
1648 "expected a number",
1649 ),
1650 (
1651 "struct A { #[shape(zzz)] a: u8 }",
1652 "the `zzz` attribute is not supported",
1653 ),
1654 (
1655 "struct A { #[serde(flatten, rename = \"x\")] a: B }",
1656 "takes no other attribute",
1657 ),
1658 (
1659 "struct A { a: u8, #[serde(rename = \"a\")] b: u8 }",
1660 "the key \"a\" is used by two fields",
1661 ),
1662 (
1664 "#[serde(untagged)] enum E { #[shape(bogus_typo)] U, V { a: u8 } }",
1665 "the `bogus_typo` attribute is not supported",
1666 ),
1667 (
1668 "#[serde(untagged)] enum E { #[serde(default)] U, V { a: u8 } }",
1669 "`default` does not apply to a variant",
1670 ),
1671 (
1672 "#[serde(untagged)] enum E { #[shape(min_properties = 5)] N { a: u8 }, M(String) }",
1673 "apply only to a newtype variant",
1674 ),
1675 (
1676 "#[serde(untagged)] enum E { #[shape(min_length = 1)] U, V { a: u8 } }",
1677 "no constraint applies to a unit variant",
1678 ),
1679 (
1680 "#[serde(tag = \"k\")] enum E { #[shape(min_items = 1)] A { a: u8 } }",
1681 "apply only to a newtype variant of an untagged enum",
1682 ),
1683 (
1684 "enum E { A, #[serde(rename = \"A\")] B }",
1685 "the variant key \"A\" is used twice",
1686 ),
1687 (
1688 "#[serde(tag = \"k\", untagged)] enum E { A }",
1689 "tag and untagged cannot be combined",
1690 ),
1691 ("#[serde(untagged)] enum E { A, B }", "one unit variant"),
1692 ("enum E { A(u8), B }", "externally tagged"),
1693 ("enum E {}", "at least one variant"),
1694 (
1696 "#[serde(untagged)] enum E { One(#[serde(flatten)] String) }",
1697 "`flatten` does not apply to the field of a tuple variant",
1698 ),
1699 (
1700 "#[serde(untagged)] enum E { One(#[shape(zzz)] String) }",
1701 "the `zzz` attribute is not supported",
1702 ),
1703 (
1704 "#[serde(untagged)] enum E { #[shape(min_length = 1)] One(#[shape(min_length = 2)] String) }",
1705 "`min_length` is given twice",
1706 ),
1707 (
1708 "#[serde(untagged)] enum E { One(u8, u8) }",
1709 "exactly one field",
1710 ),
1711 (
1712 "#[serde(tag = \"k\")] enum E { A(#[shape(min = 1)] B) }",
1713 "no constraint applies to a newtype variant of a tagged enum",
1714 ),
1715 ("struct A<T> { a: T }", "does not support generic types"),
1717 ("struct A(u8);", "needs a struct with named fields"),
1718 ("union A { a: u8 }", "does not support unions"),
1719 ];
1720 for (source, expected) in cases {
1721 let message = refusal(source);
1722 assert!(
1723 message.contains(expected),
1724 "{source}: {message:?} lacks {expected:?}"
1725 );
1726 }
1727 }
1728
1729 #[test]
1730 fn what_the_type_system_decides_is_asserted_in_the_expansion() {
1731 let wrong_kind = expand(&parse("struct A { #[shape(min = 1)] a: String }"))
1732 .expect("the kind is checked by the compiler")
1733 .to_string();
1734 assert!(wrong_kind.contains("class_in"), "{wrong_kind}");
1735 assert!(
1736 wrong_kind.contains("Integer") && wrong_kind.contains("Number"),
1737 "{wrong_kind}"
1738 );
1739 let flattened = expand(&parse("struct A { #[serde(flatten)] a: B }"))
1740 .expect("the type is checked by the compiler")
1741 .to_string();
1742 assert!(flattened.contains("IS_OBJECT"), "{flattened}");
1743 let tagged = expand(&parse("#[serde(tag = \"k\")] enum E { A(B) }"))
1744 .expect("the type is checked by the compiler")
1745 .to_string();
1746 assert!(
1747 tagged.contains("IS_OBJECT") && tagged.contains("keys_unique"),
1748 "{tagged}"
1749 );
1750 let constant = expand(&parse("struct A { #[shape(constant = \"x\")] a: u8 }"))
1751 .expect("the kind is checked by the compiler")
1752 .to_string();
1753 assert!(
1754 constant.contains("class_in") && constant.contains("String"),
1755 "{constant}"
1756 );
1757 }
1758
1759 #[test]
1760 fn variant_names_follow_serde() {
1761 let table = [
1762 ("HTTPServer", Case::Snake, "h_t_t_p_server"),
1763 ("HTTPServer", Case::Kebab, "h-t-t-p-server"),
1764 ("HTTPServer", Case::ScreamingSnake, "H_T_T_P_SERVER"),
1765 ("HTTPServer", Case::ScreamingKebab, "H-T-T-P-SERVER"),
1766 ("HTTPServer", Case::Camel, "hTTPServer"),
1767 ("HTTPServer", Case::Lower, "httpserver"),
1768 ("HTTPServer", Case::Upper, "HTTPSERVER"),
1769 ("HTTPServer", Case::Pascal, "HTTPServer"),
1770 ("Utf8Bom", Case::Snake, "utf8_bom"),
1771 ("Utf8Bom", Case::Kebab, "utf8-bom"),
1772 ("A", Case::Snake, "a"),
1773 ("RegexParse", Case::Kebab, "regex-parse"),
1774 ("RegexParse", Case::Camel, "regexParse"),
1775 ("V2Api", Case::Snake, "v2_api"),
1776 ];
1777 for (name, case, expected) in table {
1778 assert_eq!(
1779 variant_name(name, Some(case)),
1780 expected,
1781 "{name} as {case:?}"
1782 );
1783 }
1784 assert_eq!(variant_name("RegexParse", None), "RegexParse");
1785 }
1786
1787 #[test]
1788 fn field_names_follow_serde() {
1789 let table = [
1790 ("code_unit", Case::Camel, "codeUnit"),
1791 ("code_unit", Case::Pascal, "CodeUnit"),
1792 ("code_unit", Case::Kebab, "code-unit"),
1793 ("code_unit", Case::ScreamingSnake, "CODE_UNIT"),
1794 ("code_unit", Case::ScreamingKebab, "CODE-UNIT"),
1795 ("code_unit", Case::Upper, "CODE_UNIT"),
1796 ("code_unit", Case::Lower, "code_unit"),
1797 ("Mixed_Case", Case::Lower, "Mixed_Case"),
1798 ("Mixed_Case", Case::Snake, "Mixed_Case"),
1799 ("code_unit", Case::Snake, "code_unit"),
1800 ("x_1_y", Case::Pascal, "X1Y"),
1801 ("x_1_y", Case::Camel, "x1Y"),
1802 ("_leading", Case::Pascal, "Leading"),
1803 ("_leading", Case::Camel, "leading"),
1804 ("trailing_", Case::Pascal, "Trailing"),
1805 ("a__b", Case::Pascal, "AB"),
1806 ("a__b", Case::Kebab, "a--b"),
1807 ("http_server", Case::Camel, "httpServer"),
1808 ];
1809 for (name, case, expected) in table {
1810 assert_eq!(field_name(name, Some(case)), expected, "{name} as {case:?}");
1811 }
1812 assert_eq!(field_name("code_unit", None), "code_unit");
1813 }
1814}