12#![cfg_attr(nightly, feature(thread_local, type_alias_impl_trait))]345extern crate self as jrsonnet_evaluator;67mod arr;8pub mod async_import;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13pub mod function;14pub mod gc;15mod import;16mod integrations;17pub mod manifest;18mod obj;19pub mod stack;20pub mod stdlib;21pub mod tla;22pub mod trace;23pub mod typed;24pub mod val;2526use std::{27 any::Any,28 cell::{RefCell, RefMut},29 clone::Clone,30 collections::hash_map::Entry,31 fmt::{self, Debug},32 marker::PhantomData,33 rc::Rc,34};3536pub use ctx::*;37pub use dynamic::*;38pub use error::{Error, ErrorKind::*, Result, ResultExt};39pub use evaluate::*;40use function::CallLocation;41pub use import::*;42use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};43pub use jrsonnet_interner::{IBytes, IStr};44pub use jrsonnet_ir as parser;45pub use jrsonnet_ir::NumValue;46use jrsonnet_ir::{Expr, Source, SourcePath};47#[doc(hidden)]48pub use jrsonnet_macros;4950#[cfg(not(any(feature = "ir-parser", feature = "peg-parser")))]51compile_error!("at least one of `ir-parser` or `peg-parser` features must be enabled");5253pub use error::SyntaxError;54pub use obj::*;55pub use rustc_hash;56use rustc_hash::FxHashMap;57use stack::check_depth;58pub use tla::apply_tla;59pub use val::{Thunk, Val};6061use crate::gc::WithCapacityExt as _;6263#[allow(clippy::needless_return)]64pub(crate) fn parse_jsonnet(code: &str, source: Source) -> Result<Expr, SyntaxError> {65 #[cfg(feature = "peg-parser")]66 {67 use std::sync::LazyLock;68 static USE_LEGACY_PARSER: LazyLock<bool> =69 LazyLock::new(|| std::env::var_os("JRSONNET_LEGACY_PARSER").is_some());7071 if *USE_LEGACY_PARSER {72 return parse_peg(code, source);73 }74 }75 #[cfg(feature = "ir-parser")]76 {77 return parse_ir(code, source);78 }79 #[cfg(feature = "peg-parser")]80 {81 return parse_peg(code, source);82 }83}8485#[cfg(feature = "ir-parser")]86fn parse_ir(code: &str, source: Source) -> Result<Expr, SyntaxError> {87 jrsonnet_ir_parser::parse(code, &jrsonnet_ir_parser::ParserSettings { source }).map_err(|e| {88 SyntaxError {89 message: e.message,90 location: (e.location.0, e.location.1),91 }92 })93}9495#[cfg(feature = "peg-parser")]96fn parse_peg(code: &str, source: Source) -> Result<Expr, SyntaxError> {97 jrsonnet_peg_parser::parse(code, &jrsonnet_peg_parser::ParserSettings { source }).map_err(|e| {98 let message = e99 .expected100 .tokens()101 .find(|t| t.starts_with("!!!"))102 .map_or_else(103 || {104 format!(105 "expected {}, got {:?}",106 e.expected,107 code.chars()108 .nth(e.location.0)109 .map_or_else(|| "EOF".into(), |c: char| c.to_string())110 )111 },112 |v| v[3..].into(),113 );114 SyntaxError {115 message,116 location: e.location,117 }118 })119}120121cc_dyn!(122 #[derive(Clone)]123 CcUnbound<V>,124 Unbound<Bound = V>125);126127128129pub trait Unbound: Trace {130 131 type Bound;132 133 fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;134}135136137138#[derive(Clone, Trace)]139pub enum MaybeUnbound {140 141 Unbound(CcUnbound<Val>),142 143 Bound(Thunk<Val>),144}145146impl Debug for MaybeUnbound {147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {148 write!(f, "MaybeUnbound")149 }150}151impl MaybeUnbound {152 153 pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {154 match self {155 Self::Unbound(v) => v.0.bind(sup_this),156 Self::Bound(v) => Ok(v.evaluate()?),157 }158 }159}160161cc_dyn!(CcContextInitializer, ContextInitializer);162163164165pub trait ContextInitializer {166 167 168 fn populate(&self, for_file: Source, builder: &mut ContextBuilder);169 170 171 fn as_any(&self) -> &dyn Any;172}173impl<T> ContextInitializer for &T174where175 T: ContextInitializer,176{177 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {178 (*self).populate(for_file, builder);179 }180181 fn as_any(&self) -> &dyn Any {182 (*self).as_any()183 }184}185186187impl ContextInitializer for () {188 fn populate(&self, _for_file: Source, _builder: &mut ContextBuilder) {}189 fn as_any(&self) -> &dyn Any {190 self191 }192}193194impl<T> ContextInitializer for Option<T>195where196 T: ContextInitializer + 'static,197{198 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {199 if let Some(ctx) = self {200 ctx.populate(for_file, builder);201 }202 }203204 fn as_any(&self) -> &dyn Any {205 self206 }207}208209macro_rules! impl_context_initializer {210 ($($gen:ident)*) => {211 #[allow(non_snake_case)]212 impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {213 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {214 let ($($gen,)*) = self;215 $($gen.populate(for_file.clone(), builder);)*216 }217 fn as_any(&self) -> &dyn Any {218 self219 }220 }221 };222 ($($cur:ident)* @ $c:ident $($rest:ident)*) => {223 impl_context_initializer!($($cur)*);224 impl_context_initializer!($($cur)* $c @ $($rest)*);225 };226 ($($cur:ident)* @) => {227 impl_context_initializer!($($cur)*);228 }229}230impl_context_initializer! {231 A @ B C D E F G232}233234#[derive(Trace)]235struct FileData {236 string: Option<IStr>,237 bytes: Option<IBytes>,238 parsed: Option<Rc<Expr>>,239 evaluated: Option<Val>,240241 evaluating: bool,242}243impl FileData {244 fn new_string(data: IStr) -> Self {245 Self {246 string: Some(data),247 bytes: None,248 parsed: None,249 evaluated: None,250 evaluating: false,251 }252 }253 fn new_bytes(data: IBytes) -> Self {254 Self {255 string: None,256 bytes: Some(data),257 parsed: None,258 evaluated: None,259 evaluating: false,260 }261 }262 pub(crate) fn get_string(&mut self) -> Option<IStr> {263 if self.string.is_none() {264 self.string = Some(265 self.bytes266 .as_ref()267 .expect("either string or bytes should be set")268 .clone()269 .cast_str()?,270 );271 }272 Some(self.string.clone().expect("just set"))273 }274}275276#[derive(Trace)]277pub struct EvaluationStateInternals {278 279 file_cache: RefCell<FxHashMap<SourcePath, FileData>>,280 281 282 context_initializer: CcContextInitializer,283 284 import_resolver: Rc<dyn ImportResolver>,285}286287288#[derive(Clone, Trace)]289pub struct State(Cc<EvaluationStateInternals>);290291thread_local! {292 pub static DEFAULT_STATE: State = State::builder().build();293 pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};294}295pub struct StateEnterGuard(PhantomData<()>);296impl Drop for StateEnterGuard {297 fn drop(&mut self) {298 STATE.with_borrow_mut(|v| *v = None);299 }300}301302pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {303 if let Some(state) = STATE.with_borrow(Clone::clone) {304 v(state)305 } else {306 let s = DEFAULT_STATE.with(Clone::clone);307 v(s)308 }309}310311impl State {312 pub fn enter(&self) -> StateEnterGuard {313 self.try_enter().expect("entered state already exists")314 }315 pub fn try_enter(&self) -> Option<StateEnterGuard> {316 STATE.with_borrow_mut(|v| {317 if v.is_none() {318 *v = Some(self.clone());319 Some(StateEnterGuard(PhantomData))320 } else {321 None322 }323 })324 }325 326 pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {327 let mut file_cache = self.file_cache();328 let mut file = file_cache.entry(path.clone());329330 let file = match file {331 Entry::Occupied(ref mut d) => d.get_mut(),332 Entry::Vacant(v) => {333 let data = self.import_resolver().load_file_contents(&path)?;334 v.insert(FileData::new_string(335 std::str::from_utf8(&data)336 .map_err(|_| ImportBadFileUtf8(path.clone()))?337 .into(),338 ))339 }340 };341 Ok(file342 .get_string()343 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?)344 }345 346 pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {347 let mut file_cache = self.file_cache();348 let mut file = file_cache.entry(path.clone());349350 let file = match file {351 Entry::Occupied(ref mut d) => d.get_mut(),352 Entry::Vacant(v) => {353 let data = self.import_resolver().load_file_contents(&path)?;354 v.insert(FileData::new_bytes(data.as_slice().into()))355 }356 };357 if let Some(str) = &file.bytes {358 return Ok(str.clone());359 }360 if file.bytes.is_none() {361 file.bytes = Some(362 file.string363 .as_ref()364 .expect("either string or bytes should be set")365 .clone()366 .cast_bytes(),367 );368 }369 Ok(file.bytes.as_ref().expect("just set").clone())370 }371 372 pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {373 let mut file_cache = self.file_cache();374 let mut file = file_cache.entry(path.clone());375376 let file = match file {377 Entry::Occupied(ref mut d) => d.get_mut(),378 Entry::Vacant(v) => {379 let data = self.import_resolver().load_file_contents(&path)?;380 v.insert(FileData::new_string(381 std::str::from_utf8(&data)382 .map_err(|_| ImportBadFileUtf8(path.clone()))?383 .into(),384 ))385 }386 };387 if let Some(val) = &file.evaluated {388 return Ok(val.clone());389 }390 let code = file391 .get_string()392 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?;393 let file_name = Source::new(path.clone(), code.clone());394 if file.parsed.is_none() {395 file.parsed = Some(396 parse_jsonnet(&code, file_name.clone())397 .map(Rc::new)398 .map_err(|e| ImportSyntaxError {399 path: file_name.clone(),400 error: Box::new(e),401 })?,402 );403 }404 let parsed = file.parsed.as_ref().expect("just set").clone();405 if file.evaluating {406 bail!(InfiniteRecursionDetected)407 }408 file.evaluating = true;409 410 drop(file_cache);411 let res = evaluate(self.create_default_context(file_name), &parsed);412413 let mut file_cache = self.file_cache();414 let mut file = file_cache.entry(path);415416 let Entry::Occupied(file) = &mut file else {417 unreachable!("this file was just here")418 };419 let file = file.get_mut();420 file.evaluating = false;421 match res {422 Ok(v) => {423 file.evaluated = Some(v.clone());424 Ok(v)425 }426 Err(e) => Err(e),427 }428 }429430 431 pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {432 let resolved = self.resolve_from(from, &path)?;433 self.import_resolved(resolved)434 }435 pub fn import(&self, path: impl AsPathLike) -> Result<Val> {436 let resolved = self.resolve_from_default(&path)?;437 self.import_resolved(resolved)438 }439440 441 pub fn create_default_context(&self, source: Source) -> Context {442 self.create_default_context_with(source, &())443 }444445 446 pub fn create_default_context_with(447 &self,448 source: Source,449 context_initializer: &dyn ContextInitializer,450 ) -> Context {451 let default_initializer = self.context_initializer();452 let mut builder = ContextBuilder::new();453 default_initializer.populate(source.clone(), &mut builder);454 context_initializer.populate(source, &mut builder);455456 builder.build()457 }458}459460461impl State {462 fn file_cache(&self) -> RefMut<'_, FxHashMap<SourcePath, FileData>> {463 self.0.file_cache.borrow_mut()464 }465}466467pub fn in_frame<T>(468 e: CallLocation<'_>,469 frame_desc: impl FnOnce() -> String,470 f: impl FnOnce() -> Result<T>,471) -> Result<T> {472 let _guard = check_depth()?;473474 f().with_description_src(e, frame_desc)475}476477478pub fn in_description_frame<T>(479 frame_desc: impl FnOnce() -> String,480 f: impl FnOnce() -> Result<T>,481) -> Result<T> {482 let _guard = check_depth()?;483484 f().with_description(frame_desc)485}486487#[derive(Trace)]488pub struct InitialUnderscore(pub Thunk<Val>);489impl ContextInitializer for InitialUnderscore {490 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {491 builder.bind("_", self.0.clone());492 }493494 fn as_any(&self) -> &dyn Any {495 self496 }497}498499500impl State {501 502 pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {503 self.evaluate_snippet_with(name, code, &())504 }505 506 pub fn evaluate_snippet_with(507 &self,508 name: impl Into<IStr>,509 code: impl Into<IStr>,510 context_initializer: &dyn ContextInitializer,511 ) -> Result<Val> {512 let code = code.into();513 let source = Source::new_virtual(name.into(), code.clone());514 let parsed = parse_jsonnet(&code, source.clone()).map_err(|e| ImportSyntaxError {515 path: source.clone(),516 error: Box::new(e),517 })?;518 evaluate(519 self.create_default_context_with(source, context_initializer),520 &parsed,521 )522 }523}524525526impl State {527 528 #[allow(clippy::missing_panics_doc)]529 pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {530 self.import_resolver().resolve_from(from, path)531 }532 #[allow(clippy::missing_panics_doc)]533 pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {534 self.import_resolver().resolve_from_default(path)535 }536 pub fn import_resolver(&self) -> &dyn ImportResolver {537 &*self.0.import_resolver538 }539 pub fn context_initializer(&self) -> &dyn ContextInitializer {540 &*self.0.context_initializer.0541 }542}543544impl State {545 pub fn builder() -> StateBuilder {546 StateBuilder::default()547 }548}549550impl Default for State {551 fn default() -> Self {552 Self::builder().build()553 }554}555556#[derive(Default)]557pub struct StateBuilder {558 import_resolver: Option<Rc<dyn ImportResolver>>,559 context_initializer: Option<CcContextInitializer>,560}561impl StateBuilder {562 pub fn import_resolver(&mut self, import_resolver: impl ImportResolver) -> &mut Self {563 let _ = self.import_resolver.insert(Rc::new(import_resolver));564 self565 }566 pub fn context_initializer(567 &mut self,568 context_initializer: impl ContextInitializer + Trace,569 ) -> &mut Self {570 let _ = self571 .context_initializer572 .insert(CcContextInitializer::new(context_initializer));573 self574 }575 pub fn build(mut self) -> State {576 State(Cc::new(EvaluationStateInternals {577 file_cache: RefCell::new(FxHashMap::new()),578 context_initializer: self579 .context_initializer580 .take()581 .unwrap_or_else(|| CcContextInitializer::new(())),582 import_resolver: self583 .import_resolver584 .take()585 .unwrap_or_else(|| Rc::new(DummyImportResolver)),586 }))587 }588}