git.delta.rocks / jrsonnet / refs/commits / 4f26f96ee098

difftreelog

perf remove AST (de)serialization

Yaroslav Bolyukin2024-05-19parent: #0ae36ba.patch.diff
in: master

12 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -543,8 +543,6 @@
  "hashbrown 0.14.5",
  "jrsonnet-gcmodule",
  "rustc-hash",
- "serde",
- "structdump",
 ]
 
 [[package]]
@@ -563,9 +561,7 @@
  "jrsonnet-gcmodule",
  "jrsonnet-interner",
  "peg",
- "serde",
  "static_assertions",
- "structdump",
 ]
 
 [[package]]
@@ -586,7 +582,6 @@
 version = "0.5.0-pre96"
 dependencies = [
  "base64",
- "bincode",
  "jrsonnet-evaluator",
  "jrsonnet-gcmodule",
  "jrsonnet-macros",
@@ -602,7 +597,6 @@
  "sha1",
  "sha2",
  "sha3",
- "structdump",
 ]
 
 [[package]]
@@ -1102,28 +1096,6 @@
 version = "0.11.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
-
-[[package]]
-name = "structdump"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b0570327507bf281d8a6e6b0d4c082b12cb6bcee27efce755aa5efacd44076c1"
-dependencies = [
- "proc-macro2",
- "quote",
- "structdump-derive",
-]
-
-[[package]]
-name = "structdump-derive"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29cc0b59cfa11f1bceda09a9a7e37e6a6c3138575fd24ade8aa9af6d09aedf28"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
 
 [[package]]
 name = "syn"
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -79,7 +79,6 @@
 num-bigint = "0.4.5"
 derivative = "2.2.0"
 strsim = "0.11.0"
-structdump = "0.2.0"
 proc-macro2 = "1.0"
 quote = "1.0"
 syn = "2.0"
modifiedcrates/jrsonnet-interner/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-interner/Cargo.toml
+++ b/crates/jrsonnet-interner/Cargo.toml
@@ -10,20 +10,8 @@
 [lints]
 workspace = true
 
-[features]
-default = []
-# Implement value serialization using structdump
-structdump = ["dep:structdump"]
-# Implement value serialization using serde
-#
-# Warning: serialized values won't be deduplicated
-serde = ["dep:serde"]
-
 [dependencies]
 jrsonnet-gcmodule.workspace = true
-
-serde = { workspace = true, optional = true }
-structdump = { workspace = true, optional = true }
 
 rustc-hash.workspace = true
 hashbrown = { workspace = true, features = ["inline-more"] }
modifiedcrates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -219,45 +219,6 @@
 	}
 }
 
-#[cfg(feature = "serde")]
-impl serde::Serialize for IStr {
-	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
-	where
-		S: serde::Serializer,
-	{
-		self.as_str().serialize(serializer)
-	}
-}
-
-#[cfg(feature = "serde")]
-impl<'de> serde::Deserialize<'de> for IStr {
-	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
-	where
-		D: serde::Deserializer<'de>,
-	{
-		let str = <&str>::deserialize(deserializer)?;
-		Ok(intern_str(str))
-	}
-}
-
-#[cfg(feature = "structdump")]
-impl structdump::Codegen for IStr {
-	fn gen_code(
-		&self,
-		res: &mut structdump::CodegenResult,
-		_unique: bool,
-	) -> structdump::TokenStream {
-		let s: &str = self;
-		res.add_code(
-			structdump::quote! {
-				structdump_import::IStr::from(#s)
-			},
-			Some(structdump::quote![structdump_import::IStr]),
-			false,
-		)
-	}
-}
-
 thread_local! {
 	static POOL: RefCell<HashMap<Inner, (), BuildHasherDefault<FxHasher>>> = RefCell::new(HashMap::with_capacity_and_hasher(200, BuildHasherDefault::default()));
 }
modifiedcrates/jrsonnet-parser/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-parser/Cargo.toml
+++ b/crates/jrsonnet-parser/Cargo.toml
@@ -11,21 +11,6 @@
 default = []
 exp-destruct = []
 exp-null-coaelse = []
-# Implement serialization of AST using structdump
-#
-# Structdump generates code, which exactly replicated passed AST
-# Contrary to serde, has no code bloat problem, and is recommended
-#
-# The only limitation is serialized form is only useable if built from build script
-structdump = ["dep:structdump", "jrsonnet-interner/structdump"]
-# Implement serialization of AST using serde
-#
-# Warning: as serde doesn't deduplicate strings, `Source` struct will bloat
-# output binary with repeating source code. To resolve this issue, you should either
-# override serialization of this struct using custom `Serializer`/`Deserializer`,
-# not rely on Source, and fill its `source_code` with empty value, or use `structdump`
-# instead
-serde = ["dep:serde"]
 
 [dependencies]
 jrsonnet-interner.workspace = true
@@ -34,6 +19,3 @@
 static_assertions.workspace = true
 
 peg.workspace = true
-
-serde = { workspace = true, features = ["derive", "rc"], optional = true }
-structdump = { workspace = true, features = ["derive"], optional = true }
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -6,15 +6,9 @@
 
 use jrsonnet_gcmodule::Trace;
 use jrsonnet_interner::IStr;
-#[cfg(feature = "serde")]
-use serde::{Deserialize, Serialize};
-#[cfg(feature = "structdump")]
-use structdump::Codegen;
 
 use crate::source::Source;
 
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
-#[cfg_attr(feature = "structdump", derive(Codegen))]
 #[derive(Debug, PartialEq, Trace)]
 pub enum FieldName {
 	/// {fixed: 2}
@@ -23,8 +17,6 @@
 	Dyn(LocExpr),
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]
 #[repr(u8)]
 pub enum Visibility {
@@ -42,13 +34,9 @@
 	}
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Clone, Debug, PartialEq, Trace)]
 pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub struct FieldMember {
 	pub name: FieldName,
@@ -58,8 +46,6 @@
 	pub value: LocExpr,
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub enum Member {
 	Field(FieldMember),
@@ -67,8 +53,6 @@
 	AssertStmt(AssertStmt),
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]
 pub enum UnaryOpType {
 	Plus,
@@ -93,8 +77,6 @@
 	}
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]
 pub enum BinaryOpType {
 	Mul,
@@ -164,14 +146,10 @@
 }
 
 /// name, default value
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub struct Param(pub Destruct, pub Option<LocExpr>);
 
 /// Defined function parameters
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, Clone, PartialEq, Trace)]
 pub struct ParamsDesc(pub Rc<Vec<Param>>);
 
@@ -182,8 +160,6 @@
 	}
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub struct ArgsDesc {
 	pub unnamed: Vec<LocExpr>,
@@ -195,8 +171,6 @@
 	}
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, Clone, PartialEq, Eq, Trace)]
 pub enum DestructRest {
 	/// ...rest
@@ -205,8 +179,6 @@
 	Drop,
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, Clone, PartialEq, Trace)]
 pub enum Destruct {
 	Full(IStr),
@@ -268,8 +240,6 @@
 	}
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, Clone, PartialEq, Trace)]
 pub enum BindSpec {
 	Field {
@@ -291,26 +261,18 @@
 	}
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub struct IfSpecData(pub LocExpr);
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub struct ForSpecData(pub Destruct, pub LocExpr);
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub enum CompSpec {
 	IfSpec(IfSpecData),
 	ForSpec(ForSpecData),
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub struct ObjComp {
 	pub pre_locals: Vec<BindSpec>,
@@ -319,16 +281,12 @@
 	pub compspecs: Vec<CompSpec>,
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub enum ObjBody {
 	MemberList(Vec<Member>),
 	ObjComp(ObjComp),
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Eq, Clone, Copy, Trace)]
 pub enum LiteralType {
 	This,
@@ -339,8 +297,6 @@
 	False,
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub struct SliceDesc {
 	pub start: Option<LocExpr>,
@@ -349,8 +305,6 @@
 }
 
 /// Syntax base
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub enum Expr {
 	Literal(LiteralType),
@@ -420,8 +374,6 @@
 	Slice(LocExpr, SliceDesc),
 }
 
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 pub struct IndexPart {
 	pub value: LocExpr,
@@ -430,8 +382,6 @@
 }
 
 /// file, begin offset, end offset
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Clone, PartialEq, Eq, Trace)]
 #[trace(skip)]
 #[repr(C)]
@@ -452,8 +402,6 @@
 }
 
 /// Holds AST expression and its location in source file
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
-#[cfg_attr(feature = "structdump", derive(Codegen))]
 #[derive(Clone, PartialEq, Trace)]
 pub struct LocExpr(pub Rc<Expr>, pub ExprLocation);
 
modifiedcrates/jrsonnet-parser/src/source.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/source.rs
+++ b/crates/jrsonnet-parser/src/source.rs
@@ -8,10 +8,6 @@
 
 use jrsonnet_gcmodule::{Trace, Tracer};
 use jrsonnet_interner::{IBytes, IStr};
-#[cfg(feature = "serde")]
-use serde::{Deserialize, Serialize};
-#[cfg(feature = "structdump")]
-use structdump::Codegen;
 
 use crate::location::{location_to_offset, offset_to_location, CodeLocation};
 
@@ -130,31 +126,6 @@
 impl Default for SourcePath {
 	fn default() -> Self {
 		Self(Rc::new(SourceDefault))
-	}
-}
-
-#[cfg(feature = "structdump")]
-impl Codegen for SourcePath {
-	fn gen_code(
-		&self,
-		res: &mut structdump::CodegenResult,
-		unique: bool,
-	) -> structdump::TokenStream {
-		let source_virtual = self
-			.0
-			.as_any()
-			.downcast_ref::<SourceVirtual>()
-			.expect("can only codegen for virtual source paths!")
-			.0
-			.clone();
-		let val = res.add_value(source_virtual, false);
-		res.add_code(
-			structdump::quote! {
-				structdump_import::SourcePath::new(structdump_import::SourceVirtual(#val))
-			},
-			Some(structdump::quote!(SourcePath)),
-			unique,
-		)
 	}
 }
 
@@ -237,7 +208,6 @@
 ///
 /// It is used for --ext-code=.../--tla-code=.../standard library source code by default,
 /// and user can construct arbitrary values by hand, without asking import resolver
-#[cfg_attr(feature = "structdump", derive(Codegen))]
 #[derive(Trace, Hash, PartialEq, Eq, Debug, Clone)]
 pub struct SourceVirtual(pub IStr);
 impl Display for SourceVirtual {
@@ -288,8 +258,6 @@
 
 /// Either real file, or virtual
 /// Hash of FileName always have same value as raw Path, to make it possible to use with raw_entry_mut
-#[cfg_attr(feature = "structdump", derive(Codegen))]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
 #[derive(Clone, PartialEq, Eq, Debug)]
 pub struct Source(pub Rc<(SourcePath, IStr)>);
 
modifiedcrates/jrsonnet-stdlib/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/Cargo.toml
+++ b/crates/jrsonnet-stdlib/Cargo.toml
@@ -11,14 +11,6 @@
 workspace = true
 
 [features]
-default = ["codegenerated-stdlib"]
-# Speed-up initialization by generating code for parsed stdlib,
-# instead of invoking parser for it.
-# This is mutually exclusive with `serialized-stdlib`.
-codegenerated-stdlib = ["jrsonnet-parser/structdump"]
-# Use the embedded serialized stdlib.
-# This is mutually exclusive with `codegenerated-stdlib`.
-serialized-stdlib = []
 # Enables legacy `std.thisFile` support, at the cost of worse caching
 legacy-this-file = []
 # Add order preservation flag to some functions
@@ -36,9 +28,7 @@
 jrsonnet-parser.workspace = true
 jrsonnet-gcmodule.workspace = true
 
-# Used for stdlib AST serialization
-bincode = { workspace = true, optional = true }
-# Used both for stdlib AST serialization and std.parseJson/std.parseYaml
+# Used for std.parseJson/std.parseYaml
 serde.workspace = true
 
 # std.md5
@@ -65,4 +55,3 @@
 
 [build-dependencies]
 jrsonnet-parser.workspace = true
-structdump = { workspace = true, features = ["derive"] }
deletedcrates/jrsonnet-stdlib/build.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/build.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-fn main() {
-	#[cfg(feature = "codegenerated-stdlib")]
-	{
-		use std::{env, fs::File, io::Write, path::Path};
-
-		use jrsonnet_parser::{parse, ParserSettings, Source};
-		use structdump::CodegenResult;
-
-		let parsed = parse(
-			include_str!("./src/std.jsonnet"),
-			&ParserSettings {
-				source: Source::new_virtual(
-					"<std>".into(),
-					include_str!("./src/std.jsonnet").into(),
-				),
-			},
-		)
-		.expect("parse");
-
-		let mut out = CodegenResult::default();
-
-		let v = out.codegen(&parsed, true);
-
-		{
-			let out_dir = env::var("OUT_DIR").unwrap();
-			let dest_path = Path::new(&out_dir).join("stdlib.rs");
-			let mut f = File::create(dest_path).unwrap();
-			f.write_all(
-				("#[allow(clippy::redundant_clone, clippy::similar_names)]".to_owned()
-					+ &v.to_string())
-					.as_bytes(),
-			)
-			.unwrap();
-		}
-	}
-}
deletedcrates/jrsonnet-stdlib/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/expr.rs
+++ /dev/null
@@ -1,109 +0,0 @@
-use jrsonnet_parser::LocExpr;
-
-pub fn stdlib_expr() -> LocExpr {
-	#[cfg(all(feature = "serialized-stdlib", feature = "codegenerated-stdlib"))]
-	compile_error!(
-		"features `serialized-stdlib` and `codegenerated-stdlib` are mutually exclusive"
-	);
-	#[cfg(all(feature = "serialized-stdlib", not(feature = "codegenerated-stdlib")))]
-	{
-		use bincode::{BincodeRead, DefaultOptions, Options};
-		use serde::{Deserialize, Deserializer};
-
-		struct LocDeserializer<R, O: Options> {
-			source: Source,
-			wrapped: bincode::Deserializer<R, O>,
-		}
-		macro_rules! delegate {
-			($(fn $name:ident($($arg:ident: $ty:ty),*))+) => {$(
-				fn $name<V>(mut self $(, $arg: $ty)*, visitor: V) -> Result<V::Value, Self::Error>
-				where V: serde::de::Visitor<'de>,
-				{
-					self.wrapped.$name($($arg,)* visitor)
-				}
-			)+};
-		}
-		impl<'de, R, O> Deserializer<'de> for LocDeserializer<R, O>
-		where
-			R: BincodeRead<'de>,
-			O: Options,
-		{
-			type Error = <&'de mut bincode::Deserializer<R, O> as Deserializer<'de>>::Error;
-
-			delegate! {
-				fn deserialize_any()
-				fn deserialize_bool()
-				fn deserialize_u16()
-				fn deserialize_u32()
-				fn deserialize_u64()
-				fn deserialize_i16()
-				fn deserialize_i32()
-				fn deserialize_i64()
-				fn deserialize_f32()
-				fn deserialize_f64()
-				fn deserialize_u128()
-				fn deserialize_i128()
-				fn deserialize_u8()
-				fn deserialize_i8()
-				fn deserialize_unit()
-				fn deserialize_char()
-				fn deserialize_str()
-				fn deserialize_string()
-				fn deserialize_bytes()
-				fn deserialize_byte_buf()
-				fn deserialize_enum(name: &'static str, variants: &'static [&'static str])
-				fn deserialize_tuple(len: usize)
-				fn deserialize_option()
-				fn deserialize_seq()
-				fn deserialize_map()
-				fn deserialize_struct(name: &'static str, fields: &'static [&'static str])
-				fn deserialize_identifier()
-				fn deserialize_newtype_struct(name: &'static str)
-				fn deserialize_unit_struct(name: &'static str)
-				fn deserialize_tuple_struct(name: &'static str, len: usize)
-				fn deserialize_ignored_any()
-			}
-
-			fn is_human_readable(&self) -> bool {
-				false
-			}
-		}
-
-		// In build.rs, Source object is populated with empty values, deserializer wrapper loads correct values on deserialize
-		let mut deserializer = bincode::Deserializer::from_slice(
-			include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode")),
-			DefaultOptions::new()
-				.with_fixint_encoding()
-				.allow_trailing_bytes(),
-		);
-
-		// Should not panic, stdlib.bincode is generated in build.rs
-		LocExpr::deserialize(&mut deserializer).unwrap()
-	}
-
-	#[cfg(all(feature = "codegenerated-stdlib", not(feature = "serialized-stdlib")))]
-	{
-		mod structdump_import {
-			pub(super) use std::{option::Option, rc::Rc, vec};
-
-			pub(super) use jrsonnet_parser::*;
-		}
-
-		include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))
-	}
-
-	#[cfg(not(any(feature = "serialized-stdlib", feature = "codegenerated-stdlib")))]
-	{
-		use jrsonnet_parser::Source;
-
-		const STDLIB_STR: &str = include_str!("./std.jsonnet");
-
-		jrsonnet_parser::parse(
-			STDLIB_STR,
-			&jrsonnet_parser::ParserSettings {
-				source: Source::new_virtual("<std>".into(), STDLIB_STR.into()),
-			},
-		)
-		.unwrap()
-	}
-}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/lib.rs
1#![allow(clippy::similar_names)]23use std::{4	cell::{Ref, RefCell, RefMut},5	collections::HashMap,6	rc::Rc,7};89pub use arrays::*;10pub use compat::*;11pub use encoding::*;12pub use hash::*;13use jrsonnet_evaluator::{14	error::{ErrorKind::*, Result},15	function::{CallLocation, FuncVal, TlaArg},16	tb,17	trace::PathResolver,18	ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,19};20use jrsonnet_gcmodule::Trace;21use jrsonnet_parser::Source;22pub use manifest::*;23pub use math::*;24pub use misc::*;25pub use objects::*;26pub use operator::*;27pub use parse::*;28pub use sets::*;29pub use sort::*;30pub use strings::*;31pub use types::*;3233#[cfg(feature = "exp-regex")]34pub use crate::regex::*;3536mod arrays;37mod compat;38mod encoding;39mod expr;40mod hash;41mod manifest;42mod math;43mod misc;44mod objects;45mod operator;46mod parse;47#[cfg(feature = "exp-regex")]48mod regex;49mod sets;50mod sort;51mod strings;52mod types;5354#[allow(clippy::too_many_lines)]55pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {56	let mut builder = ObjValueBuilder::new();5758	let expr = expr::stdlib_expr();59	let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)60		.expect("stdlib.jsonnet should have no errors")61		.as_obj()62		.expect("stdlib.jsonnet should evaluate to object");6364	builder.with_super(eval);6566	// FIXME: Use PHF67	for (name, builtin) in [68		// Types69		("type", builtin_type::INST),70		("isString", builtin_is_string::INST),71		("isNumber", builtin_is_number::INST),72		("isBoolean", builtin_is_boolean::INST),73		("isObject", builtin_is_object::INST),74		("isArray", builtin_is_array::INST),75		("isFunction", builtin_is_function::INST),76		// Arrays77		("makeArray", builtin_make_array::INST),78		("repeat", builtin_repeat::INST),79		("slice", builtin_slice::INST),80		("map", builtin_map::INST),81		("mapWithIndex", builtin_map_with_index::INST),82		("mapWithKey", builtin_map_with_key::INST),83		("flatMap", builtin_flatmap::INST),84		("filter", builtin_filter::INST),85		("foldl", builtin_foldl::INST),86		("foldr", builtin_foldr::INST),87		("range", builtin_range::INST),88		("join", builtin_join::INST),89		("lines", builtin_lines::INST),90		("resolvePath", builtin_resolve_path::INST),91		("deepJoin", builtin_deep_join::INST),92		("reverse", builtin_reverse::INST),93		("any", builtin_any::INST),94		("all", builtin_all::INST),95		("member", builtin_member::INST),96		("find", builtin_find::INST),97		("contains", builtin_contains::INST),98		("count", builtin_count::INST),99		("avg", builtin_avg::INST),100		("removeAt", builtin_remove_at::INST),101		("remove", builtin_remove::INST),102		("flattenArrays", builtin_flatten_arrays::INST),103		("flattenDeepArray", builtin_flatten_deep_array::INST),104		("prune", builtin_prune::INST),105		("filterMap", builtin_filter_map::INST),106		// Math107		("abs", builtin_abs::INST),108		("sign", builtin_sign::INST),109		("max", builtin_max::INST),110		("min", builtin_min::INST),111		("clamp", builtin_clamp::INST),112		("sum", builtin_sum::INST),113		("modulo", builtin_modulo::INST),114		("floor", builtin_floor::INST),115		("ceil", builtin_ceil::INST),116		("log", builtin_log::INST),117		("pow", builtin_pow::INST),118		("sqrt", builtin_sqrt::INST),119		("sin", builtin_sin::INST),120		("cos", builtin_cos::INST),121		("tan", builtin_tan::INST),122		("asin", builtin_asin::INST),123		("acos", builtin_acos::INST),124		("atan", builtin_atan::INST),125		("atan2", builtin_atan2::INST),126		("exp", builtin_exp::INST),127		("mantissa", builtin_mantissa::INST),128		("exponent", builtin_exponent::INST),129		("round", builtin_round::INST),130		("isEven", builtin_is_even::INST),131		("isOdd", builtin_is_odd::INST),132		("isInteger", builtin_is_integer::INST),133		("isDecimal", builtin_is_decimal::INST),134		// Operator135		("mod", builtin_mod::INST),136		("primitiveEquals", builtin_primitive_equals::INST),137		("equals", builtin_equals::INST),138		("xor", builtin_xor::INST),139		("xnor", builtin_xnor::INST),140		("format", builtin_format::INST),141		// Sort142		("sort", builtin_sort::INST),143		("uniq", builtin_uniq::INST),144		("set", builtin_set::INST),145		("minArray", builtin_min_array::INST),146		("maxArray", builtin_max_array::INST),147		// Hash148		("md5", builtin_md5::INST),149		("sha1", builtin_sha1::INST),150		("sha256", builtin_sha256::INST),151		("sha512", builtin_sha512::INST),152		("sha3", builtin_sha3::INST),153		// Encoding154		("encodeUTF8", builtin_encode_utf8::INST),155		("decodeUTF8", builtin_decode_utf8::INST),156		("base64", builtin_base64::INST),157		("base64Decode", builtin_base64_decode::INST),158		("base64DecodeBytes", builtin_base64_decode_bytes::INST),159		// Objects160		("objectFieldsEx", builtin_object_fields_ex::INST),161		("objectFields", builtin_object_fields::INST),162		("objectFieldsAll", builtin_object_fields_all::INST),163		("objectValues", builtin_object_values::INST),164		("objectValuesAll", builtin_object_values_all::INST),165		("objectKeysValues", builtin_object_keys_values::INST),166		("objectKeysValuesAll", builtin_object_keys_values_all::INST),167		("objectHasEx", builtin_object_has_ex::INST),168		("objectHas", builtin_object_has::INST),169		("objectHasAll", builtin_object_has_all::INST),170		("objectRemoveKey", builtin_object_remove_key::INST),171		// Manifest172		("escapeStringJson", builtin_escape_string_json::INST),173		("escapeStringPython", builtin_escape_string_python::INST),174		("escapeStringXML", builtin_escape_string_xml::INST),175		("manifestJsonEx", builtin_manifest_json_ex::INST),176		("manifestJson", builtin_manifest_json::INST),177		("manifestJsonMinified", builtin_manifest_json_minified::INST),178		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),179		("manifestYamlStream", builtin_manifest_yaml_stream::INST),180		("manifestTomlEx", builtin_manifest_toml_ex::INST),181		("manifestToml", builtin_manifest_toml::INST),182		("toString", builtin_to_string::INST),183		("manifestPython", builtin_manifest_python::INST),184		("manifestPythonVars", builtin_manifest_python_vars::INST),185		("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),186		("manifestIni", builtin_manifest_ini::INST),187		// Parse188		("parseJson", builtin_parse_json::INST),189		("parseYaml", builtin_parse_yaml::INST),190		// Strings191		("codepoint", builtin_codepoint::INST),192		("substr", builtin_substr::INST),193		("char", builtin_char::INST),194		("strReplace", builtin_str_replace::INST),195		("escapeStringBash", builtin_escape_string_bash::INST),196		("escapeStringDollars", builtin_escape_string_dollars::INST),197		("isEmpty", builtin_is_empty::INST),198		("equalsIgnoreCase", builtin_equals_ignore_case::INST),199		("splitLimit", builtin_splitlimit::INST),200		("splitLimitR", builtin_splitlimitr::INST),201		("split", builtin_split::INST),202		("asciiUpper", builtin_ascii_upper::INST),203		("asciiLower", builtin_ascii_lower::INST),204		("findSubstr", builtin_find_substr::INST),205		("parseInt", builtin_parse_int::INST),206		#[cfg(feature = "exp-bigint")]207		("bigint", builtin_bigint::INST),208		("parseOctal", builtin_parse_octal::INST),209		("parseHex", builtin_parse_hex::INST),210		("stringChars", builtin_string_chars::INST),211		("lstripChars", builtin_lstrip_chars::INST),212		("rstripChars", builtin_rstrip_chars::INST),213		("stripChars", builtin_strip_chars::INST),214		// Misc215		("length", builtin_length::INST),216		("get", builtin_get::INST),217		("startsWith", builtin_starts_with::INST),218		("endsWith", builtin_ends_with::INST),219		("assertEqual", builtin_assert_equal::INST),220		("mergePatch", builtin_merge_patch::INST),221		// Sets222		("setMember", builtin_set_member::INST),223		("setInter", builtin_set_inter::INST),224		("setDiff", builtin_set_diff::INST),225		("setUnion", builtin_set_union::INST),226		// Regex227		#[cfg(feature = "exp-regex")]228		("regexQuoteMeta", builtin_regex_quote_meta::INST),229		// Compat230		("__compare", builtin___compare::INST),231		("__compare_array", builtin___compare_array::INST),232		("__array_less", builtin___array_less::INST),233		("__array_greater", builtin___array_greater::INST),234		("__array_less_or_equal", builtin___array_less_or_equal::INST),235		(236			"__array_greater_or_equal",237			builtin___array_greater_or_equal::INST,238		),239	]240	.iter()241	.copied()242	{243		builder.method(name, builtin);244	}245246	builder.method(247		"extVar",248		builtin_ext_var {249			settings: settings.clone(),250		},251	);252	builder.method(253		"native",254		builtin_native {255			settings: settings.clone(),256		},257	);258	builder.method("trace", builtin_trace { settings });259	builder.method("id", FuncVal::Id);260261	#[cfg(feature = "exp-regex")]262	{263		// Regex264		let regex_cache = RegexCache::default();265		builder.method(266			"regexFullMatch",267			builtin_regex_full_match {268				cache: regex_cache.clone(),269			},270		);271		builder.method(272			"regexPartialMatch",273			builtin_regex_partial_match {274				cache: regex_cache.clone(),275			},276		);277		builder.method(278			"regexReplace",279			builtin_regex_replace {280				cache: regex_cache.clone(),281			},282		);283		builder.method(284			"regexGlobalReplace",285			builtin_regex_global_replace { cache: regex_cache },286		);287	};288289	builder.build()290}291292pub trait TracePrinter {293	fn print_trace(&self, loc: CallLocation, value: IStr);294}295296pub struct StdTracePrinter {297	resolver: PathResolver,298}299impl StdTracePrinter {300	pub fn new(resolver: PathResolver) -> Self {301		Self { resolver }302	}303}304impl TracePrinter for StdTracePrinter {305	fn print_trace(&self, loc: CallLocation, value: IStr) {306		eprint!("TRACE:");307		if let Some(loc) = loc.0 {308			let locs = loc.0.map_source_locations(&[loc.1]);309			eprint!(310				" {}:{}",311				loc.0.source_path().path().map_or_else(312					|| loc.0.source_path().to_string(),313					|p| self.resolver.resolve(p)314				),315				locs[0].line316			);317		}318		eprintln!(" {value}");319	}320}321322pub struct Settings {323	/// Used for `std.extVar`324	pub ext_vars: HashMap<IStr, TlaArg>,325	/// Used for `std.native`326	pub ext_natives: HashMap<IStr, FuncVal>,327	/// Used for `std.trace`328	pub trace_printer: Box<dyn TracePrinter>,329	/// Used for `std.thisFile`330	pub path_resolver: PathResolver,331}332333fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {334	let source_name = format!("<extvar:{name}>");335	Source::new_virtual(source_name.into(), code.into())336}337338#[derive(Trace, Clone)]339pub struct ContextInitializer {340	/// When we don't need to support legacy-this-file, we can reuse same context for all files341	#[cfg(not(feature = "legacy-this-file"))]342	context: jrsonnet_evaluator::Context,343	/// For `populate`344	#[cfg(not(feature = "legacy-this-file"))]345	stdlib_thunk: Thunk<Val>,346	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it347	#[cfg(feature = "legacy-this-file")]348	stdlib_obj: ObjValue,349	settings: Rc<RefCell<Settings>>,350}351impl ContextInitializer {352	pub fn new(s: State, resolver: PathResolver) -> Self {353		let settings = Settings {354			ext_vars: HashMap::new(),355			ext_natives: HashMap::new(),356			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),357			path_resolver: resolver,358		};359		let settings = Rc::new(RefCell::new(settings));360		let stdlib_obj = stdlib_uncached(settings.clone());361		#[cfg(not(feature = "legacy-this-file"))]362		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));363		#[cfg(feature = "legacy-this-file")]364		let _ = s;365		Self {366			#[cfg(not(feature = "legacy-this-file"))]367			context: {368				let mut context = ContextBuilder::with_capacity(s, 1);369				context.bind("std", stdlib_thunk.clone());370				context.build()371			},372			#[cfg(not(feature = "legacy-this-file"))]373			stdlib_thunk,374			#[cfg(feature = "legacy-this-file")]375			stdlib_obj,376			settings,377		}378	}379	pub fn settings(&self) -> Ref<Settings> {380		self.settings.borrow()381	}382	pub fn settings_mut(&self) -> RefMut<Settings> {383		self.settings.borrow_mut()384	}385	pub fn add_ext_var(&self, name: IStr, value: Val) {386		self.settings_mut()387			.ext_vars388			.insert(name, TlaArg::Val(value));389	}390	pub fn add_ext_str(&self, name: IStr, value: IStr) {391		self.settings_mut()392			.ext_vars393			.insert(name, TlaArg::String(value));394	}395	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {396		let code = code.into();397		let source = extvar_source(name, code.clone());398		let parsed = jrsonnet_parser::parse(399			&code,400			&jrsonnet_parser::ParserSettings {401				source: source.clone(),402			},403		)404		.map_err(|e| ImportSyntaxError {405			path: source,406			error: Box::new(e),407		})?;408		// self.data_mut().volatile_files.insert(source_name, code);409		self.settings_mut()410			.ext_vars411			.insert(name.into(), TlaArg::Code(parsed));412		Ok(())413	}414	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {415		self.settings_mut()416			.ext_natives417			.insert(name.into(), cb.into());418	}419}420impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {421	fn reserve_vars(&self) -> usize {422		1423	}424	#[cfg(not(feature = "legacy-this-file"))]425	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {426		self.context.clone()427	}428	#[cfg(not(feature = "legacy-this-file"))]429	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {430		builder.bind("std", self.stdlib_thunk.clone());431	}432	#[cfg(feature = "legacy-this-file")]433	fn populate(&self, source: Source, builder: &mut ContextBuilder) {434		let mut std = ObjValueBuilder::new();435		std.with_super(self.stdlib_obj.clone());436		std.field("thisFile").hide().value({437			let source_path = source.source_path();438			source_path.path().map_or_else(439				|| source_path.to_string(),440				|p| self.settings().path_resolver.resolve(p),441			)442		});443		let stdlib_with_this_file = std.build();444445		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));446	}447	fn as_any(&self) -> &dyn std::any::Any {448		self449	}450}451452pub trait StateExt {453	/// This method was previously implemented in jrsonnet-evaluator itself454	fn with_stdlib(&self);455}456457impl StateExt for State {458	fn with_stdlib(&self) {459		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());460		self.settings_mut().context_initializer = tb!(initializer);461	}462}
deletedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ /dev/null
@@ -1,5 +0,0 @@
-{
-  local std = self,
-
-  thisFile:: error 'std.thisFile is deprecated, to enable its support in jrsonnet - recompile it with "legacy-this-file" support.\nThis will slow down stdlib caching a bit, though',
-}