git.delta.rocks / jrsonnet / refs/commits / 55128e2ebc3a

difftreelog

fix correct null-coaelse chaining

Yaroslav Bolyukin2023-08-10parent: #23d571a.patch.diff
in: master

3 files changed

modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
446 || format!("variable <{name}> access"),446 || format!("variable <{name}> access"),
447 || ctx.binding(name.clone())?.evaluate(),447 || ctx.binding(name.clone())?.evaluate(),
448 )?,448 )?,
449 Index {449 Index { indexable, parts } => {
450 indexable: LocExpr(v, _),450 let mut parts = parts.iter();
451 index,451 let mut indexable = match &indexable {
452 #[cfg(feature = "exp-null-coaelse")]452 // Cheaper to execute than creating object with overriden `this`
453 null_coaelse,
454 } if matches!(&**v, Expr::Literal(LiteralType::Super)) => {453 LocExpr(v, _) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {
455 let name = evaluate(ctx.clone(), index)?;454 let part = parts.next().expect("at least part should exist");
456 let Val::Str(name) = name else {
457 throw!(ValueIndexMustBeTypeGot(
458 ValType::Obj,
459 ValType::Str,
460 name.value_type(),
461 ))
462 };
463 let Some(super_obj) = ctx.super_obj() else {455 let Some(super_obj) = ctx.super_obj() else {
464 #[cfg(feature = "exp-null-coaelse")]456 #[cfg(feature = "exp-null-coaelse")]
465 if *null_coaelse {457 if part.null_coaelse {
466 return Ok(Val::Null);458 return Ok(Val::Null);
467 }459 }
468 throw!(NoSuperFound)460 throw!(NoSuperFound)
469 };461 };
462 let name = evaluate(ctx.clone(), &part.value)?;
463
464 let Val::Str(name) = name else {
465 throw!(ValueIndexMustBeTypeGot(
466 ValType::Obj,
467 ValType::Str,
468 name.value_type(),
469 ))
470 };
471
470 let this = ctx472 let this = ctx
471 .this()473 .this()
472 .expect("no this found, while super present, should not happen");474 .expect("no this found, while super present, should not happen");
473 let key = name.into_flat();475 let name = name.into_flat();
474 match super_obj.get_for(key.clone(), this.clone())? {476 match super_obj
477 .get_for(name.clone(), this.clone())
478 .with_description_src(&part.value, || format!("field <{name}> access"))?
479 {
475 Some(v) => v,480 Some(v) => v,
476 #[cfg(feature = "exp-null-coaelse")]481 #[cfg(feature = "exp-null-coaelse")]
477 None if *null_coaelse => Val::Null,482 None if part.null_coaelse => return Ok(Val::Null),
478 None => {483 None => {
479 let suggestions = suggest_object_fields(super_obj, key.clone());484 let suggestions = suggest_object_fields(super_obj, name.clone());
480485
481 throw!(NoSuchField(key, suggestions))486 throw!(NoSuchField(name, suggestions))
482 }487 }
483 }488 }
484 }489 }
485 Index {490 e => evaluate(ctx.clone(), e)?,
486 indexable,491 };
487 index,492
488 #[cfg(feature = "exp-null-coaelse")]493 for part in parts {
489 null_coaelse,494 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {
490 } => match (evaluate(ctx.clone(), indexable)?, evaluate(ctx, index)?) {495 (Val::Obj(v), Val::Str(key)) => match v
491 (Val::Obj(v), Val::Str(key)) => State::push(496 .get(key.clone().into_flat())
492 CallLocation::new(loc),497 .with_description_src(&part.value, || format!("field <{key}> access"))?
493 || format!("field <{key}> access"),498 {
494 || match v.get(key.clone().into_flat()) {499 Some(v) => v,
495 Ok(Some(v)) => Ok(v),500 #[cfg(feature = "exp-null-coaelse")]
496 #[cfg(feature = "exp-null-coaelse")]501 None if part.null_coaelse => return Ok(Val::Null),
497 Ok(None) if *null_coaelse => Ok(Val::Null),502 None => {
498 Ok(None) => {503 let suggestions = suggest_object_fields(&v, key.clone().into_flat());
499 let suggestions = suggest_object_fields(&v, key.clone().into_flat());504
500505 throw!(NoSuchField(key.clone().into_flat(), suggestions))
501 throw!(NoSuchField(key.clone().into_flat(), suggestions))506 }
502 }507 },
503 Err(e) => Err(e),508 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(
504 },509 ValType::Obj,
505 )?,510 ValType::Str,
506 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(511 n.value_type(),
507 ValType::Obj,512 )),
508 ValType::Str,513 (Val::Arr(v), Val::Num(n)) => {
509 n.value_type(),514 if n.fract() > f64::EPSILON {
510 )),515 throw!(FractionalIndex)
511516 }
512 (Val::Arr(v), Val::Num(n)) => {517 v.get(n as usize)?
513 if n.fract() > f64::EPSILON {518 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
514 throw!(FractionalIndex)519 }
515 }520 (Val::Arr(_), Val::Str(n)) => {
516 v.get(n as usize)?521 throw!(AttemptedIndexAnArrayWithString(n.into_flat()))
517 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?522 }
518 }523 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
519 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n.into_flat())),524 ValType::Arr,
520 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(525 ValType::Num,
521 ValType::Arr,526 n.value_type(),
522 ValType::Num,527 )),
523 n.value_type(),528
524 )),529 (Val::Str(s), Val::Num(n)) => Val::Str({
525530 let v: IStr = s
526 (Val::Str(s), Val::Num(n)) => Val::Str({531 .clone()
527 let v: IStr = s532 .into_flat()
528 .clone()533 .chars()
529 .into_flat()534 .skip(n as usize)
530 .chars()535 .take(1)
531 .skip(n as usize)536 .collect::<String>()
532 .take(1)537 .into();
533 .collect::<String>()538 if v.is_empty() {
534 .into();539 let size = s.into_flat().chars().count();
535 if v.is_empty() {540 throw!(StringBoundsError(n as usize, size))
536 let size = s.into_flat().chars().count();541 }
537 throw!(StringBoundsError(n as usize, size))542 StrValue::Flat(v)
538 }543 }),
539 StrValue::Flat(v)544 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
540 }),545 ValType::Str,
541 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(546 ValType::Num,
542 ValType::Str,547 n.value_type(),
543 ValType::Num,548 )),
544 n.value_type(),549 #[cfg(feature = "exp-null-coaelse")]
545 )),550 (Val::Null, _) if part.null_coaelse => return Ok(Val::Null),
546 #[cfg(feature = "exp-null-coaelse")]551 (v, _) => throw!(CantIndexInto(v.value_type())),
547 (Val::Null, _) if *null_coaelse => Val::Null,552 };
548553 }
549 (v, _) => throw!(CantIndexInto(v.value_type())),554 indexable
550 },555 }
551 LocalExpr(bindings, returned) => {556 LocalExpr(bindings, returned) => {
552 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =557 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =
553 GcHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());558 GcHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -406,9 +406,7 @@
 	/// a[b], a.b, a?.b
 	Index {
 		indexable: LocExpr,
-		index: LocExpr,
-		#[cfg(feature = "exp-null-coaelse")]
-		null_coaelse: bool,
+		parts: Vec<IndexPart>,
 	},
 	/// function(x) x
 	Function(ParamsDesc, LocExpr),
@@ -421,6 +419,15 @@
 	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,
+	#[cfg(feature = "exp-null-coaelse")]
+	pub null_coaelse: bool,
+}
+
 /// file, begin offset, end offset
 #[cfg_attr(feature = "structdump", derive(Codegen))]
 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -337,22 +337,24 @@
 						unaryop(<"~">) _ b:@ {expr_un!(BitNot b)}
 				--
 				a:(@) _ "[" _ e:slice_desc(s) _ "]" {Expr::Slice(a, e)}
-				indexable:(@) _ null_coaelse:("?" _ ensure_null_coaelse())? "."  _ index:id_loc(s) {Expr::Index{
-					indexable, index,
-					#[cfg(feature = "exp-null-coaelse")]
-					null_coaelse: null_coaelse.is_some(),
-				}}
-				indexable:(@) _ null_coaelse:("?" _ "." _ ensure_null_coaelse())? "[" _ index:expr(s) _ "]" {Expr::Index{
-					indexable, index,
-					#[cfg(feature = "exp-null-coaelse")]
-					null_coaelse: null_coaelse.is_some(),
-				}}
+				indexable:(@) _ parts:index_part(s)+ {Expr::Index{indexable, parts}}
 				a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {Expr::Apply(a, args, ts.is_some())}
 				a:(@) _ "{" _ body:objinside(s) _ "}" {Expr::ObjExtend(a, body)}
 				--
 				e:expr_basic(s) {e}
 				"(" _ e:expr(s) _ ")" {Expr::Parened(e)}
 			}
+		pub rule index_part(s: &ParserSettings) -> IndexPart
+		= n:("?" _ ensure_null_coaelse())? "." _ value:id_loc(s) {IndexPart {
+			value,
+			#[cfg(feature = "exp-null-coaelse")]
+			null_coaelse: n.is_some(),
+		}}
+		/ n:("?" _ "." _ ensure_null_coaelse())? "[" _ value:expr(s) _ "]" {IndexPart {
+			value,
+			#[cfg(feature = "exp-null-coaelse")]
+			null_coaelse: n.is_some(),
+		}}
 
 		pub rule jsonnet(s: &ParserSettings) -> LocExpr = _ e:expr(s) _ {e}
 	}