difftreelog
feat macro name interning
in: master
9 files changed
cmds/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"]
crates/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()
}
}
+
crates/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 {
crates/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`]
crates/jrsonnet-interner/src/names.rsdiffbeforeafterbothno changes
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth1use 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};1516fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>17where18 Ident: PartialEq<I>,19{20 let attrs = attrs21 .iter()22 .filter(|a| a.path().is_ident(&ident))23 .collect::<Vec<_>>();24 if attrs.len() > 1 {25 return Err(Error::new(26 attrs[1].span(),27 "this attribute may be specified only once",28 ));29 } else if attrs.is_empty() {30 return Ok(false);31 }32 let attr = attrs[0];3334 match attr.meta {35 Meta::Path(_) => Ok(true),36 _ => Ok(false),37 }38}39fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>40where41 Ident: PartialEq<I>,42{43 let attrs = attrs44 .iter()45 .filter(|a| a.path().is_ident(&ident))46 .collect::<Vec<_>>();47 if attrs.len() > 1 {48 return Err(Error::new(49 attrs[1].span(),50 "this attribute may be specified only once",51 ));52 } else if attrs.is_empty() {53 return Ok(None);54 }55 let attr = attrs[0];56 let attr = attr.parse_args::<A>()?;5758 Ok(Some(attr))59}60fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)61where62 Ident: PartialEq<I>,63{64 attrs.retain(|a| !a.path().is_ident(&ident));65}6667fn path_is(path: &Path, needed: &str) -> bool {68 path.leading_colon.is_none()69 && !path.segments.is_empty()70 && path.segments.iter().last().unwrap().ident == needed71}7273fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {74 match ty {75 Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {76 let args = &path.path.segments.iter().last().unwrap().arguments;77 Some(args)78 }79 _ => None,80 }81}8283fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {84 let Some(args) = type_is_path(ty, "Option") else {85 return Ok(None);86 };87 // It should have only on angle-bracketed param ("<String>"):88 let PathArguments::AngleBracketed(params) = args else {89 return Err(Error::new(args.span(), "missing option generic"));90 };91 let generic_arg = params.args.iter().next().unwrap();92 // This argument must be a type:93 let GenericArgument::Type(ty) = generic_arg else {94 return Err(Error::new(95 generic_arg.span(),96 "option generic should be a type",97 ));98 };99 Ok(Some(ty))100}101102struct Field {103 attrs: Vec<Attribute>,104 name: Ident,105 _colon: Token![:],106 ty: Type,107}108impl Parse for Field {109 fn parse(input: ParseStream) -> syn::Result<Self> {110 Ok(Self {111 attrs: input.call(Attribute::parse_outer)?,112 name: input.parse()?,113 _colon: input.parse()?,114 ty: input.parse()?,115 })116 }117}118119mod kw {120 syn::custom_keyword!(fields);121 syn::custom_keyword!(rename);122 syn::custom_keyword!(alias);123 syn::custom_keyword!(flatten);124 syn::custom_keyword!(add);125 syn::custom_keyword!(hide);126 syn::custom_keyword!(ok);127}128129struct BuiltinAttrs {130 fields: Vec<Field>,131}132impl Parse for BuiltinAttrs {133 fn parse(input: ParseStream) -> syn::Result<Self> {134 if input.is_empty() {135 return Ok(Self { fields: Vec::new() });136 }137 input.parse::<kw::fields>()?;138 let fields;139 parenthesized!(fields in input);140 let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;141 Ok(Self {142 fields: p.into_iter().collect(),143 })144 }145}146147enum Optionality {148 Required,149 Optional,150 Default(Expr),151 TypeDefault,152}153154#[allow(155 clippy::large_enum_variant,156 reason = "this macro is not that hot for it to matter"157)]158enum ArgInfo {159 Normal {160 ty: Box<Type>,161 optionality: Optionality,162 name: Option<String>,163 cfg_attrs: Vec<Attribute>,164 },165 Lazy {166 is_option: bool,167 name: Option<String>,168 },169 Context,170 Location,171 This,172}173174impl ArgInfo {175 fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {176 let FnArg::Typed(arg) = arg else {177 unreachable!()178 };179 let ident = match &arg.pat as &Pat {180 Pat::Ident(i) => Some(i.ident.clone()),181 _ => None,182 };183 let ty = &arg.ty;184 if type_is_path(ty, "Context").is_some() {185 return Ok(Self::Context);186 } else if type_is_path(ty, "CallLocation").is_some() {187 return Ok(Self::Location);188 } else if type_is_path(ty, "Thunk").is_some() {189 return Ok(Self::Lazy {190 is_option: false,191 name: ident.map(|v| v.to_string()),192 });193 }194195 match ty as &Type {196 Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),197 _ => {}198 }199200 let (optionality, ty) = if try_parse_attr_noargs(&mut arg.attrs, "default")? {201 remove_attr(&mut arg.attrs, "default");202 (Optionality::TypeDefault, ty.clone())203 } else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {204 remove_attr(&mut arg.attrs, "default");205 (Optionality::Default(default), ty.clone())206 } else if let Some(ty) = extract_type_from_option(ty)? {207 if type_is_path(ty, "Thunk").is_some() {208 return Ok(Self::Lazy {209 is_option: true,210 name: ident.map(|v| v.to_string()),211 });212 }213214 (Optionality::Optional, Box::new(ty.clone()))215 } else {216 (Optionality::Required, ty.clone())217 };218219 let cfg_attrs = arg220 .attrs221 .iter()222 .filter(|a| a.path().is_ident("cfg"))223 .cloned()224 .collect();225226 Ok(Self::Normal {227 ty,228 optionality,229 name: ident.map(|v| v.to_string()),230 cfg_attrs,231 })232 }233}234235#[proc_macro_attribute]236pub fn builtin(237 attr: proc_macro::TokenStream,238 item: proc_macro::TokenStream,239) -> proc_macro::TokenStream {240 let attr = parse_macro_input!(attr as BuiltinAttrs);241 let item_fn = parse_macro_input!(item as ItemFn);242243 match builtin_inner(attr, item_fn) {244 Ok(v) => v.into(),245 Err(e) => e.into_compile_error().into(),246 }247}248249#[allow(clippy::too_many_lines)]250fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {251 let ReturnType::Type(_, result) = &fun.sig.output else {252 return Err(Error::new(253 fun.sig.span(),254 "builtin should return something",255 ));256 };257258 let name = fun.sig.ident.to_string();259 let args = fun260 .sig261 .inputs262 .iter_mut()263 .map(|arg| ArgInfo::parse(&name, arg))264 .collect::<Result<Vec<_>>>()?;265266 let params_desc = args.iter().filter_map(|a| match a {267 ArgInfo::Normal {268 optionality,269 name,270 cfg_attrs,271 ..272 } => {273 let name = name274 .as_ref()275 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});276 let default = match optionality {277 Optionality::Required => quote!(ParamDefault::None),278 Optionality::Optional | Optionality::TypeDefault => quote!(ParamDefault::Exists),279 Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),280 };281 Some(quote! {282 #(#cfg_attrs)*283 [#name => #default],284 })285 }286 ArgInfo::Lazy { is_option, name } => {287 let name = name288 .as_ref()289 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});290 Some(quote! {291 [#name => ParamDefault::exists(#is_option)],292 })293 }294 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,295 });296297 let mut id = 0usize;298 let pass = args299 .iter()300 .map(|a| match a {301 ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {302 let cid = id;303 id += 1;304 (quote! {#cid}, a)305 }306 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {307 (quote! {compile_error!("should not use id")}, a)308 }309 })310 .map(|(id, a)| match a {311 ArgInfo::Normal {312 ty,313 optionality,314 name,315 cfg_attrs,316 } => {317 let name = name.as_ref().map_or("<unnamed>", String::as_str);318 let eval = quote! {jrsonnet_evaluator::in_description_frame(319 || format!("argument <{}> evaluation", #name),320 || <#ty>::from_untyped(value.evaluate()?),321 )?};322 let value = match optionality {323 Optionality::Required => quote! {{324 let value = parsed[#id].as_ref().expect("args shape is checked");325 #eval326 },},327 Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {328 Some(#eval)329 } else {330 None331 },},332 Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {333 #eval334 } else {335 let v: #ty = #expr;336 v337 },},338 Optionality::TypeDefault => quote! {if let Some(value) = &parsed[#id] {339 #eval340 } else {341 let v: #ty = Default::default();342 v343 },},344 };345 quote! {346 #(#cfg_attrs)*347 #value348 }349 }350 ArgInfo::Lazy { is_option, .. } => {351 if *is_option {352 quote! {if let Some(value) = &parsed[#id] {353 Some(value.clone())354 } else {355 None356 },}357 } else {358 quote! {359 parsed[#id].as_ref().expect("args shape is correct").clone(),360 }361 }362 }363 ArgInfo::Context => quote! {ctx.clone(),},364 ArgInfo::Location => quote! {location,},365 ArgInfo::This => quote! {self,},366 });367368 let fields = attr.fields.iter().map(|field| {369 let attrs = &field.attrs;370 let name = &field.name;371 let ty = &field.ty;372 quote! {373 #(#attrs)*374 pub #name: #ty,375 }376 });377378 let name = &fun.sig.ident;379 let vis = &fun.vis;380 let static_ext = if attr.fields.is_empty() {381 quote! {382 impl #name {383 pub const INST: &'static dyn StaticBuiltin = &#name {};384 }385 impl StaticBuiltin for #name {}386 }387 } else {388 quote! {}389 };390 let static_derive_copy = if attr.fields.is_empty() {391 quote! {, Copy}392 } else {393 quote! {}394 };395396 Ok(quote! {397 #fun398399 #[doc(hidden)]400 #[allow(non_camel_case_types)]401 #[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]402 #vis struct #name {403 #(#fields)*404 }405 const _: () = {406 use ::jrsonnet_evaluator::{407 State, Val,408 function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},409 Result, Context, typed::Typed,410 parser::Span, params, Thunk,411 };412 params!(413 #(#params_desc)*414 );415416 #static_ext417 impl Builtin for #name418 where419 Self: 'static420 {421 fn name(&self) -> &str {422 stringify!(#name)423 }424 fn params(&self) -> FunctionSignature {425 PARAMS.with(|p| p.clone())426 }427 #[allow(unused_variables)]428 fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {429 let result: #result = #name(#(#pass)*);430 <_ as Typed>::into_result(result)431 }432 fn as_any(&self) -> &dyn ::std::any::Any {433 self434 }435 }436 };437 })438}439440#[derive(Default)]441#[allow(clippy::struct_excessive_bools)]442struct TypedAttr {443 rename: Option<String>,444 aliases: Vec<String>,445 flatten: bool,446 /// flatten(ok) strategy for flattened optionals447 /// field would be None in case of any parsing error (as in serde)448 flatten_ok: bool,449 // Should it be `field+:` instead of `field:`450 add: bool,451 // Should it be `field::` instead of `field:`452 hide: bool,453}454impl Parse for TypedAttr {455 fn parse(input: ParseStream) -> syn::Result<Self> {456 let mut out = Self::default();457 loop {458 let lookahead = input.lookahead1();459 if lookahead.peek(kw::rename) {460 input.parse::<kw::rename>()?;461 input.parse::<Token![=]>()?;462 let name = input.parse::<LitStr>()?;463 if out.rename.is_some() {464 return Err(Error::new(465 name.span(),466 "rename attribute may only be specified once",467 ));468 }469 out.rename = Some(name.value());470 } else if lookahead.peek(kw::alias) {471 input.parse::<kw::alias>()?;472 input.parse::<Token![=]>()?;473 let alias = input.parse::<LitStr>()?;474 out.aliases.push(alias.value());475 } else if lookahead.peek(kw::flatten) {476 input.parse::<kw::flatten>()?;477 out.flatten = true;478 if input.peek(token::Paren) {479 let content;480 parenthesized!(content in input);481 let lookahead = content.lookahead1();482 if lookahead.peek(kw::ok) {483 content.parse::<kw::ok>()?;484 out.flatten_ok = true;485 } else {486 return Err(lookahead.error());487 }488 }489 } else if lookahead.peek(kw::add) {490 input.parse::<kw::add>()?;491 out.add = true;492 } else if lookahead.peek(kw::hide) {493 input.parse::<kw::hide>()?;494 out.hide = true;495 } else if input.is_empty() {496 break;497 } else {498 return Err(lookahead.error());499 }500 if input.peek(Token![,]) {501 input.parse::<Token![,]>()?;502 } else {503 break;504 }505 }506 Ok(out)507 }508}509510struct TypedField {511 attr: TypedAttr,512 ident: Ident,513 ty: Type,514 is_option: bool,515 is_lazy: bool,516}517impl TypedField {518 fn parse(field: &syn::Field) -> Result<Self> {519 let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();520 let Some(ident) = field.ident.clone() else {521 return Err(Error::new(522 field.span(),523 "this field should appear in output object, but it has no visible name",524 ));525 };526 let (is_option, ty) = extract_type_from_option(&field.ty)?527 .map_or_else(|| (false, field.ty.clone()), |ty| (true, ty.clone()));528 if is_option && attr.flatten {529 if !attr.flatten_ok {530 return Err(Error::new(531 field.span(),532 "strategy should be set when flattening Option",533 ));534 }535 } else if attr.flatten_ok {536 return Err(Error::new(537 field.span(),538 "flatten(ok) is only useable on optional fields",539 ));540 }541542 let is_lazy = type_is_path(&ty, "Thunk").is_some();543544 Ok(Self {545 attr,546 ident,547 ty,548 is_option,549 is_lazy,550 })551 }552 /// None if this field is flattened in jsonnet output553 fn name(&self) -> Option<String> {554 if self.attr.flatten {555 return None;556 }557 Some(558 self.attr559 .rename560 .clone()561 .unwrap_or_else(|| self.ident.to_string()),562 )563 }564565 fn expand_field(&self) -> Option<TokenStream> {566 if self.is_option {567 return None;568 }569 let name = self.name()?;570 let ty = &self.ty;571 Some(quote! {572 (#name, <#ty as Typed>::TYPE)573 })574 }575576 fn expand_parse(&self) -> TokenStream {577 if self.is_option {578 self.expand_parse_optional()579 } else {580 self.expand_parse_mandatory()581 }582 }583584 fn expand_parse_optional(&self) -> TokenStream {585 let ident = &self.ident;586 let ty = &self.ty;587588 // optional flatten is handled in same way as serde589 if self.attr.flatten {590 return quote! {591 #ident: <#ty as TypedObj>::parse(&obj).ok(),592 };593 }594595 let name = self.name().unwrap();596 let aliases = &self.attr.aliases;597598 quote! {599 #ident: {600 let __value = if let Some(__v) = obj.get(#name.into())? {601 Some(__v)602 } #(else if let Some(__v) = obj.get(#aliases.into())? {603 Some(__v)604 })* else {605 None606 };607608 __value.map(<#ty as Typed>::from_untyped).transpose()?609 },610 }611 }612613 fn expand_parse_mandatory(&self) -> TokenStream {614 let ident = &self.ident;615 let ty = &self.ty;616617 // optional flatten is handled in same way as serde618 if self.attr.flatten {619 return quote! {620 #ident: <#ty as TypedObj>::parse(&obj)?,621 };622 }623624 let name = self.name().unwrap();625 let aliases = &self.attr.aliases;626627 let error_text = if aliases.is_empty() {628 // clippy does not understand name variable usage in quote! macro629 #[allow(clippy::redundant_clone)]630 name.clone()631 } else {632 format!("{name} (alias {})", aliases.join(", "))633 };634635 quote! {636 #ident: {637 let __value = if let Some(__v) = obj.get(#name.into())? {638 __v639 } #(else if let Some(__v) = obj.get(#aliases.into())? {640 __v641 })* else {642 return Err(ErrorKind::NoSuchField(#error_text.into(), vec![]).into());643 };644645 <#ty as Typed>::from_untyped(__value)?646 },647 }648 }649650 fn expand_serialize(&self) -> TokenStream {651 let ident = &self.ident;652 let ty = &self.ty;653 self.name().map_or_else(654 || {655 if self.is_option {656 quote! {657 if let Some(value) = self.#ident {658 <#ty as TypedObj>::serialize(value, out)?;659 }660 }661 } else {662 quote! {663 <#ty as TypedObj>::serialize(self.#ident, out)?;664 }665 }666 },667 |name| {668 let hide = if self.attr.hide {669 quote! {.hide()}670 } else {671 quote! {}672 };673 let add = if self.attr.add {674 quote! {.add()}675 } else {676 quote! {}677 };678 let value = if self.is_lazy {679 quote! {680 out.field(#name)681 #hide682 #add683 .try_thunk(<#ty as Typed>::into_lazy_untyped(value))?;684 }685 } else {686 quote! {687 out.field(#name)688 #hide689 #add690 .try_value(<#ty as Typed>::into_untyped(value)?)?;691 }692 };693 if self.is_option {694 quote! {695 if let Some(value) = self.#ident {696 #value697 }698 }699 } else {700 quote! {701 {702 let value = self.#ident;703 #value704 }705 }706 }707 },708 )709 }710}711712#[proc_macro_derive(Typed, attributes(typed))]713pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {714 let input = parse_macro_input!(item as DeriveInput);715716 match derive_typed_inner(input) {717 Ok(v) => v.into(),718 Err(e) => e.to_compile_error().into(),719 }720}721722fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {723 let syn::Data::Struct(data) = &input.data else {724 return Err(Error::new(input.span(), "only structs supported"));725 };726727 let ident = &input.ident;728 let fields = data729 .fields730 .iter()731 .map(TypedField::parse)732 .collect::<Result<Vec<_>>>()?;733734 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();735736 let typed = {737 let fields = fields738 .iter()739 .filter_map(TypedField::expand_field)740 .collect::<Vec<_>>();741 quote! {742 impl #impl_generics Typed for #ident #ty_generics #where_clause {743 const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[744 #(#fields,)*745 ]);746747 fn from_untyped(value: Val) -> JrResult<Self> {748 let obj = value.as_obj().expect("shape is correct");749 Self::parse(&obj)750 }751752 fn into_untyped(value: Self) -> JrResult<Val> {753 let mut out = ObjValueBuilder::new();754 value.serialize(&mut out)?;755 Ok(Val::Obj(out.build()))756 }757758 }759 }760 };761762 let fields_parse = fields.iter().map(TypedField::expand_parse);763 let fields_serialize = fields764 .iter()765 .map(TypedField::expand_serialize)766 .collect::<Vec<_>>();767768 Ok(quote! {769 const _: () = {770 use ::jrsonnet_evaluator::{771 typed::{ComplexValType, Typed, TypedObj, CheckType},772 Val, State,773 error::{ErrorKind, Result as JrResult},774 ObjValueBuilder, ObjValue,775 };776777 #typed778779 impl #impl_generics TypedObj for #ident #ty_generics #where_clause {780 fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {781 #(#fields_serialize)*782783 Ok(())784 }785 fn parse(obj: &ObjValue) -> JrResult<Self> {786 Ok(Self {787 #(#fields_parse)*788 })789 }790 }791 };792 })793}794795struct FormatInput {796 formatting: LitStr,797 arguments: Vec<Expr>,798}799impl Parse for FormatInput {800 fn parse(input: ParseStream) -> Result<Self> {801 let formatting = input.parse()?;802 let mut arguments = Vec::new();803804 while input.peek(Token![,]) {805 input.parse::<Token![,]>()?;806 if input.is_empty() {807 // Trailing comma808 break;809 }810 let expr = input.parse()?;811 arguments.push(expr);812 }813814 if !input.is_empty() {815 return Err(syn::Error::new(input.span(), "unexpected trailing input"));816 }817818 Ok(Self {819 formatting,820 arguments,821 })822 }823}824fn is_format_str(i: &str) -> bool {825 let mut is_plain = true;826 // -1 = {827 // +1 = }828 let mut is_bracket = 0i8;829 for ele in i.chars() {830 match ele {831 '{' if is_bracket == -1 => {832 is_bracket = 0;833 }834 '}' if is_bracket == -1 => {835 is_plain = false;836 break;837 }838 '}' if is_bracket == 1 => {839 is_bracket = 0;840 }841 '{' if is_bracket == 1 => {842 is_plain = false;843 break;844 }845 '{' => {846 is_bracket = -1;847 }848 '}' => {849 is_bracket = 1;850 }851 _ if is_bracket != 0 => {852 is_plain = false;853 break;854 }855 _ => {}856 }857 }858 !is_plain || is_bracket != 0859}860impl FormatInput {861 fn expand(self) -> TokenStream {862 let format = self.formatting;863 if is_format_str(&format.value()) {864 let args = self.arguments;865 quote! {866 ::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))867 }868 } else {869 if let Some(first) = self.arguments.first() {870 return syn::Error::new(871 first.span(),872 "string has no formatting codes, it should not have the arguments",873 )874 .into_compile_error();875 }876 quote! {877 ::jrsonnet_evaluator::IStr::from(#format)878 }879 }880 }881}882883/// `IStr` formatting helper884///885/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`886/// This macro looks for formatting codes in the input string, and uses887/// `format!()` only when necessary888#[proc_macro]889pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {890 let input = parse_macro_input!(input as FormatInput);891 input.expand().into()892}893894/// Create Thunk using closure syntax895#[proc_macro]896#[allow(non_snake_case)]897pub fn Thunk(input: proc_macro::TokenStream) -> proc_macro::TokenStream {898 let input = parse_macro_input!(input as ExprClosure);899900 let span = input.inputs.span();901 let move_check = input.capture.is_none().then(|| {902 quote_spanned! {span => {903 compile_error!("Thunk! needs to be called with move closure");904 }}905 });906907 let (env, closure, args) = syn_dissect_closure::split_env(input);908909 let trace_check = args.iter().map(|el| {910 let span = el.span();911 quote_spanned! {span => ::jrsonnet_evaluator::gc::assert_trace(&#el);}912 });913914 quote! {{915 #move_check916 #(#trace_check)*917 ::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))918 }}.into()919}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}crates/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),)*
+ ];
+ }
+ }
+ }
+}
crates/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)*
+ }))
+ }
+ }
+ };
+ })
+}
crates/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(®ex, 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(®ex, str)