git.delta.rocks / jrsonnet / refs/commits / 86671948a995

difftreelog

feat macro name interning

vtqzklkwYaroslav Bolyukin2026-03-22parent: #795a53d.patch.diff
in: master

9 files changed

modifiedcmds/jrsonnet/Cargo.tomldiffbeforeafterboth
--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -11,6 +11,10 @@
 workspace = true
 
 [features]
+default = [
+    "exp-regex",
+]
+
 experimental = [
     "exp-preserve-order",
     "exp-destruct",
@@ -18,7 +22,6 @@
     "exp-object-iteration",
     "exp-bigint",
     "exp-apply",
-    "exp-regex",
 ]
 # Use mimalloc as allocator
 mimalloc = ["mimallocator"]
modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -5,11 +5,11 @@
 	rc::Rc,
 };
 
-use jrsonnet_gcmodule::{cc_dyn, Cc};
+use jrsonnet_gcmodule::{cc_dyn, Cc, Trace};
 use jrsonnet_interner::IBytes;
 use jrsonnet_parser::{Expr, Spanned};
 
-use crate::{function::NativeFn, Context, Result, Thunk, Val};
+use crate::{function::NativeFn, typed::Typed, Context, Result, Thunk, Val};
 
 mod spec;
 pub use spec::{ArrayLike, *};
@@ -241,3 +241,4 @@
 		self.0.is_cheap()
 	}
 }
+
modifiedcrates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj/mod.rs
+++ b/crates/jrsonnet-evaluator/src/obj/mod.rs
@@ -12,11 +12,12 @@
 use educe::Educe;
 use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{Span, Visibility};
+use jrsonnet_parser::Span;
 use rustc_hash::{FxHashMap, FxHashSet};
 
 mod oop;
 
+pub use jrsonnet_parser::Visibility;
 pub use oop::ObjValueBuilder;
 
 use crate::{
@@ -30,7 +31,7 @@
 };
 
 #[cfg(not(feature = "exp-preserve-order"))]
-mod ordering {
+pub mod ordering {
 	#![allow(
 		// This module works as stub for preserve-order feature
 		clippy::unused_self,
@@ -41,6 +42,9 @@
 	#[derive(Clone, Copy, Default, Debug, Trace)]
 	pub struct FieldIndex(());
 	impl FieldIndex {
+		pub fn absolute(_v: u32) -> Self {
+			Self(())
+		}
 		pub const fn next(self) -> Self {
 			Self(())
 		}
@@ -54,7 +58,7 @@
 }
 
 #[cfg(feature = "exp-preserve-order")]
-mod ordering {
+pub mod ordering {
 	use std::cmp::Reverse;
 
 	use jrsonnet_gcmodule::Trace;
@@ -62,6 +66,9 @@
 	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]
 	pub struct FieldIndex(u32);
 	impl FieldIndex {
+		pub fn absolute(v: u32) -> Self {
+			Self(v)
+		}
 		pub fn next(self) -> Self {
 			Self(self.0 + 1)
 		}
@@ -149,7 +156,7 @@
 	Pending,
 }
 
-type EnumFieldsHandler<'a> =
+pub type EnumFieldsHandler<'a> =
 	dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;
 
 pub enum EnumFields {
modifiedcrates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -21,6 +21,8 @@
 mod inner;
 use inner::Inner;
 
+mod names;
+
 /// Interned string
 ///
 /// Provides O(1) comparsions and hashing, cheap copy, and cheap conversion to [`IBytes`]
addedcrates/jrsonnet-interner/src/names.rsdiffbeforeafterboth

no changes

modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -13,6 +13,11 @@
 	LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,
 };
 
+use self::typed::derive_typed_inner;
+
+mod typed;
+mod names;
+
 fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>
 where
 	Ident: PartialEq<I>,
@@ -435,278 +440,6 @@
 			}
 		};
 	})
-}
-
-#[derive(Default)]
-#[allow(clippy::struct_excessive_bools)]
-struct TypedAttr {
-	rename: Option<String>,
-	aliases: Vec<String>,
-	flatten: bool,
-	/// flatten(ok) strategy for flattened optionals
-	/// field would be None in case of any parsing error (as in serde)
-	flatten_ok: bool,
-	// Should it be `field+:` instead of `field:`
-	add: bool,
-	// Should it be `field::` instead of `field:`
-	hide: bool,
-}
-impl Parse for TypedAttr {
-	fn parse(input: ParseStream) -> syn::Result<Self> {
-		let mut out = Self::default();
-		loop {
-			let lookahead = input.lookahead1();
-			if lookahead.peek(kw::rename) {
-				input.parse::<kw::rename>()?;
-				input.parse::<Token![=]>()?;
-				let name = input.parse::<LitStr>()?;
-				if out.rename.is_some() {
-					return Err(Error::new(
-						name.span(),
-						"rename attribute may only be specified once",
-					));
-				}
-				out.rename = Some(name.value());
-			} else if lookahead.peek(kw::alias) {
-				input.parse::<kw::alias>()?;
-				input.parse::<Token![=]>()?;
-				let alias = input.parse::<LitStr>()?;
-				out.aliases.push(alias.value());
-			} else if lookahead.peek(kw::flatten) {
-				input.parse::<kw::flatten>()?;
-				out.flatten = true;
-				if input.peek(token::Paren) {
-					let content;
-					parenthesized!(content in input);
-					let lookahead = content.lookahead1();
-					if lookahead.peek(kw::ok) {
-						content.parse::<kw::ok>()?;
-						out.flatten_ok = true;
-					} else {
-						return Err(lookahead.error());
-					}
-				}
-			} else if lookahead.peek(kw::add) {
-				input.parse::<kw::add>()?;
-				out.add = true;
-			} else if lookahead.peek(kw::hide) {
-				input.parse::<kw::hide>()?;
-				out.hide = true;
-			} else if input.is_empty() {
-				break;
-			} else {
-				return Err(lookahead.error());
-			}
-			if input.peek(Token![,]) {
-				input.parse::<Token![,]>()?;
-			} else {
-				break;
-			}
-		}
-		Ok(out)
-	}
-}
-
-struct TypedField {
-	attr: TypedAttr,
-	ident: Ident,
-	ty: Type,
-	is_option: bool,
-	is_lazy: bool,
-}
-impl TypedField {
-	fn parse(field: &syn::Field) -> Result<Self> {
-		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();
-		let Some(ident) = field.ident.clone() else {
-			return Err(Error::new(
-				field.span(),
-				"this field should appear in output object, but it has no visible name",
-			));
-		};
-		let (is_option, ty) = extract_type_from_option(&field.ty)?
-			.map_or_else(|| (false, field.ty.clone()), |ty| (true, ty.clone()));
-		if is_option && attr.flatten {
-			if !attr.flatten_ok {
-				return Err(Error::new(
-					field.span(),
-					"strategy should be set when flattening Option",
-				));
-			}
-		} else if attr.flatten_ok {
-			return Err(Error::new(
-				field.span(),
-				"flatten(ok) is only useable on optional fields",
-			));
-		}
-
-		let is_lazy = type_is_path(&ty, "Thunk").is_some();
-
-		Ok(Self {
-			attr,
-			ident,
-			ty,
-			is_option,
-			is_lazy,
-		})
-	}
-	/// None if this field is flattened in jsonnet output
-	fn name(&self) -> Option<String> {
-		if self.attr.flatten {
-			return None;
-		}
-		Some(
-			self.attr
-				.rename
-				.clone()
-				.unwrap_or_else(|| self.ident.to_string()),
-		)
-	}
-
-	fn expand_field(&self) -> Option<TokenStream> {
-		if self.is_option {
-			return None;
-		}
-		let name = self.name()?;
-		let ty = &self.ty;
-		Some(quote! {
-			(#name, <#ty as Typed>::TYPE)
-		})
-	}
-
-	fn expand_parse(&self) -> TokenStream {
-		if self.is_option {
-			self.expand_parse_optional()
-		} else {
-			self.expand_parse_mandatory()
-		}
-	}
-
-	fn expand_parse_optional(&self) -> TokenStream {
-		let ident = &self.ident;
-		let ty = &self.ty;
-
-		// optional flatten is handled in same way as serde
-		if self.attr.flatten {
-			return quote! {
-				#ident: <#ty as TypedObj>::parse(&obj).ok(),
-			};
-		}
-
-		let name = self.name().unwrap();
-		let aliases = &self.attr.aliases;
-
-		quote! {
-			#ident: {
-				let __value = if let Some(__v) = obj.get(#name.into())? {
-					Some(__v)
-				} #(else if let Some(__v) = obj.get(#aliases.into())? {
-					Some(__v)
-				})* else {
-					None
-				};
-
-				__value.map(<#ty as Typed>::from_untyped).transpose()?
-			},
-		}
-	}
-
-	fn expand_parse_mandatory(&self) -> TokenStream {
-		let ident = &self.ident;
-		let ty = &self.ty;
-
-		// optional flatten is handled in same way as serde
-		if self.attr.flatten {
-			return quote! {
-				#ident: <#ty as TypedObj>::parse(&obj)?,
-			};
-		}
-
-		let name = self.name().unwrap();
-		let aliases = &self.attr.aliases;
-
-		let error_text = if aliases.is_empty() {
-			// clippy does not understand name variable usage in quote! macro
-			#[allow(clippy::redundant_clone)]
-			name.clone()
-		} else {
-			format!("{name} (alias {})", aliases.join(", "))
-		};
-
-		quote! {
-			#ident: {
-				let __value = if let Some(__v) = obj.get(#name.into())? {
-					__v
-				} #(else if let Some(__v) = obj.get(#aliases.into())? {
-					__v
-				})* else {
-					return Err(ErrorKind::NoSuchField(#error_text.into(), vec![]).into());
-				};
-
-				<#ty as Typed>::from_untyped(__value)?
-			},
-		}
-	}
-
-	fn expand_serialize(&self) -> TokenStream {
-		let ident = &self.ident;
-		let ty = &self.ty;
-		self.name().map_or_else(
-			|| {
-				if self.is_option {
-					quote! {
-						if let Some(value) = self.#ident {
-							<#ty as TypedObj>::serialize(value, out)?;
-						}
-					}
-				} else {
-					quote! {
-						<#ty as TypedObj>::serialize(self.#ident, out)?;
-					}
-				}
-			},
-			|name| {
-				let hide = if self.attr.hide {
-					quote! {.hide()}
-				} else {
-					quote! {}
-				};
-				let add = if self.attr.add {
-					quote! {.add()}
-				} else {
-					quote! {}
-				};
-				let value = if self.is_lazy {
-					quote! {
-						out.field(#name)
-							#hide
-							#add
-							.try_thunk(<#ty as Typed>::into_lazy_untyped(value))?;
-					}
-				} else {
-					quote! {
-						out.field(#name)
-							#hide
-							#add
-							.try_value(<#ty as Typed>::into_untyped(value)?)?;
-					}
-				};
-				if self.is_option {
-					quote! {
-						if let Some(value) = self.#ident {
-							#value
-						}
-					}
-				} else {
-					quote! {
-						{
-							let value = self.#ident;
-							#value
-						}
-					}
-				}
-			},
-		)
-	}
 }
 
 #[proc_macro_derive(Typed, attributes(typed))]
@@ -717,79 +450,6 @@
 		Ok(v) => v.into(),
 		Err(e) => e.to_compile_error().into(),
 	}
-}
-
-fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {
-	let syn::Data::Struct(data) = &input.data else {
-		return Err(Error::new(input.span(), "only structs supported"));
-	};
-
-	let ident = &input.ident;
-	let fields = data
-		.fields
-		.iter()
-		.map(TypedField::parse)
-		.collect::<Result<Vec<_>>>()?;
-
-	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
-
-	let typed = {
-		let fields = fields
-			.iter()
-			.filter_map(TypedField::expand_field)
-			.collect::<Vec<_>>();
-		quote! {
-			impl #impl_generics Typed for #ident #ty_generics #where_clause {
-				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[
-					#(#fields,)*
-				]);
-
-				fn from_untyped(value: Val) -> JrResult<Self> {
-					let obj = value.as_obj().expect("shape is correct");
-					Self::parse(&obj)
-				}
-
-				fn into_untyped(value: Self) -> JrResult<Val> {
-					let mut out = ObjValueBuilder::new();
-					value.serialize(&mut out)?;
-					Ok(Val::Obj(out.build()))
-				}
-
-			}
-		}
-	};
-
-	let fields_parse = fields.iter().map(TypedField::expand_parse);
-	let fields_serialize = fields
-		.iter()
-		.map(TypedField::expand_serialize)
-		.collect::<Vec<_>>();
-
-	Ok(quote! {
-		const _: () = {
-			use ::jrsonnet_evaluator::{
-				typed::{ComplexValType, Typed, TypedObj, CheckType},
-				Val, State,
-				error::{ErrorKind, Result as JrResult},
-				ObjValueBuilder, ObjValue,
-			};
-
-			#typed
-
-			impl #impl_generics TypedObj for #ident #ty_generics #where_clause {
-				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {
-					#(#fields_serialize)*
-
-					Ok(())
-				}
-				fn parse(obj: &ObjValue) -> JrResult<Self> {
-					Ok(Self {
-						#(#fields_parse)*
-					})
-				}
-			}
-		};
-	})
 }
 
 struct FormatInput {
addedcrates/jrsonnet-macros/src/names.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-macros/src/names.rs
@@ -0,0 +1,32 @@
+use proc_macro2::TokenStream;
+use quote::quote;
+use std::cell::RefCell;
+
+#[derive(Default)]
+pub struct Names {
+	names: Vec<String>,
+}
+
+impl Names {
+	pub fn intern(&mut self, s: impl AsRef<str>) -> usize {
+		let s = s.as_ref();
+		if let Some(pos) = self.names.iter().position(|v| v == s) {
+			return pos;
+		}
+		let pos = self.names.len();
+		self.names.push(s.to_owned());
+		pos
+	}
+
+	pub fn expand(&self) -> TokenStream {
+		let len = self.names.len();
+		let name = self.names.iter();
+		quote! {
+			thread_local! {
+				static NAMES: [::jrsonnet_evaluator::IStr; #len] = [
+					#(::jrsonnet_evaluator::IStr::from(#name),)*
+				];
+			}
+		}
+	}
+}
addedcrates/jrsonnet-macros/src/typed.rsdiffbeforeafterboth
after · crates/jrsonnet-macros/src/typed.rs
1use crate::names::Names;2use crate::{extract_type_from_option, kw, parse_attr, type_is_path};3use proc_macro2::TokenStream;4use quote::quote;5use syn::parse::{Parse, ParseStream};6use syn::spanned::Spanned as _;7use syn::{parenthesized, token, DeriveInput, Error, Ident, LitStr, Result, Token, Type};89#[derive(Default)]10#[allow(clippy::struct_excessive_bools)]11struct TypedAttr {12	rename: Option<String>,13	aliases: Vec<String>,14	flatten: bool,15	/// flatten(ok) strategy for flattened optionals16	/// field would be None in case of any parsing error (as in serde)17	flatten_ok: bool,18	// Should it be `field+:` instead of `field:`19	add: bool,20	// Should it be `field::` instead of `field:`21	hide: bool,22}23impl Parse for TypedAttr {24	fn parse(input: ParseStream) -> syn::Result<Self> {25		let mut out = Self::default();26		loop {27			let lookahead = input.lookahead1();28			if lookahead.peek(kw::rename) {29				input.parse::<kw::rename>()?;30				input.parse::<Token![=]>()?;31				let name = input.parse::<LitStr>()?;32				if out.rename.is_some() {33					return Err(Error::new(34						name.span(),35						"rename attribute may only be specified once",36					));37				}38				out.rename = Some(name.value());39			} else if lookahead.peek(kw::alias) {40				input.parse::<kw::alias>()?;41				input.parse::<Token![=]>()?;42				let alias = input.parse::<LitStr>()?;43				out.aliases.push(alias.value());44			} else if lookahead.peek(kw::flatten) {45				input.parse::<kw::flatten>()?;46				out.flatten = true;47				if input.peek(token::Paren) {48					let content;49					parenthesized!(content in input);50					let lookahead = content.lookahead1();51					if lookahead.peek(kw::ok) {52						content.parse::<kw::ok>()?;53						out.flatten_ok = true;54					} else {55						return Err(lookahead.error());56					}57				}58			} else if lookahead.peek(kw::add) {59				input.parse::<kw::add>()?;60				out.add = true;61			} else if lookahead.peek(kw::hide) {62				input.parse::<kw::hide>()?;63				out.hide = true;64			} else if input.is_empty() {65				break;66			} else {67				return Err(lookahead.error());68			}69			if input.peek(Token![,]) {70				input.parse::<Token![,]>()?;71			} else {72				break;73			}74		}75		Ok(out)76	}77}78struct TypedField {79	attr: TypedAttr,80	ident: Ident,81	ty: Type,82	is_option: bool,83	is_lazy: bool,84}85impl TypedField {86	fn parse(field: &syn::Field) -> Result<Self> {87		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();88		let Some(ident) = field.ident.clone() else {89			return Err(Error::new(90				field.span(),91				"this field should appear in output object, but it has no visible name",92			));93		};94		let (is_option, ty) = extract_type_from_option(&field.ty)?95			.map_or_else(|| (false, field.ty.clone()), |ty| (true, ty.clone()));96		if is_option && attr.flatten {97			if !attr.flatten_ok {98				return Err(Error::new(99					field.span(),100					"strategy should be set when flattening Option",101				));102			}103		} else if attr.flatten_ok {104			return Err(Error::new(105				field.span(),106				"flatten(ok) is only useable on optional fields",107			));108		}109110		let is_lazy = type_is_path(&ty, "Thunk").is_some();111112		Ok(Self {113			attr,114			ident,115			ty,116			is_option,117			is_lazy,118		})119	}120	/// None if this field is flattened in jsonnet output121	fn name(&self) -> Option<String> {122		if self.attr.flatten {123			return None;124		}125		Some(126			self.attr127				.rename128				.clone()129				.unwrap_or_else(|| self.ident.to_string()),130		)131	}132133	fn expand_field(&self) -> Option<TokenStream> {134		if self.is_option {135			return None;136		}137		let name = self.name()?;138		let ty = &self.ty;139		Some(quote! {140			(#name, <#ty as Typed>::TYPE)141		})142	}143144	fn expand_parse(&self, names: &mut Names) -> TokenStream {145		if self.is_option {146			self.expand_parse_optional(names)147		} else {148			self.expand_parse_mandatory(names)149		}150	}151152	fn expand_parse_optional(&self, names: &mut Names) -> TokenStream {153		let ident = &self.ident;154		let ty = &self.ty;155156		// optional flatten is handled in same way as serde157		if self.attr.flatten {158			return quote! {159				#ident: <#ty as TypedObj>::parse(&obj).ok(),160			};161		}162163		let name = names.intern(self.name().unwrap());164		let aliases = self165			.attr166			.aliases167			.iter()168			.map(|name| names.intern(name))169			.collect::<Vec<_>>();170171		quote! {172			#ident: {173				let __value = if let Some(__v) = obj.get(__names[#name].clone())? {174					Some(__v)175				} #(else if let Some(__v) = obj.get(__names[#aliases].clone())? {176					Some(__v)177				})* else {178					None179				};180181				__value.map(<#ty as Typed>::from_untyped).transpose()?182			},183		}184	}185186	fn expand_parse_mandatory(&self, names: &mut Names) -> TokenStream {187		let ident = &self.ident;188		let ty = &self.ty;189190		// optional flatten is handled in same way as serde191		if self.attr.flatten {192			return quote! {193				#ident: <#ty as TypedObj>::parse(&obj)?,194			};195		}196197		let name = self.name().unwrap();198		let aliases = &self.attr.aliases;199200		let error_text = if aliases.is_empty() {201			// clippy does not understand name variable usage in quote! macro202			#[allow(clippy::redundant_clone)]203			name.clone()204		} else {205			format!("{name} (alias {})", aliases.join(", "))206		};207208		let error_text = names.intern(error_text);209		let name = names.intern(name);210		let aliases = aliases.iter().map(|alias| names.intern(alias));211212		quote! {213			#ident: {214				let __value = if let Some(__v) = obj.get(__names[#name].clone())? {215					__v216				} #(else if let Some(__v) = obj.get(__names[#aliases].clone())? {217					__v218				})* else {219					return Err(ErrorKind::NoSuchField(__names[#error_text].clone(), vec![]).into());220				};221222				<#ty as Typed>::from_untyped(__value)?223			},224		}225	}226227	fn expand_serialize(&self, names: &mut Names) -> TokenStream {228		let ident = &self.ident;229		let ty = &self.ty;230		self.name().map_or_else(231			|| {232				if self.is_option {233					quote! {234						if let Some(value) = self.#ident {235							<#ty as TypedObj>::serialize(value, out)?;236						}237					}238				} else {239					quote! {240						<#ty as TypedObj>::serialize(self.#ident, out)?;241					}242				}243			},244			|name| {245				let name = names.intern(name);246				let hide = if self.attr.hide {247					quote! {.hide()}248				} else {249					quote! {}250				};251				let add = if self.attr.add {252					quote! {.add()}253				} else {254					quote! {}255				};256				let value = if self.is_lazy {257					quote! {258						out.field(__names[#name].clone())259							#hide260							#add261							.try_thunk(<#ty as Typed>::into_lazy_untyped(value))?;262					}263				} else {264					quote! {265						out.field(__names[#name].clone())266							#hide267							#add268							.try_value(<#ty as Typed>::into_untyped(value)?)?;269					}270				};271				if self.is_option {272					quote! {273						if let Some(value) = self.#ident {274							#value275						}276					}277				} else {278					quote! {279						{280							let value = self.#ident;281							#value282						}283					}284				}285			},286		)287	}288}289290pub fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {291	let syn::Data::Struct(data) = &input.data else {292		return Err(Error::new(input.span(), "only structs supported"));293	};294295	let ident = &input.ident;296	let fields = data297		.fields298		.iter()299		.map(TypedField::parse)300		.collect::<Result<Vec<_>>>()?;301302	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();303304	let capacity = fields.len();305306	let typed = {307		let fields = fields308			.iter()309			.filter_map(TypedField::expand_field)310			.collect::<Vec<_>>();311		quote! {312			impl #impl_generics Typed for #ident #ty_generics #where_clause {313				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[314					#(#fields,)*315				]);316317				fn from_untyped(value: Val) -> JrResult<Self> {318					let obj = value.as_obj().expect("shape is correct");319					Self::parse(&obj)320				}321322				fn into_untyped(value: Self) -> JrResult<Val> {323					let mut out = ObjValueBuilder::with_capacity(#capacity);324					value.serialize(&mut out)?;325					Ok(Val::Obj(out.build()))326				}327328			}329		}330	};331332	let mut names = Names::default();333334	let fields_parse = fields335		.iter()336		.map(|f| f.expand_parse(&mut names))337		.collect::<Vec<_>>();338	let fields_serialize = fields339		.iter()340		.map(|f| f.expand_serialize(&mut names))341		.collect::<Vec<_>>();342343	let names_expanded = names.expand();344	Ok(quote! {345		const _: () = {346			use ::jrsonnet_evaluator::{347				typed::{ComplexValType, Typed, TypedObj, CheckType},348				Val, State,349				error::{ErrorKind, Result as JrResult},350				ObjValueBuilder, ObjValue, IStr,351			};352353			#typed354355			#names_expanded356357			impl #impl_generics TypedObj for #ident #ty_generics #where_clause {358				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {359					NAMES.with(|__names| {360						#(#fields_serialize)*361362						Ok(())363					})364				}365				fn parse(obj: &ObjValue) -> JrResult<Self> {366					NAMES.with(|__names| Ok(Self {367						#(#fields_parse)*368					}))369				}370			}371		};372	})373}
modifiedcrates/jrsonnet-stdlib/src/regex.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/regex.rs
+++ b/crates/jrsonnet-stdlib/src/regex.rs
@@ -4,8 +4,9 @@
 use jrsonnet_evaluator::{
 	error::{ErrorKind::*, Result},
 	rustc_hash::FxBuildHasher,
+	typed::Typed,
 	val::StrValue,
-	IStr, ObjValueBuilder, Val,
+	IStr, ObjValue, ObjValueBuilder,
 };
 use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_macros::builtin;
@@ -20,7 +21,7 @@
 		Self {
 			cache: RefCell::new(LruCache::with_hasher(
 				NonZeroUsize::new(20).unwrap(),
-				FxBuildHasher::default(),
+				FxBuildHasher,
 			)),
 		}
 	}
@@ -40,21 +41,27 @@
 	}
 }
 
-pub fn regex_match_inner(regex: &Regex, str: String) -> Result<Val> {
-	let mut out = ObjValueBuilder::with_capacity(3);
+#[derive(Typed)]
+pub struct RegexMatch {
+	string: IStr,
+	captures: Vec<IStr>,
+	#[typed(rename = "namedCaptures")]
+	named_captures: ObjValue,
+}
 
+fn regex_match_inner(regex: &Regex, str: String) -> Result<Option<RegexMatch>> {
 	let mut captures = Vec::with_capacity(regex.captures_len());
 	let mut named_captures = ObjValueBuilder::with_capacity(regex.capture_names().len());
 
 	let Some(captured) = regex.captures(&str) else {
-		return Ok(Val::Null);
+		return Ok(None);
 	};
 
 	for ele in captured.iter().skip(1) {
 		if let Some(ele) = ele {
-			captures.push(Val::Str(StrValue::Flat(ele.as_str().into())));
+			captures.push(ele.as_str().into());
 		} else {
-			captures.push(Val::Str(StrValue::Flat(IStr::empty())));
+			captures.push(IStr::empty());
 		}
 	}
 	for (i, name) in regex
@@ -67,13 +74,11 @@
 		named_captures.field(name).try_value(capture)?;
 	}
 
-	out.field("string")
-		.value(Val::Str(captured.get(0).unwrap().as_str().into()));
-	out.field("captures").value(Val::Arr(captures.into()));
-	out.field("namedCaptures")
-		.value(Val::Obj(named_captures.build()));
-
-	Ok(Val::Obj(out.build()))
+	Ok(Some(RegexMatch {
+		string: captured.get(0).expect("regex matched").as_str().into(),
+		named_captures: named_captures.build(),
+		captures,
+	}))
 }
 
 #[builtin(fields(
@@ -83,7 +88,7 @@
 	this: &builtin_regex_partial_match,
 	pattern: IStr,
 	str: String,
-) -> Result<Val> {
+) -> Result<Option<RegexMatch>> {
 	let regex = this.cache.parse(pattern)?;
 	regex_match_inner(&regex, str)
 }
@@ -95,7 +100,7 @@
 	this: &builtin_regex_full_match,
 	pattern: StrValue,
 	str: String,
-) -> Result<Val> {
+) -> Result<Option<RegexMatch>> {
 	let pattern = format!("^{pattern}$").into();
 	let regex = this.cache.parse(pattern)?;
 	regex_match_inner(&regex, str)