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.rsdiffbeforeafterboth13 LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,13 LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,14};14};1516use self::typed::derive_typed_inner;1718mod typed;19mod names;152016fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>21fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>17where22where437 })442 })438}443}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}711444712#[proc_macro_derive(Typed, attributes(typed))]445#[proc_macro_derive(Typed, attributes(typed))]713pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {446pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {719 }452 }720}453}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}794454795struct FormatInput {455struct FormatInput {796 formatting: LitStr,456 formatting: LitStr,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)