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
after · crates/jrsonnet-macros/src/lib.rs
1use std::string::String;23use proc_macro2::TokenStream;4use quote::{quote, quote_spanned};5use syn::{6	parenthesized,7	parse::{Parse, ParseStream},8	parse_macro_input,9	punctuated::Punctuated,10	spanned::Spanned,11	token::{self, Comma},12	Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,13	LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,14};1516use self::typed::derive_typed_inner;1718mod typed;19mod names;2021fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>22where23	Ident: PartialEq<I>,24{25	let attrs = attrs26		.iter()27		.filter(|a| a.path().is_ident(&ident))28		.collect::<Vec<_>>();29	if attrs.len() > 1 {30		return Err(Error::new(31			attrs[1].span(),32			"this attribute may be specified only once",33		));34	} else if attrs.is_empty() {35		return Ok(false);36	}37	let attr = attrs[0];3839	match attr.meta {40		Meta::Path(_) => Ok(true),41		_ => Ok(false),42	}43}44fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>45where46	Ident: PartialEq<I>,47{48	let attrs = attrs49		.iter()50		.filter(|a| a.path().is_ident(&ident))51		.collect::<Vec<_>>();52	if attrs.len() > 1 {53		return Err(Error::new(54			attrs[1].span(),55			"this attribute may be specified only once",56		));57	} else if attrs.is_empty() {58		return Ok(None);59	}60	let attr = attrs[0];61	let attr = attr.parse_args::<A>()?;6263	Ok(Some(attr))64}65fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)66where67	Ident: PartialEq<I>,68{69	attrs.retain(|a| !a.path().is_ident(&ident));70}7172fn path_is(path: &Path, needed: &str) -> bool {73	path.leading_colon.is_none()74		&& !path.segments.is_empty()75		&& path.segments.iter().last().unwrap().ident == needed76}7778fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {79	match ty {80		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {81			let args = &path.path.segments.iter().last().unwrap().arguments;82			Some(args)83		}84		_ => None,85	}86}8788fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {89	let Some(args) = type_is_path(ty, "Option") else {90		return Ok(None);91	};92	// It should have only on angle-bracketed param ("<String>"):93	let PathArguments::AngleBracketed(params) = args else {94		return Err(Error::new(args.span(), "missing option generic"));95	};96	let generic_arg = params.args.iter().next().unwrap();97	// This argument must be a type:98	let GenericArgument::Type(ty) = generic_arg else {99		return Err(Error::new(100			generic_arg.span(),101			"option generic should be a type",102		));103	};104	Ok(Some(ty))105}106107struct Field {108	attrs: Vec<Attribute>,109	name: Ident,110	_colon: Token![:],111	ty: Type,112}113impl Parse for Field {114	fn parse(input: ParseStream) -> syn::Result<Self> {115		Ok(Self {116			attrs: input.call(Attribute::parse_outer)?,117			name: input.parse()?,118			_colon: input.parse()?,119			ty: input.parse()?,120		})121	}122}123124mod kw {125	syn::custom_keyword!(fields);126	syn::custom_keyword!(rename);127	syn::custom_keyword!(alias);128	syn::custom_keyword!(flatten);129	syn::custom_keyword!(add);130	syn::custom_keyword!(hide);131	syn::custom_keyword!(ok);132}133134struct BuiltinAttrs {135	fields: Vec<Field>,136}137impl Parse for BuiltinAttrs {138	fn parse(input: ParseStream) -> syn::Result<Self> {139		if input.is_empty() {140			return Ok(Self { fields: Vec::new() });141		}142		input.parse::<kw::fields>()?;143		let fields;144		parenthesized!(fields in input);145		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;146		Ok(Self {147			fields: p.into_iter().collect(),148		})149	}150}151152enum Optionality {153	Required,154	Optional,155	Default(Expr),156	TypeDefault,157}158159#[allow(160	clippy::large_enum_variant,161	reason = "this macro is not that hot for it to matter"162)]163enum ArgInfo {164	Normal {165		ty: Box<Type>,166		optionality: Optionality,167		name: Option<String>,168		cfg_attrs: Vec<Attribute>,169	},170	Lazy {171		is_option: bool,172		name: Option<String>,173	},174	Context,175	Location,176	This,177}178179impl ArgInfo {180	fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {181		let FnArg::Typed(arg) = arg else {182			unreachable!()183		};184		let ident = match &arg.pat as &Pat {185			Pat::Ident(i) => Some(i.ident.clone()),186			_ => None,187		};188		let ty = &arg.ty;189		if type_is_path(ty, "Context").is_some() {190			return Ok(Self::Context);191		} else if type_is_path(ty, "CallLocation").is_some() {192			return Ok(Self::Location);193		} else if type_is_path(ty, "Thunk").is_some() {194			return Ok(Self::Lazy {195				is_option: false,196				name: ident.map(|v| v.to_string()),197			});198		}199200		match ty as &Type {201			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),202			_ => {}203		}204205		let (optionality, ty) = if try_parse_attr_noargs(&mut arg.attrs, "default")? {206			remove_attr(&mut arg.attrs, "default");207			(Optionality::TypeDefault, ty.clone())208		} else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {209			remove_attr(&mut arg.attrs, "default");210			(Optionality::Default(default), ty.clone())211		} else if let Some(ty) = extract_type_from_option(ty)? {212			if type_is_path(ty, "Thunk").is_some() {213				return Ok(Self::Lazy {214					is_option: true,215					name: ident.map(|v| v.to_string()),216				});217			}218219			(Optionality::Optional, Box::new(ty.clone()))220		} else {221			(Optionality::Required, ty.clone())222		};223224		let cfg_attrs = arg225			.attrs226			.iter()227			.filter(|a| a.path().is_ident("cfg"))228			.cloned()229			.collect();230231		Ok(Self::Normal {232			ty,233			optionality,234			name: ident.map(|v| v.to_string()),235			cfg_attrs,236		})237	}238}239240#[proc_macro_attribute]241pub fn builtin(242	attr: proc_macro::TokenStream,243	item: proc_macro::TokenStream,244) -> proc_macro::TokenStream {245	let attr = parse_macro_input!(attr as BuiltinAttrs);246	let item_fn = parse_macro_input!(item as ItemFn);247248	match builtin_inner(attr, item_fn) {249		Ok(v) => v.into(),250		Err(e) => e.into_compile_error().into(),251	}252}253254#[allow(clippy::too_many_lines)]255fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {256	let ReturnType::Type(_, result) = &fun.sig.output else {257		return Err(Error::new(258			fun.sig.span(),259			"builtin should return something",260		));261	};262263	let name = fun.sig.ident.to_string();264	let args = fun265		.sig266		.inputs267		.iter_mut()268		.map(|arg| ArgInfo::parse(&name, arg))269		.collect::<Result<Vec<_>>>()?;270271	let params_desc = args.iter().filter_map(|a| match a {272		ArgInfo::Normal {273			optionality,274			name,275			cfg_attrs,276			..277		} => {278			let name = name279				.as_ref()280				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});281			let default = match optionality {282				Optionality::Required => quote!(ParamDefault::None),283				Optionality::Optional | Optionality::TypeDefault => quote!(ParamDefault::Exists),284				Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),285			};286			Some(quote! {287				#(#cfg_attrs)*288				[#name => #default],289			})290		}291		ArgInfo::Lazy { is_option, name } => {292			let name = name293				.as_ref()294				.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});295			Some(quote! {296				[#name => ParamDefault::exists(#is_option)],297			})298		}299		ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,300	});301302	let mut id = 0usize;303	let pass = args304		.iter()305		.map(|a| match a {306			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {307				let cid = id;308				id += 1;309				(quote! {#cid}, a)310			}311			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {312				(quote! {compile_error!("should not use id")}, a)313			}314		})315		.map(|(id, a)| match a {316			ArgInfo::Normal {317				ty,318				optionality,319				name,320				cfg_attrs,321			} => {322				let name = name.as_ref().map_or("<unnamed>", String::as_str);323				let eval = quote! {jrsonnet_evaluator::in_description_frame(324					|| format!("argument <{}> evaluation", #name),325					|| <#ty>::from_untyped(value.evaluate()?),326				)?};327				let value = match optionality {328					Optionality::Required => quote! {{329						let value = parsed[#id].as_ref().expect("args shape is checked");330						#eval331					},},332					Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {333						Some(#eval)334					} else {335						None336					},},337					Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {338						#eval339					} else {340						let v: #ty = #expr;341						v342					},},343					Optionality::TypeDefault => quote! {if let Some(value) = &parsed[#id] {344						#eval345					} else {346						let v: #ty = Default::default();347						v348					},},349				};350				quote! {351					#(#cfg_attrs)*352					#value353				}354			}355			ArgInfo::Lazy { is_option, .. } => {356				if *is_option {357					quote! {if let Some(value) = &parsed[#id] {358						Some(value.clone())359					} else {360						None361					},}362				} else {363					quote! {364						parsed[#id].as_ref().expect("args shape is correct").clone(),365					}366				}367			}368			ArgInfo::Context => quote! {ctx.clone(),},369			ArgInfo::Location => quote! {location,},370			ArgInfo::This => quote! {self,},371		});372373	let fields = attr.fields.iter().map(|field| {374		let attrs = &field.attrs;375		let name = &field.name;376		let ty = &field.ty;377		quote! {378			#(#attrs)*379			pub #name: #ty,380		}381	});382383	let name = &fun.sig.ident;384	let vis = &fun.vis;385	let static_ext = if attr.fields.is_empty() {386		quote! {387			impl #name {388				pub const INST: &'static dyn StaticBuiltin = &#name {};389			}390			impl StaticBuiltin for #name {}391		}392	} else {393		quote! {}394	};395	let static_derive_copy = if attr.fields.is_empty() {396		quote! {, Copy}397	} else {398		quote! {}399	};400401	Ok(quote! {402		#fun403404		#[doc(hidden)]405		#[allow(non_camel_case_types)]406		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]407		#vis struct #name {408			#(#fields)*409		}410		const _: () = {411			use ::jrsonnet_evaluator::{412				State, Val,413				function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},414				Result, Context, typed::Typed,415				parser::Span, params, Thunk,416			};417			params!(418				#(#params_desc)*419			);420421			#static_ext422			impl Builtin for #name423			where424				Self: 'static425			{426				fn name(&self) -> &str {427					stringify!(#name)428				}429				fn params(&self) -> FunctionSignature {430					PARAMS.with(|p| p.clone())431				}432				#[allow(unused_variables)]433				fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {434					let result: #result = #name(#(#pass)*);435					<_ as Typed>::into_result(result)436				}437				fn as_any(&self) -> &dyn ::std::any::Any {438					self439				}440			}441		};442	})443}444445#[proc_macro_derive(Typed, attributes(typed))]446pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {447	let input = parse_macro_input!(item as DeriveInput);448449	match derive_typed_inner(input) {450		Ok(v) => v.into(),451		Err(e) => e.to_compile_error().into(),452	}453}454455struct FormatInput {456	formatting: LitStr,457	arguments: Vec<Expr>,458}459impl Parse for FormatInput {460	fn parse(input: ParseStream) -> Result<Self> {461		let formatting = input.parse()?;462		let mut arguments = Vec::new();463464		while input.peek(Token![,]) {465			input.parse::<Token![,]>()?;466			if input.is_empty() {467				// Trailing comma468				break;469			}470			let expr = input.parse()?;471			arguments.push(expr);472		}473474		if !input.is_empty() {475			return Err(syn::Error::new(input.span(), "unexpected trailing input"));476		}477478		Ok(Self {479			formatting,480			arguments,481		})482	}483}484fn is_format_str(i: &str) -> bool {485	let mut is_plain = true;486	// -1 = {487	// +1 = }488	let mut is_bracket = 0i8;489	for ele in i.chars() {490		match ele {491			'{' if is_bracket == -1 => {492				is_bracket = 0;493			}494			'}' if is_bracket == -1 => {495				is_plain = false;496				break;497			}498			'}' if is_bracket == 1 => {499				is_bracket = 0;500			}501			'{' if is_bracket == 1 => {502				is_plain = false;503				break;504			}505			'{' => {506				is_bracket = -1;507			}508			'}' => {509				is_bracket = 1;510			}511			_ if is_bracket != 0 => {512				is_plain = false;513				break;514			}515			_ => {}516		}517	}518	!is_plain || is_bracket != 0519}520impl FormatInput {521	fn expand(self) -> TokenStream {522		let format = self.formatting;523		if is_format_str(&format.value()) {524			let args = self.arguments;525			quote! {526				::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))527			}528		} else {529			if let Some(first) = self.arguments.first() {530				return syn::Error::new(531					first.span(),532					"string has no formatting codes, it should not have the arguments",533				)534				.into_compile_error();535			}536			quote! {537				::jrsonnet_evaluator::IStr::from(#format)538			}539		}540	}541}542543/// `IStr` formatting helper544///545/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`546/// This macro looks for formatting codes in the input string, and uses547/// `format!()` only when necessary548#[proc_macro]549pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {550	let input = parse_macro_input!(input as FormatInput);551	input.expand().into()552}553554/// Create Thunk using closure syntax555#[proc_macro]556#[allow(non_snake_case)]557pub fn Thunk(input: proc_macro::TokenStream) -> proc_macro::TokenStream {558	let input = parse_macro_input!(input as ExprClosure);559560	let span = input.inputs.span();561	let move_check = input.capture.is_none().then(|| {562		quote_spanned! {span => {563			compile_error!("Thunk! needs to be called with move closure");564		}}565	});566567	let (env, closure, args) = syn_dissect_closure::split_env(input);568569	let trace_check = args.iter().map(|el| {570		let span = el.span();571		quote_spanned! {span => ::jrsonnet_evaluator::gc::assert_trace(&#el);}572	});573574	quote! {{575		#move_check576		#(#trace_check)*577		::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))578	}}.into()579}
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
--- /dev/null
+++ b/crates/jrsonnet-macros/src/typed.rs
@@ -0,0 +1,373 @@
+use crate::names::Names;
+use crate::{extract_type_from_option, kw, parse_attr, type_is_path};
+use proc_macro2::TokenStream;
+use quote::quote;
+use syn::parse::{Parse, ParseStream};
+use syn::spanned::Spanned as _;
+use syn::{parenthesized, token, DeriveInput, Error, Ident, LitStr, Result, Token, Type};
+
+#[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, names: &mut Names) -> TokenStream {
+		if self.is_option {
+			self.expand_parse_optional(names)
+		} else {
+			self.expand_parse_mandatory(names)
+		}
+	}
+
+	fn expand_parse_optional(&self, names: &mut Names) -> 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 = names.intern(self.name().unwrap());
+		let aliases = self
+			.attr
+			.aliases
+			.iter()
+			.map(|name| names.intern(name))
+			.collect::<Vec<_>>();
+
+		quote! {
+			#ident: {
+				let __value = if let Some(__v) = obj.get(__names[#name].clone())? {
+					Some(__v)
+				} #(else if let Some(__v) = obj.get(__names[#aliases].clone())? {
+					Some(__v)
+				})* else {
+					None
+				};
+
+				__value.map(<#ty as Typed>::from_untyped).transpose()?
+			},
+		}
+	}
+
+	fn expand_parse_mandatory(&self, names: &mut Names) -> 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(", "))
+		};
+
+		let error_text = names.intern(error_text);
+		let name = names.intern(name);
+		let aliases = aliases.iter().map(|alias| names.intern(alias));
+
+		quote! {
+			#ident: {
+				let __value = if let Some(__v) = obj.get(__names[#name].clone())? {
+					__v
+				} #(else if let Some(__v) = obj.get(__names[#aliases].clone())? {
+					__v
+				})* else {
+					return Err(ErrorKind::NoSuchField(__names[#error_text].clone(), vec![]).into());
+				};
+
+				<#ty as Typed>::from_untyped(__value)?
+			},
+		}
+	}
+
+	fn expand_serialize(&self, names: &mut Names) -> 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 name = names.intern(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(__names[#name].clone())
+							#hide
+							#add
+							.try_thunk(<#ty as Typed>::into_lazy_untyped(value))?;
+					}
+				} else {
+					quote! {
+						out.field(__names[#name].clone())
+							#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
+						}
+					}
+				}
+			},
+		)
+	}
+}
+
+pub 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 capacity = fields.len();
+
+	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::with_capacity(#capacity);
+					value.serialize(&mut out)?;
+					Ok(Val::Obj(out.build()))
+				}
+
+			}
+		}
+	};
+
+	let mut names = Names::default();
+
+	let fields_parse = fields
+		.iter()
+		.map(|f| f.expand_parse(&mut names))
+		.collect::<Vec<_>>();
+	let fields_serialize = fields
+		.iter()
+		.map(|f| f.expand_serialize(&mut names))
+		.collect::<Vec<_>>();
+
+	let names_expanded = names.expand();
+	Ok(quote! {
+		const _: () = {
+			use ::jrsonnet_evaluator::{
+				typed::{ComplexValType, Typed, TypedObj, CheckType},
+				Val, State,
+				error::{ErrorKind, Result as JrResult},
+				ObjValueBuilder, ObjValue, IStr,
+			};
+
+			#typed
+
+			#names_expanded
+
+			impl #impl_generics TypedObj for #ident #ty_generics #where_clause {
+				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {
+					NAMES.with(|__names| {
+						#(#fields_serialize)*
+
+						Ok(())
+					})
+				}
+				fn parse(obj: &ObjValue) -> JrResult<Self> {
+					NAMES.with(|__names| Ok(Self {
+						#(#fields_parse)*
+					}))
+				}
+			}
+		};
+	})
+}
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)