git.delta.rocks / jrsonnet / refs/commits / 76b0db1d8913

difftreelog

feat builtin downcasting

Yaroslav Bolyukin2023-02-16parent: #5acdbdb.patch.diff
in: master

2 files changed

modifiedcrates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -1,4 +1,4 @@
-use std::borrow::Cow;
+use std::{any::Any, borrow::Cow};
 
 use jrsonnet_gcmodule::Trace;
 
@@ -25,6 +25,8 @@
 	fn params(&self) -> &[BuiltinParam];
 	/// Call the builtin
 	fn call(&self, ctx: Context, loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val>;
+
+	fn as_any(&self) -> &dyn Any;
 }
 
 pub trait StaticBuiltin: Builtin + Send + Sync
@@ -76,6 +78,10 @@
 			.collect::<Result<Vec<Val>>>()?;
 		self.handler.call(&args)
 	}
+
+	fn as_any(&self) -> &dyn Any {
+		self
+	}
 }
 
 pub trait NativeCallbackHandler: Trace {
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-macros/src/lib.rs
1use proc_macro2::TokenStream;2use quote::quote;3use syn::{4	parenthesized,5	parse::{Parse, ParseStream},6	parse_macro_input,7	punctuated::Punctuated,8	spanned::Spanned,9	token::{self, Comma},10	Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, Path,11	PathArguments, Result, ReturnType, Token, Type,12};1314fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>15where16	Ident: PartialEq<I>,17{18	let attrs = attrs19		.iter()20		.filter(|a| a.path.is_ident(&ident))21		.collect::<Vec<_>>();22	if attrs.len() > 1 {23		return Err(Error::new(24			attrs[1].span(),25			"this attribute may be specified only once",26		));27	} else if attrs.is_empty() {28		return Ok(None);29	}30	let attr = attrs[0];31	let attr = attr.parse_args::<A>()?;3233	Ok(Some(attr))34}3536fn path_is(path: &Path, needed: &str) -> bool {37	path.leading_colon.is_none()38		&& !path.segments.is_empty()39		&& path.segments.iter().last().unwrap().ident == needed40}4142fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {43	match ty {44		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {45			let args = &path.path.segments.iter().last().unwrap().arguments;46			Some(args)47		}48		_ => None,49	}50}5152fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {53	let Some(args) = type_is_path(ty, "Option") else {54		return Ok(None)55	};56	// It should have only on angle-bracketed param ("<String>"):57	let PathArguments::AngleBracketed(params) = args else {58		return Err(Error::new(args.span(), "missing option generic"));59	};60	let generic_arg = params.args.iter().next().unwrap();61	// This argument must be a type:62	let GenericArgument::Type(ty) = generic_arg else {63		return Err(Error::new(64			generic_arg.span(),65			"option generic should be a type",66		))67	};68	Ok(Some(ty))69}7071struct Field {72	name: Ident,73	_colon: Token![:],74	ty: Type,75}76impl Parse for Field {77	fn parse(input: ParseStream) -> syn::Result<Self> {78		Ok(Self {79			name: input.parse()?,80			_colon: input.parse()?,81			ty: input.parse()?,82		})83	}84}8586mod kw {87	syn::custom_keyword!(fields);88	syn::custom_keyword!(rename);89	syn::custom_keyword!(flatten);90	syn::custom_keyword!(ok);91}9293struct EmptyAttr;94impl Parse for EmptyAttr {95	fn parse(_input: ParseStream) -> Result<Self> {96		Ok(Self)97	}98}99100struct BuiltinAttrs {101	fields: Vec<Field>,102}103impl Parse for BuiltinAttrs {104	fn parse(input: ParseStream) -> syn::Result<Self> {105		if input.is_empty() {106			return Ok(Self { fields: Vec::new() });107		}108		input.parse::<kw::fields>()?;109		let fields;110		parenthesized!(fields in input);111		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;112		Ok(Self {113			fields: p.into_iter().collect(),114		})115	}116}117118enum ArgInfo {119	Normal {120		ty: Box<Type>,121		is_option: bool,122		name: Option<String>,123		cfg_attrs: Vec<Attribute>,124	},125	Lazy {126		is_option: bool,127		name: Option<String>,128	},129	Context,130	Location,131	This,132}133134impl ArgInfo {135	fn parse(name: &str, arg: &FnArg) -> Result<Self> {136		let FnArg::Typed(arg) = arg else {137			unreachable!()138		};139		let ident = match &arg.pat as &Pat {140			Pat::Ident(i) => Some(i.ident.clone()),141			_ => None,142		};143		let ty = &arg.ty;144		if type_is_path(ty, "Context").is_some() {145			return Ok(Self::Context);146		} else if type_is_path(ty, "CallLocation").is_some() {147			return Ok(Self::Location);148		} else if type_is_path(ty, "Thunk").is_some() {149			return Ok(Self::Lazy {150				is_option: false,151				name: ident.map(|v| v.to_string()),152			});153		}154155		match ty as &Type {156			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),157			_ => {}158		}159160		let (is_option, ty) = if let Some(ty) = extract_type_from_option(ty)? {161			if type_is_path(ty, "Thunk").is_some() {162				return Ok(Self::Lazy {163					is_option: true,164					name: ident.map(|v| v.to_string()),165				});166			}167168			(true, Box::new(ty.clone()))169		} else {170			(false, ty.clone())171		};172173		let cfg_attrs = arg174			.attrs175			.iter()176			.filter(|a| a.path.is_ident("cfg"))177			.cloned()178			.collect();179180		Ok(Self::Normal {181			ty,182			is_option,183			name: ident.map(|v| v.to_string()),184			cfg_attrs,185		})186	}187}188189#[proc_macro_attribute]190pub fn builtin(191	attr: proc_macro::TokenStream,192	item: proc_macro::TokenStream,193) -> proc_macro::TokenStream {194	let attr = parse_macro_input!(attr as BuiltinAttrs);195	let item_fn = item.clone();196	let item_fn: ItemFn = parse_macro_input!(item_fn);197198	match builtin_inner(attr, item_fn, item.into()) {199		Ok(v) => v.into(),200		Err(e) => e.into_compile_error().into(),201	}202}203204fn builtin_inner(205	attr: BuiltinAttrs,206	fun: ItemFn,207	item: proc_macro2::TokenStream,208) -> syn::Result<TokenStream> {209	let ReturnType::Type(_, result) = &fun.sig.output else {210		return Err(Error::new(211			fun.sig.span(),212			"builtin should return something",213		))214	};215216	let name = fun.sig.ident.to_string();217	let args = fun218		.sig219		.inputs220		.iter()221		.map(|arg| ArgInfo::parse(&name, arg))222		.collect::<Result<Vec<_>>>()?;223224	let params_desc = args.iter().flat_map(|a| match a {225		ArgInfo::Normal {226			is_option,227			name,228			cfg_attrs,229			..230		} => {231			let name = name232				.as_ref()233				.map(|n| quote! {Some(std::borrow::Cow::Borrowed(#n))})234				.unwrap_or_else(|| quote! {None});235			Some(quote! {236				#(#cfg_attrs)*237				BuiltinParam {238					name: #name,239					has_default: #is_option,240				},241			})242		}243		ArgInfo::Lazy { is_option, name } => {244			let name = name245				.as_ref()246				.map(|n| quote! {Some(std::borrow::Cow::Borrowed(#n))})247				.unwrap_or_else(|| quote! {None});248			Some(quote! {249				BuiltinParam {250					name: #name,251					has_default: #is_option,252				},253			})254		}255		ArgInfo::Context => None,256		ArgInfo::Location => None,257		ArgInfo::This => None,258	});259260	let mut id = 0usize;261	let pass = args262		.iter()263		.map(|a| match a {264			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {265				let cid = id;266				id += 1;267				(quote! {#cid}, a)268			}269			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {270				(quote! {compile_error!("should not use id")}, a)271			}272		})273		.map(|(id, a)| match a {274			ArgInfo::Normal {275				ty,276				is_option,277				name,278				cfg_attrs,279			} => {280				let name = name.as_ref().map(|v| v.as_str()).unwrap_or("<unnamed>");281				let eval = quote! {jrsonnet_evaluator::State::push_description(282					|| format!("argument <{}> evaluation", #name),283					|| <#ty>::from_untyped(value.evaluate()?),284				)?};285				let value = if *is_option {286					quote! {if let Some(value) = &parsed[#id] {287						Some(#eval)288					} else {289						None290					},}291				} else {292					quote! {{293						let value = parsed[#id].as_ref().expect("args shape is checked");294						#eval295					},}296				};297				quote! {298					#(#cfg_attrs)*299					#value300				}301			}302			ArgInfo::Lazy { is_option, .. } => {303				if *is_option {304					quote! {if let Some(value) = &parsed[#id] {305						Some(value.clone())306					} else {307						None308					}}309				} else {310					quote! {311						parsed[#id].as_ref().expect("args shape is correct").clone(),312					}313				}314			}315			ArgInfo::Context => quote! {ctx.clone(),},316			ArgInfo::Location => quote! {location,},317			ArgInfo::This => quote! {self,},318		});319320	let fields = attr.fields.iter().map(|field| {321		let name = &field.name;322		let ty = &field.ty;323		quote! {324			pub #name: #ty,325		}326	});327328	let name = &fun.sig.ident;329	let vis = &fun.vis;330	let static_ext = if attr.fields.is_empty() {331		quote! {332			impl #name {333				pub const INST: &'static dyn StaticBuiltin = &#name {};334			}335			impl StaticBuiltin for #name {}336		}337	} else {338		quote! {}339	};340	let static_derive_copy = if attr.fields.is_empty() {341		quote! {, Copy}342	} else {343		quote! {}344	};345346	Ok(quote! {347		#item348349		#[doc(hidden)]350		#[allow(non_camel_case_types)]351		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]352		#vis struct #name {353			#(#fields)*354		}355		const _: () = {356			use ::jrsonnet_evaluator::{357				State, Val,358				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam}, CallLocation, ArgsLike, parse::parse_builtin_call},359				error::Result, Context, typed::Typed,360				parser::ExprLocation,361			};362			const PARAMS: &'static [BuiltinParam] = &[363				#(#params_desc)*364			];365366			#static_ext367			impl Builtin for #name368			where369				Self: 'static370			{371				fn name(&self) -> &str {372					stringify!(#name)373				}374				fn params(&self) -> &[BuiltinParam] {375					PARAMS376				}377				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {378					let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;379380					let result: #result = #name(#(#pass)*);381					<_ as Typed>::into_result(result)382				}383			}384		};385	})386}387388#[derive(Default)]389struct TypedAttr {390	rename: Option<String>,391	flatten: bool,392	/// flatten(ok) strategy for flattened optionals393	/// field would be None in case of any parsing error (as in serde)394	flatten_ok: bool,395}396impl Parse for TypedAttr {397	fn parse(input: ParseStream) -> syn::Result<Self> {398		let mut out = Self::default();399		loop {400			let lookahead = input.lookahead1();401			if lookahead.peek(kw::rename) {402				input.parse::<kw::rename>()?;403				input.parse::<Token![=]>()?;404				let name = input.parse::<LitStr>()?;405				if out.rename.is_some() {406					return Err(Error::new(407						name.span(),408						"rename attribute may only be specified once",409					));410				}411				out.rename = Some(name.value());412			} else if lookahead.peek(kw::flatten) {413				input.parse::<kw::flatten>()?;414				out.flatten = true;415				if input.peek(token::Paren) {416					let content;417					parenthesized!(content in input);418					let lookahead = content.lookahead1();419					if lookahead.peek(kw::ok) {420						content.parse::<kw::ok>()?;421						out.flatten_ok = true;422					} else {423						return Err(lookahead.error());424					}425				}426			} else if input.is_empty() {427				break;428			} else {429				return Err(lookahead.error());430			}431			if input.peek(Token![,]) {432				input.parse::<Token![,]>()?;433			} else {434				break;435			}436		}437		Ok(out)438	}439}440441struct TypedField {442	attr: TypedAttr,443	ident: Ident,444	ty: Type,445	is_option: bool,446}447impl TypedField {448	fn parse(field: &syn::Field) -> Result<Self> {449		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();450		let Some(ident) = field.ident.clone() else {451			return Err(Error::new(452				field.span(),453				"this field should appear in output object, but it has no visible name",454			));455		};456		let (is_option, ty) = if let Some(ty) = extract_type_from_option(&field.ty)? {457			(true, ty.clone())458		} else {459			(false, field.ty.clone())460		};461		if is_option && attr.flatten {462			if !attr.flatten_ok {463				return Err(Error::new(464					field.span(),465					"strategy should be set when flattening Option",466				));467			}468		} else if attr.flatten_ok {469			return Err(Error::new(470				field.span(),471				"flatten(ok) is only useable on optional fields",472			));473		}474475		Ok(Self {476			attr,477			ident,478			ty,479			is_option,480		})481	}482	/// None if this field is flattened in jsonnet output483	fn name(&self) -> Option<String> {484		if self.attr.flatten {485			return None;486		}487		Some(488			self.attr489				.rename490				.clone()491				.unwrap_or_else(|| self.ident.to_string()),492		)493	}494495	fn expand_field(&self) -> Option<TokenStream> {496		if self.is_option {497			return None;498		}499		let name = self.name()?;500		let ty = &self.ty;501		Some(quote! {502			(#name, <#ty as Typed>::TYPE)503		})504	}505	fn expand_parse(&self) -> TokenStream {506		let ident = &self.ident;507		let ty = &self.ty;508		if self.attr.flatten {509			// optional flatten is handled in same way as serde510			return if self.is_option {511				quote! {512					#ident: <#ty as TypedObj>::parse(&obj).ok(),513				}514			} else {515				quote! {516					#ident: <#ty as TypedObj>::parse(&obj)?,517				}518			};519		};520521		let name = self.name().unwrap();522		let value = if self.is_option {523			quote! {524				if let Some(value) = obj.get(#name.into())? {525					Some(<#ty as Typed>::from_untyped(value)?)526				} else {527					None528				}529			}530		} else {531			quote! {532				<#ty as Typed>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?533			}534		};535536		quote! {537			#ident: #value,538		}539	}540	fn expand_serialize(&self) -> Result<TokenStream> {541		let ident = &self.ident;542		let ty = &self.ty;543		Ok(if let Some(name) = self.name() {544			if self.is_option {545				quote! {546					if let Some(value) = self.#ident {547						out.member(#name.into()).value(<#ty as Typed>::into_untyped(value)?)?;548					}549				}550			} else {551				quote! {552					out.member(#name.into()).value(<#ty as Typed>::into_untyped(self.#ident)?)?;553				}554			}555		} else if self.is_option {556			quote! {557				if let Some(value) = self.#ident {558					<#ty as TypedObj>::serialize(value, out)?;559				}560			}561		} else {562			quote! {563				<#ty as TypedObj>::serialize(self.#ident, out)?;564			}565		})566	}567}568569#[proc_macro_derive(Typed, attributes(typed))]570pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {571	let input = parse_macro_input!(item as DeriveInput);572573	match derive_typed_inner(input) {574		Ok(v) => v.into(),575		Err(e) => e.to_compile_error().into(),576	}577}578579fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {580	let syn::Data::Struct(data) = &input.data else {581		return Err(Error::new(input.span(), "only structs supported"));582	};583584	let ident = &input.ident;585	let fields = data586		.fields587		.iter()588		.map(TypedField::parse)589		.collect::<Result<Vec<_>>>()?;590591	let typed = {592		let fields = fields593			.iter()594			.flat_map(TypedField::expand_field)595			.collect::<Vec<_>>();596		let len = fields.len();597		quote! {598			const ITEMS: [(&'static str, &'static ComplexValType); #len] = [599				#(#fields,)*600			];601			impl Typed for #ident {602				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&ITEMS);603604				fn from_untyped(value: Val) -> Result<Self> {605					let obj = value.as_obj().expect("shape is correct");606					Self::parse(&obj)607				}608609				fn into_untyped(value: Self) -> Result<Val> {610					let mut out = ObjValueBuilder::new();611					value.serialize(&mut out)?;612					Ok(Val::Obj(out.build()))613				}614615			}616		}617	};618619	let fields_parse = fields.iter().map(TypedField::expand_parse);620	let fields_serialize = fields621		.iter()622		.map(TypedField::expand_serialize)623		.collect::<Result<Vec<_>>>()?;624625	Ok(quote! {626		const _: () = {627			use ::jrsonnet_evaluator::{628				typed::{ComplexValType, Typed, TypedObj, CheckType},629				Val, State,630				error::{ErrorKind, Result as JrResult},631				ObjValueBuilder, ObjValue,632			};633634			#typed635636			impl TypedObj for #ident {637				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {638					#(#fields_serialize)*639640					Ok(())641				}642				fn parse(obj: &ObjValue) -> JrResult<Self> {643					Ok(Self {644						#(#fields_parse)*645					})646				}647			}648		};649	})650}
after · crates/jrsonnet-macros/src/lib.rs
1use proc_macro2::TokenStream;2use quote::quote;3use syn::{4	parenthesized,5	parse::{Parse, ParseStream},6	parse_macro_input,7	punctuated::Punctuated,8	spanned::Spanned,9	token::{self, Comma},10	Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, Path,11	PathArguments, Result, ReturnType, Token, Type,12};1314fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>15where16	Ident: PartialEq<I>,17{18	let attrs = attrs19		.iter()20		.filter(|a| a.path.is_ident(&ident))21		.collect::<Vec<_>>();22	if attrs.len() > 1 {23		return Err(Error::new(24			attrs[1].span(),25			"this attribute may be specified only once",26		));27	} else if attrs.is_empty() {28		return Ok(None);29	}30	let attr = attrs[0];31	let attr = attr.parse_args::<A>()?;3233	Ok(Some(attr))34}3536fn path_is(path: &Path, needed: &str) -> bool {37	path.leading_colon.is_none()38		&& !path.segments.is_empty()39		&& path.segments.iter().last().unwrap().ident == needed40}4142fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {43	match ty {44		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {45			let args = &path.path.segments.iter().last().unwrap().arguments;46			Some(args)47		}48		_ => None,49	}50}5152fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {53	let Some(args) = type_is_path(ty, "Option") else {54		return Ok(None)55	};56	// It should have only on angle-bracketed param ("<String>"):57	let PathArguments::AngleBracketed(params) = args else {58		return Err(Error::new(args.span(), "missing option generic"));59	};60	let generic_arg = params.args.iter().next().unwrap();61	// This argument must be a type:62	let GenericArgument::Type(ty) = generic_arg else {63		return Err(Error::new(64			generic_arg.span(),65			"option generic should be a type",66		))67	};68	Ok(Some(ty))69}7071struct Field {72	name: Ident,73	_colon: Token![:],74	ty: Type,75}76impl Parse for Field {77	fn parse(input: ParseStream) -> syn::Result<Self> {78		Ok(Self {79			name: input.parse()?,80			_colon: input.parse()?,81			ty: input.parse()?,82		})83	}84}8586mod kw {87	syn::custom_keyword!(fields);88	syn::custom_keyword!(rename);89	syn::custom_keyword!(flatten);90	syn::custom_keyword!(ok);91}9293struct EmptyAttr;94impl Parse for EmptyAttr {95	fn parse(_input: ParseStream) -> Result<Self> {96		Ok(Self)97	}98}99100struct BuiltinAttrs {101	fields: Vec<Field>,102}103impl Parse for BuiltinAttrs {104	fn parse(input: ParseStream) -> syn::Result<Self> {105		if input.is_empty() {106			return Ok(Self { fields: Vec::new() });107		}108		input.parse::<kw::fields>()?;109		let fields;110		parenthesized!(fields in input);111		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;112		Ok(Self {113			fields: p.into_iter().collect(),114		})115	}116}117118enum ArgInfo {119	Normal {120		ty: Box<Type>,121		is_option: bool,122		name: Option<String>,123		cfg_attrs: Vec<Attribute>,124	},125	Lazy {126		is_option: bool,127		name: Option<String>,128	},129	Context,130	Location,131	This,132}133134impl ArgInfo {135	fn parse(name: &str, arg: &FnArg) -> Result<Self> {136		let FnArg::Typed(arg) = arg else {137			unreachable!()138		};139		let ident = match &arg.pat as &Pat {140			Pat::Ident(i) => Some(i.ident.clone()),141			_ => None,142		};143		let ty = &arg.ty;144		if type_is_path(ty, "Context").is_some() {145			return Ok(Self::Context);146		} else if type_is_path(ty, "CallLocation").is_some() {147			return Ok(Self::Location);148		} else if type_is_path(ty, "Thunk").is_some() {149			return Ok(Self::Lazy {150				is_option: false,151				name: ident.map(|v| v.to_string()),152			});153		}154155		match ty as &Type {156			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),157			_ => {}158		}159160		let (is_option, ty) = if let Some(ty) = extract_type_from_option(ty)? {161			if type_is_path(ty, "Thunk").is_some() {162				return Ok(Self::Lazy {163					is_option: true,164					name: ident.map(|v| v.to_string()),165				});166			}167168			(true, Box::new(ty.clone()))169		} else {170			(false, ty.clone())171		};172173		let cfg_attrs = arg174			.attrs175			.iter()176			.filter(|a| a.path.is_ident("cfg"))177			.cloned()178			.collect();179180		Ok(Self::Normal {181			ty,182			is_option,183			name: ident.map(|v| v.to_string()),184			cfg_attrs,185		})186	}187}188189#[proc_macro_attribute]190pub fn builtin(191	attr: proc_macro::TokenStream,192	item: proc_macro::TokenStream,193) -> proc_macro::TokenStream {194	let attr = parse_macro_input!(attr as BuiltinAttrs);195	let item_fn = item.clone();196	let item_fn: ItemFn = parse_macro_input!(item_fn);197198	match builtin_inner(attr, item_fn, item.into()) {199		Ok(v) => v.into(),200		Err(e) => e.into_compile_error().into(),201	}202}203204fn builtin_inner(205	attr: BuiltinAttrs,206	fun: ItemFn,207	item: proc_macro2::TokenStream,208) -> syn::Result<TokenStream> {209	let ReturnType::Type(_, result) = &fun.sig.output else {210		return Err(Error::new(211			fun.sig.span(),212			"builtin should return something",213		))214	};215216	let name = fun.sig.ident.to_string();217	let args = fun218		.sig219		.inputs220		.iter()221		.map(|arg| ArgInfo::parse(&name, arg))222		.collect::<Result<Vec<_>>>()?;223224	let params_desc = args.iter().flat_map(|a| match a {225		ArgInfo::Normal {226			is_option,227			name,228			cfg_attrs,229			..230		} => {231			let name = name232				.as_ref()233				.map(|n| quote! {Some(std::borrow::Cow::Borrowed(#n))})234				.unwrap_or_else(|| quote! {None});235			Some(quote! {236				#(#cfg_attrs)*237				BuiltinParam {238					name: #name,239					has_default: #is_option,240				},241			})242		}243		ArgInfo::Lazy { is_option, name } => {244			let name = name245				.as_ref()246				.map(|n| quote! {Some(std::borrow::Cow::Borrowed(#n))})247				.unwrap_or_else(|| quote! {None});248			Some(quote! {249				BuiltinParam {250					name: #name,251					has_default: #is_option,252				},253			})254		}255		ArgInfo::Context => None,256		ArgInfo::Location => None,257		ArgInfo::This => None,258	});259260	let mut id = 0usize;261	let pass = args262		.iter()263		.map(|a| match a {264			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {265				let cid = id;266				id += 1;267				(quote! {#cid}, a)268			}269			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {270				(quote! {compile_error!("should not use id")}, a)271			}272		})273		.map(|(id, a)| match a {274			ArgInfo::Normal {275				ty,276				is_option,277				name,278				cfg_attrs,279			} => {280				let name = name.as_ref().map(|v| v.as_str()).unwrap_or("<unnamed>");281				let eval = quote! {jrsonnet_evaluator::State::push_description(282					|| format!("argument <{}> evaluation", #name),283					|| <#ty>::from_untyped(value.evaluate()?),284				)?};285				let value = if *is_option {286					quote! {if let Some(value) = &parsed[#id] {287						Some(#eval)288					} else {289						None290					},}291				} else {292					quote! {{293						let value = parsed[#id].as_ref().expect("args shape is checked");294						#eval295					},}296				};297				quote! {298					#(#cfg_attrs)*299					#value300				}301			}302			ArgInfo::Lazy { is_option, .. } => {303				if *is_option {304					quote! {if let Some(value) = &parsed[#id] {305						Some(value.clone())306					} else {307						None308					}}309				} else {310					quote! {311						parsed[#id].as_ref().expect("args shape is correct").clone(),312					}313				}314			}315			ArgInfo::Context => quote! {ctx.clone(),},316			ArgInfo::Location => quote! {location,},317			ArgInfo::This => quote! {self,},318		});319320	let fields = attr.fields.iter().map(|field| {321		let name = &field.name;322		let ty = &field.ty;323		quote! {324			pub #name: #ty,325		}326	});327328	let name = &fun.sig.ident;329	let vis = &fun.vis;330	let static_ext = if attr.fields.is_empty() {331		quote! {332			impl #name {333				pub const INST: &'static dyn StaticBuiltin = &#name {};334			}335			impl StaticBuiltin for #name {}336		}337	} else {338		quote! {}339	};340	let static_derive_copy = if attr.fields.is_empty() {341		quote! {, Copy}342	} else {343		quote! {}344	};345346	Ok(quote! {347		#item348349		#[doc(hidden)]350		#[allow(non_camel_case_types)]351		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]352		#vis struct #name {353			#(#fields)*354		}355		const _: () = {356			use ::jrsonnet_evaluator::{357				State, Val,358				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam}, CallLocation, ArgsLike, parse::parse_builtin_call},359				error::Result, Context, typed::Typed,360				parser::ExprLocation,361			};362			const PARAMS: &'static [BuiltinParam] = &[363				#(#params_desc)*364			];365366			#static_ext367			impl Builtin for #name368			where369				Self: 'static370			{371				fn name(&self) -> &str {372					stringify!(#name)373				}374				fn params(&self) -> &[BuiltinParam] {375					PARAMS376				}377				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {378					let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;379380					let result: #result = #name(#(#pass)*);381					<_ as Typed>::into_result(result)382				}383				fn as_any(&self) -> &dyn ::std::any::Any {384					self385				}386			}387		};388	})389}390391#[derive(Default)]392struct TypedAttr {393	rename: Option<String>,394	flatten: bool,395	/// flatten(ok) strategy for flattened optionals396	/// field would be None in case of any parsing error (as in serde)397	flatten_ok: bool,398}399impl Parse for TypedAttr {400	fn parse(input: ParseStream) -> syn::Result<Self> {401		let mut out = Self::default();402		loop {403			let lookahead = input.lookahead1();404			if lookahead.peek(kw::rename) {405				input.parse::<kw::rename>()?;406				input.parse::<Token![=]>()?;407				let name = input.parse::<LitStr>()?;408				if out.rename.is_some() {409					return Err(Error::new(410						name.span(),411						"rename attribute may only be specified once",412					));413				}414				out.rename = Some(name.value());415			} else if lookahead.peek(kw::flatten) {416				input.parse::<kw::flatten>()?;417				out.flatten = true;418				if input.peek(token::Paren) {419					let content;420					parenthesized!(content in input);421					let lookahead = content.lookahead1();422					if lookahead.peek(kw::ok) {423						content.parse::<kw::ok>()?;424						out.flatten_ok = true;425					} else {426						return Err(lookahead.error());427					}428				}429			} else if input.is_empty() {430				break;431			} else {432				return Err(lookahead.error());433			}434			if input.peek(Token![,]) {435				input.parse::<Token![,]>()?;436			} else {437				break;438			}439		}440		Ok(out)441	}442}443444struct TypedField {445	attr: TypedAttr,446	ident: Ident,447	ty: Type,448	is_option: bool,449}450impl TypedField {451	fn parse(field: &syn::Field) -> Result<Self> {452		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();453		let Some(ident) = field.ident.clone() else {454			return Err(Error::new(455				field.span(),456				"this field should appear in output object, but it has no visible name",457			));458		};459		let (is_option, ty) = if let Some(ty) = extract_type_from_option(&field.ty)? {460			(true, ty.clone())461		} else {462			(false, field.ty.clone())463		};464		if is_option && attr.flatten {465			if !attr.flatten_ok {466				return Err(Error::new(467					field.span(),468					"strategy should be set when flattening Option",469				));470			}471		} else if attr.flatten_ok {472			return Err(Error::new(473				field.span(),474				"flatten(ok) is only useable on optional fields",475			));476		}477478		Ok(Self {479			attr,480			ident,481			ty,482			is_option,483		})484	}485	/// None if this field is flattened in jsonnet output486	fn name(&self) -> Option<String> {487		if self.attr.flatten {488			return None;489		}490		Some(491			self.attr492				.rename493				.clone()494				.unwrap_or_else(|| self.ident.to_string()),495		)496	}497498	fn expand_field(&self) -> Option<TokenStream> {499		if self.is_option {500			return None;501		}502		let name = self.name()?;503		let ty = &self.ty;504		Some(quote! {505			(#name, <#ty as Typed>::TYPE)506		})507	}508	fn expand_parse(&self) -> TokenStream {509		let ident = &self.ident;510		let ty = &self.ty;511		if self.attr.flatten {512			// optional flatten is handled in same way as serde513			return if self.is_option {514				quote! {515					#ident: <#ty as TypedObj>::parse(&obj).ok(),516				}517			} else {518				quote! {519					#ident: <#ty as TypedObj>::parse(&obj)?,520				}521			};522		};523524		let name = self.name().unwrap();525		let value = if self.is_option {526			quote! {527				if let Some(value) = obj.get(#name.into())? {528					Some(<#ty as Typed>::from_untyped(value)?)529				} else {530					None531				}532			}533		} else {534			quote! {535				<#ty as Typed>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?536			}537		};538539		quote! {540			#ident: #value,541		}542	}543	fn expand_serialize(&self) -> Result<TokenStream> {544		let ident = &self.ident;545		let ty = &self.ty;546		Ok(if let Some(name) = self.name() {547			if self.is_option {548				quote! {549					if let Some(value) = self.#ident {550						out.member(#name.into()).value(<#ty as Typed>::into_untyped(value)?)?;551					}552				}553			} else {554				quote! {555					out.member(#name.into()).value(<#ty as Typed>::into_untyped(self.#ident)?)?;556				}557			}558		} else if self.is_option {559			quote! {560				if let Some(value) = self.#ident {561					<#ty as TypedObj>::serialize(value, out)?;562				}563			}564		} else {565			quote! {566				<#ty as TypedObj>::serialize(self.#ident, out)?;567			}568		})569	}570}571572#[proc_macro_derive(Typed, attributes(typed))]573pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {574	let input = parse_macro_input!(item as DeriveInput);575576	match derive_typed_inner(input) {577		Ok(v) => v.into(),578		Err(e) => e.to_compile_error().into(),579	}580}581582fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {583	let syn::Data::Struct(data) = &input.data else {584		return Err(Error::new(input.span(), "only structs supported"));585	};586587	let ident = &input.ident;588	let fields = data589		.fields590		.iter()591		.map(TypedField::parse)592		.collect::<Result<Vec<_>>>()?;593594	let typed = {595		let fields = fields596			.iter()597			.flat_map(TypedField::expand_field)598			.collect::<Vec<_>>();599		let len = fields.len();600		quote! {601			const ITEMS: [(&'static str, &'static ComplexValType); #len] = [602				#(#fields,)*603			];604			impl Typed for #ident {605				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&ITEMS);606607				fn from_untyped(value: Val) -> Result<Self> {608					let obj = value.as_obj().expect("shape is correct");609					Self::parse(&obj)610				}611612				fn into_untyped(value: Self) -> Result<Val> {613					let mut out = ObjValueBuilder::new();614					value.serialize(&mut out)?;615					Ok(Val::Obj(out.build()))616				}617618			}619		}620	};621622	let fields_parse = fields.iter().map(TypedField::expand_parse);623	let fields_serialize = fields624		.iter()625		.map(TypedField::expand_serialize)626		.collect::<Result<Vec<_>>>()?;627628	Ok(quote! {629		const _: () = {630			use ::jrsonnet_evaluator::{631				typed::{ComplexValType, Typed, TypedObj, CheckType},632				Val, State,633				error::{ErrorKind, Result as JrResult},634				ObjValueBuilder, ObjValue,635			};636637			#typed638639			impl TypedObj for #ident {640				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {641					#(#fields_serialize)*642643					Ok(())644				}645				fn parse(obj: &ObjValue) -> JrResult<Self> {646					Ok(Self {647						#(#fields_parse)*648					})649				}650			}651		};652	})653}