difftreelog
fix destructure
in: master
4 files changed
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -142,7 +142,7 @@
Ok(field)
} else {
let (fctx, expr) = default.as_ref().expect("shape is checked");
- Ok(evaluate(fctx.clone().unwrap(), expr)?)
+ Ok(crate::evaluate(fctx.clone().unwrap(), expr)?)
}
})
};
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::{6 function::ParamName, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprParams,7 FieldMember, FieldName, ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers,8 Spanned,9};10use jrsonnet_types::ValType;11use rustc_hash::FxHashMap;1213use self::destructure::destruct;14use crate::{15 arr::ArrValue,16 bail,17 destructure::evaluate_dest,18 error::{suggest_object_fields, ErrorKind::*},19 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},20 function::{CallLocation, FuncDesc, FuncVal},21 gc::WithCapacityExt as _,22 in_frame,23 typed::{FromUntyped, IntoUntyped as _, Typed},24 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},25 with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,26 ResultExt, SupThis, Unbound, Val,27};28pub mod destructure;29pub mod operator;3031// This is the amount of bytes that need to be left on the stack before increasing the size.32// It must be at least as large as the stack required by any code that does not call33// `ensure_sufficient_stack`.34const RED_ZONE: usize = 100 * 1024; // 100k3536// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then37// on. This flag has performance relevant characteristics. Don't set it too high.38const STACK_PER_RECURSION: usize = 1024 * 1024; // 1MB3940/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations41/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit42/// from this.43///44/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.45#[inline]46pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {47 stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)48}4950pub fn evaluate_trivial(expr: &Expr) -> Option<Val> {51 fn is_trivial(expr: &Expr) -> bool {52 match expr {53 Expr::Str(_)54 | Expr::Num(_)55 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,56 Expr::Arr(a) => a.iter().all(is_trivial),57 _ => false,58 }59 }60 Some(match expr {61 Expr::Str(s) => Val::string(s.clone()),62 Expr::Num(n) => {63 Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))64 }65 Expr::Literal(LiteralType::False) => Val::Bool(false),66 Expr::Literal(LiteralType::True) => Val::Bool(true),67 Expr::Literal(LiteralType::Null) => Val::Null,68 Expr::Arr(n) => {69 if n.iter().any(|e| !is_trivial(e)) {70 return None;71 }72 Val::Arr(ArrValue::eager(73 n.iter()74 .map(evaluate_trivial)75 .map(|e| e.expect("checked trivial"))76 .collect(),77 ))78 }79 _ => return None,80 })81}8283pub fn evaluate_method(ctx: Context, name: IStr, params: ExprParams, body: Rc<Expr>) -> Val {84 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {85 name,86 ctx,87 params,88 body,89 })))90}9192pub fn evaluate_field_name(ctx: Context, field_name: &Spanned<FieldName>) -> Result<Option<IStr>> {93 Ok(match &field_name.value {94 FieldName::Fixed(n) => Some(n.clone()),95 FieldName::Dyn(expr) => in_frame(96 CallLocation::new(&field_name.span),97 || "evaluating field name".to_string(),98 || {99 let v = evaluate(ctx, expr)?;100 Ok(if matches!(v, Val::Null) {101 None102 } else {103 Some(IStr::from_untyped(v)?)104 })105 },106 )?,107 })108}109110pub fn evaluate_comp(111 ctx: Context,112 specs: &[CompSpec],113 callback: &mut impl FnMut(Context) -> Result<()>,114) -> Result<()> {115 match specs.first() {116 None => callback(ctx)?,117 Some(CompSpec::IfSpec(IfSpecData { cond, span: _ })) => {118 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {119 evaluate_comp(ctx, &specs[1..], callback)?;120 }121 }122 Some(CompSpec::ForSpec(ForSpecData {123 destruct: into,124 over,125 })) => {126 match evaluate(ctx.clone(), over)? {127 Val::Arr(list) => {128 for item in list.iter_lazy() {129 let fctx = Pending::new();130 let mut new_bindings = FxHashMap::with_capacity(into.binds_len());131 destruct(into, item, fctx.clone(), &mut new_bindings)?;132 let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);133134 evaluate_comp(ctx, &specs[1..], callback)?;135 }136 }137 #[cfg(feature = "exp-object-iteration")]138 Val::Obj(obj) => {139 for field in obj.fields(140 // TODO: Should there be ability to preserve iteration order?141 #[cfg(feature = "exp-preserve-order")]142 false,143 ) {144 let fctx = Pending::new();145 let mut new_bindings = FxHashMap::with_capacity(into.binds_len());146 let obj = obj.clone();147 let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![148 Thunk::evaluated(Val::string(field.clone())),149 Thunk!(move || obj.get(field).transpose().expect(150 "field exists, as field name was obtained from object.fields()",151 )),152 ])));153 destruct(into, value, fctx.clone(), &mut new_bindings)?;154 let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);155156 evaluate_comp(ctx, &specs[1..], callback)?;157 }158 }159 _ => bail!(InComprehensionCanOnlyIterateOverArray),160 }161 }162 }163 Ok(())164}165166trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}167impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}168169fn evaluate_object_locals(170 fctx: Context,171 locals: Rc<Vec<BindSpec>>,172) -> impl CloneableUnbound<Context> {173 #[derive(Trace, Clone)]174 struct UnboundLocals {175 fctx: Context,176 locals: Rc<Vec<BindSpec>>,177 }178 impl Unbound for UnboundLocals {179 type Bound = Context;180181 fn bind(&self, sup_this: SupThis) -> Result<Context> {182 let fctx = Context::new_future();183 let mut new_bindings =184 FxHashMap::with_capacity(self.locals.iter().map(BindSpec::binds_len).sum());185 for b in self.locals.iter() {186 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;187 }188189 let ctx = self.fctx.clone();190191 let ctx = ctx192 .extend_bindings_sup_this(new_bindings, sup_this)193 .into_future(fctx);194195 Ok(ctx)196 }197 }198199 UnboundLocals { fctx, locals }200}201202pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(203 builder: &mut ObjValueBuilder,204 ctx: Context,205 uctx: B,206 field: &FieldMember,207) -> Result<()> {208 let name = evaluate_field_name(ctx, &field.name)?;209 let Some(name) = name else {210 return Ok(());211 };212213 match field {214 FieldMember {215 plus,216 params: None,217 visibility,218 value,219 ..220 } => {221 #[derive(Trace)]222 struct UnboundValue<B: Trace> {223 uctx: B,224 value: Rc<Expr>,225 name: IStr,226 }227 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {228 type Bound = Val;229 fn bind(&self, sup_this: SupThis) -> Result<Val> {230 evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())231 }232 }233234 builder235 .field(name.clone())236 .with_add(*plus)237 .with_visibility(*visibility)238 .with_location(field.name.span.clone())239 .bindable(UnboundValue {240 uctx,241 value: value.clone(),242 name,243 })?;244 }245 FieldMember {246 params: Some(params),247 visibility,248 value,249 ..250 } => {251 #[derive(Trace)]252 struct UnboundMethod<B: Trace> {253 uctx: B,254 value: Rc<Expr>,255 params: ExprParams,256 name: IStr,257 }258 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {259 type Bound = Val;260 fn bind(&self, sup_this: SupThis) -> Result<Val> {261 Ok(evaluate_method(262 self.uctx.bind(sup_this)?,263 self.name.clone(),264 self.params.clone(),265 self.value.clone(),266 ))267 }268 }269270 builder271 .field(name.clone())272 .with_visibility(*visibility)273 // .with_location(value.span())274 .bindable(UnboundMethod {275 uctx,276 value: value.clone(),277 params: params.clone(),278 name,279 })?;280 }281 }282 Ok(())283}284285#[allow(clippy::too_many_lines)]286pub fn evaluate_member_list_object(ctx: Context, members: &ObjMembers) -> Result<ObjValue> {287 let mut builder = ObjValueBuilder::new();288 let locals = members.locals.clone();289290 // We have single context for all fields, so we can cache binds291 let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));292293 for field in &members.fields {294 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;295 }296297 if !members.asserts.is_empty() {298 #[derive(Trace)]299 struct ObjectAssert<B: Trace> {300 uctx: B,301 asserts: Rc<Vec<AssertStmt>>,302 }303 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {304 fn run(&self, sup_this: SupThis) -> Result<()> {305 let ctx = self.uctx.bind(sup_this)?;306 for assert in &*self.asserts {307 evaluate_assert(ctx.clone(), assert)?;308 }309 Ok(())310 }311 }312 builder.assert(ObjectAssert {313 uctx,314 asserts: members.asserts.clone(),315 });316 }317318 Ok(builder.build())319}320321pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {322 Ok(match object {323 ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,324 ObjBody::ObjComp(obj) => {325 let mut builder = ObjValueBuilder::new();326 let locals = obj.locals.clone();327 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {328 let uctx = evaluate_object_locals(ctx.clone(), locals.clone());329330 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)331 })?;332333 builder.build()334 }335 })336}337338pub fn evaluate_apply(339 ctx: Context,340 value: &Expr,341 args: &ArgsDesc,342 loc: CallLocation<'_>,343 tailstrict: bool,344) -> Result<Val> {345 let value = evaluate(ctx.clone(), value)?;346 Ok(match value {347 Val::Func(f) => {348 let body = || f.evaluate(ctx, loc, args, tailstrict);349 if tailstrict {350 body()?351 } else {352 in_frame(loc, || format!("function <{}> call", f.name()), body)?353 }354 }355 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),356 })357}358359pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {360 let value = &assertion.0;361 let msg = &assertion.1;362 let assertion_result = in_frame(363 CallLocation::new(&value.span),364 || "assertion condition".to_owned(),365 || bool::from_untyped(evaluate(ctx.clone(), value)?),366 )?;367 if !assertion_result {368 in_frame(369 CallLocation::new(&value.span),370 || "assertion failure".to_owned(),371 || {372 if let Some(msg) = msg {373 bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));374 }375 bail!(AssertionFailed(Val::Null.to_string()?));376 },377 )?;378 }379 Ok(())380}381382pub fn evaluate_named_param(ctx: Context, expr: &Expr, name: ParamName) -> Result<Val> {383 match name {384 ParamName::Named(name) => evaluate_named(ctx, expr, name),385 ParamName::Unnamed => evaluate(ctx, expr),386 }387}388389pub fn evaluate_named(ctx: Context, expr: &Expr, name: IStr) -> Result<Val> {390 use Expr::*;391 Ok(match expr {392 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),393 _ => evaluate(ctx, expr)?,394 })395}396397#[allow(clippy::too_many_lines)]398pub fn evaluate(ctx: Context, expr: &Expr) -> Result<Val> {399 use Expr::*;400401 if let Some(trivial) = evaluate_trivial(expr) {402 return Ok(trivial);403 }404 Ok(match expr {405 Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),406 Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),407 Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),408 Literal(LiteralType::True) => Val::Bool(true),409 Literal(LiteralType::False) => Val::Bool(false),410 Literal(LiteralType::Null) => Val::Null,411 Str(v) => Val::string(v.clone()),412 Num(v) => Val::try_num(*v)?,413 // I have tried to remove special behavior from super by implementing standalone-super414 // expresion, but looks like this case still needs special treatment.415 //416 // Note that other jsonnet implementations will fail on `if value in (super)` expression,417 // because the standalone super literal is not supported, that is because in other418 // implementations `in super` treated differently from `in smth_else`.419 BinaryOp(bin)420 if matches!(&bin.rhs, Expr::Literal(LiteralType::Super))421 && bin.op == BinaryOpType::In =>422 {423 let sup_this = ctx.try_sup_this()?;424 // In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.425 // In jrsonnet, however, this wasn't true, this was kept here for compatibility.426 if !sup_this.has_super() {427 return Ok(Val::Bool(false));428 }429 let field = evaluate(ctx, &bin.lhs)?;430 Val::Bool(sup_this.field_in_super(field.to_string()?))431 }432 BinaryOp(bin) => evaluate_binary_op_special(ctx, &bin.lhs, bin.op, &bin.rhs)?,433 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,434 Var(name) => in_frame(435 CallLocation::new(&name.span),436 || format!("local <{}> access", &**name),437 || ctx.binding((**name).clone())?.evaluate(),438 )?,439 Index { indexable, parts } => ensure_sufficient_stack(|| {440 let mut parts = parts.iter();441 let mut indexable = if matches!(&**indexable, Expr::Literal(LiteralType::Super)) {442 let part = parts.next().expect("at least part should exist");443 // sup_this existence check might also be skipped here for null-coalesce...444 // But I believe this might cause errors.445 let sup_this = ctx.try_sup_this()?;446 if !sup_this.has_super() {447 #[cfg(feature = "exp-null-coaelse")]448 if part.null_coaelse {449 return Ok(Val::Null);450 }451 bail!(NoSuperFound)452 }453 let name = evaluate(ctx.clone(), &part.value)?;454455 let Val::Str(name) = name else {456 bail!(ValueIndexMustBeTypeGot(457 ValType::Obj,458 ValType::Str,459 name.value_type(),460 ))461 };462463 let name = name.into_flat();464 match sup_this465 .get_super(name.clone())466 .with_description_src(&part.span, || format!("field <{name}> access"))?467 {468 Some(v) => v,469 #[cfg(feature = "exp-null-coaelse")]470 None if part.null_coaelse => return Ok(Val::Null),471 None => {472 let suggestions = suggest_object_fields(473 &sup_this.standalone_super().expect("super exists"),474 name.clone(),475 );476477 bail!(NoSuchField(name, suggestions))478 }479 }480 } else {481 evaluate(ctx.clone(), indexable)?482 };483484 for part in parts {485 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {486 (Val::Obj(v), Val::Str(key)) => match v487 .get(key.clone().into_flat())488 .with_description_src(&part.span, || format!("field <{key}> access"))?489 {490 Some(v) => v,491 #[cfg(feature = "exp-null-coaelse")]492 None if part.null_coaelse => return Ok(Val::Null),493 None => {494 let suggestions = suggest_object_fields(&v, key.clone().into_flat());495496 return Err(Error::from(NoSuchField(497 key.clone().into_flat(),498 suggestions,499 )))500 .with_description_src(&part.span, || format!("field <{key}> access"));501 }502 },503 (Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(504 ValType::Obj,505 ValType::Str,506 n.value_type(),507 )),508 (Val::Arr(v), Val::Num(n)) => {509 let n = n.get();510 if n.fract() > f64::EPSILON {511 bail!(FractionalIndex)512 }513 if n < 0.0 {514 bail!(ArrayBoundsError(n as isize, v.len()));515 }516 v.get(n as usize)?517 .ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?518 }519 (Val::Arr(_), Val::Str(n)) => {520 bail!(AttemptedIndexAnArrayWithString(n.into_flat()))521 }522 (Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(523 ValType::Arr,524 ValType::Num,525 n.value_type(),526 )),527528 (Val::Str(s), Val::Num(n)) => Val::Str({529 let n = n.get();530 if n.fract() > f64::EPSILON {531 bail!(FractionalIndex)532 }533 if n < 0.0 {534 bail!(ArrayBoundsError(n as isize, s.into_flat().chars().count()));535 }536 let v: IStr = s537 .clone()538 .into_flat()539 .chars()540 .skip(n as usize)541 .take(1)542 .collect::<String>()543 .into();544 if v.is_empty() {545 bail!(StringBoundsError(n as usize, s.into_flat().chars().count()))546 }547 StrValue::Flat(v)548 }),549 (Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(550 ValType::Str,551 ValType::Num,552 n.value_type(),553 )),554 #[cfg(feature = "exp-null-coaelse")]555 (Val::Null, _) if part.null_coaelse => return Ok(Val::Null),556 (v, _) => bail!(CantIndexInto(v.value_type())),557 };558 }559 Ok(indexable)560 })?,561 LocalExpr(bindings, returned) => {562 let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =563 FxHashMap::with_capacity(bindings.iter().map(BindSpec::binds_len).sum());564 let fctx = Context::new_future();565 for b in bindings {566 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;567 }568 let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);569 evaluate(ctx, returned)?570 }571 Arr(items) => {572 if items.is_empty() {573 Val::Arr(ArrValue::empty())574 } else {575 Val::Arr(ArrValue::expr(ctx, items.clone()))576 }577 }578 ArrComp(expr, comp_specs) => {579 let mut out = Vec::new();580 evaluate_comp(ctx, comp_specs, &mut |ctx| {581 let expr = expr.clone();582 out.push(Thunk!(move || evaluate(ctx, &expr)));583 Ok(())584 })?;585 Val::Arr(ArrValue::lazy(out))586 }587 Obj(body) => Val::Obj(evaluate_object(ctx, body)?),588 ObjExtend(a, b) => evaluate_add_op(589 &evaluate(ctx.clone(), a)?,590 &Val::Obj(evaluate_object(ctx, b)?),591 )?,592 Apply(value, args, tailstrict) => ensure_sufficient_stack(|| {593 evaluate_apply(ctx, value, args, CallLocation::new(&args.span), *tailstrict)594 })?,595 Function(params, body) => {596 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())597 }598 AssertExpr(assert) => {599 evaluate_assert(ctx.clone(), &assert.assert)?;600 evaluate(ctx, &assert.rest)?601 }602 ErrorStmt(s, e) => in_frame(603 CallLocation::new(s),604 || "error statement".to_owned(),605 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),606 )?,607 IfElse(if_else) => {608 if in_frame(609 CallLocation::new(&if_else.cond.span),610 || "if condition".to_owned(),611 || bool::from_untyped(evaluate(ctx.clone(), &if_else.cond.cond)?),612 )? {613 evaluate(ctx, &if_else.cond_then)?614 } else {615 match &if_else.cond_else {616 Some(v) => evaluate(ctx, v)?,617 None => Val::Null,618 }619 }620 }621 Slice(slice) => {622 fn parse_idx<T: Typed + FromUntyped>(623 ctx: Context,624 expr: Option<&Spanned<Expr>>,625 desc: &'static str,626 ) -> Result<Option<T>> {627 if let Some(value) = expr {628 Ok(in_frame(629 CallLocation::new(&value.span),630 || format!("slice {desc}"),631 || <Option<T>>::from_untyped(evaluate(ctx, value)?),632 )?)633 } else {634 Ok(None)635 }636 }637638 let indexable = evaluate(ctx.clone(), &slice.value)?;639640 let start = parse_idx(ctx.clone(), slice.slice.start.as_ref(), "start")?;641 let end = parse_idx(ctx.clone(), slice.slice.end.as_ref(), "end")?;642 let step = parse_idx(ctx, slice.slice.step.as_ref(), "step")?;643644 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?645 }646 Import(kind, path) => {647 let Expr::Str(path) = &**path else {648 bail!("computed imports are not supported")649 };650 with_state(|s| {651 let span = &kind.span;652 let resolved_path = s.resolve_from(span.0.source_path(), path)?;653 Ok(match &**kind {654 ImportKind::Normal => in_frame(655 CallLocation::new(span),656 || format!("import {:?}", path.clone()),657 || s.import_resolved(resolved_path),658 )?,659 ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),660 ImportKind::Bin => {661 Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))662 }663 }) as Result<Val>664 })?665 }666 })667}crates/jrsonnet-ir-parser/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-ir-parser/Cargo.toml
+++ b/crates/jrsonnet-ir-parser/Cargo.toml
@@ -8,6 +8,7 @@
[features]
exp-null-coaelse = ["jrsonnet-ir/exp-null-coaelse"]
+exp-destruct = ["jrsonnet-ir/exp-destruct"]
[dependencies]
insta.workspace = true
crates/jrsonnet-ir-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir-parser/src/lib.rs
+++ b/crates/jrsonnet-ir-parser/src/lib.rs
@@ -3,9 +3,9 @@
use jrsonnet_gcmodule::Acyclic;
use jrsonnet_ir::{
unescape, ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec,
- Destruct, Expr, ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse,
- IfSpecData, ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers, Slice,
- SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility,
+ Destruct, DestructRest, Expr, ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr,
+ IfElse, IfSpecData, ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers,
+ Slice, SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility,
};
use jrsonnet_lexer::{collect_lexed_str_block, Lexeme, Lexer, SyntaxKind, T};
@@ -316,7 +316,114 @@
}
fn destruct(p: &mut Parser<'_>) -> R<Destruct> {
- Ok(Destruct::Full(p.expect_ident()?))
+ if p.at_ident() {
+ return Ok(Destruct::Full(p.expect_ident()?));
+ }
+ #[cfg(not(feature = "exp-destruct"))]
+ return Err(p.error(format!(
+ "expected identifier, got {}",
+ p.current_desc()
+ )));
+ #[cfg(feature = "exp-destruct")]
+ {
+ if p.try_eat(T![?]) {
+ return Ok(Destruct::Skip);
+ }
+ if p.at(T!['[']) {
+ return destruct_array(p);
+ }
+ if p.at(T!['{']) {
+ return destruct_object(p);
+ }
+ Err(p.error(format!(
+ "expected destructure pattern, got {}",
+ p.current_desc()
+ )))
+ }
+}
+
+#[cfg(feature = "exp-destruct")]
+fn destruct_rest(p: &mut Parser<'_>) -> R<DestructRest> {
+ p.eat(T![...])?;
+ if p.at_ident() {
+ Ok(DestructRest::Keep(p.expect_ident()?))
+ } else {
+ Ok(DestructRest::Drop)
+ }
+}
+
+#[cfg(feature = "exp-destruct")]
+fn destruct_array(p: &mut Parser<'_>) -> R<Destruct> {
+ p.eat(T!['['])?;
+ let mut start = Vec::new();
+ let mut rest = None;
+ let mut end = Vec::new();
+ if !p.at(T![']']) {
+ loop {
+ if p.at(T![...]) {
+ rest = Some(destruct_rest(p)?);
+ if p.try_eat(T![,]) {
+ if !p.at(T![']']) {
+ loop {
+ end.push(destruct(p)?);
+ if !p.try_eat(T![,]) {
+ break;
+ }
+ if p.at(T![']']) {
+ break;
+ }
+ }
+ }
+ }
+ break;
+ }
+ start.push(destruct(p)?);
+ if !p.try_eat(T![,]) {
+ break;
+ }
+ if p.at(T![']']) {
+ break;
+ }
+ }
+ }
+ p.eat(T![']'])?;
+ Ok(Destruct::Array { start, rest, end })
+}
+
+#[cfg(feature = "exp-destruct")]
+fn destruct_object(p: &mut Parser<'_>) -> R<Destruct> {
+ p.eat(T!['{'])?;
+ let mut fields = Vec::new();
+ let mut rest = None;
+ if !p.at(T!['}']) {
+ loop {
+ if p.at(T![...]) {
+ rest = Some(destruct_rest(p)?);
+ p.try_eat(T![,]);
+ break;
+ }
+ let name = p.expect_ident()?;
+ let into = if p.try_eat(T![:]) {
+ Some(destruct(p)?)
+ } else {
+ None
+ };
+ let default = if p.try_eat(T![=]) {
+ Some(Rc::new(spanned(p, expr)?))
+ } else {
+ None
+ };
+ fields.push((name, into, default));
+ if !p.try_eat(T![,]) {
+ break;
+ }
+ if p.at(T!['}']) {
+ break;
+ }
+ }
+ }
+ p.eat(T!['}'])?;
+ Ok(Destruct::Object { fields, rest })
}
fn params(p: &mut Parser<'_>) -> R<ExprParams> {
@@ -383,6 +490,15 @@
}
fn bind(p: &mut Parser<'_>) -> R<BindSpec> {
+ #[cfg(feature = "exp-destruct")]
+ {
+ if !p.at_ident() {
+ let d = destruct(p)?;
+ p.eat(T![=])?;
+ let value = Rc::new(expr(p)?);
+ return Ok(BindSpec::Field { into: d, value });
+ }
+ }
let name = p.expect_ident()?;
if p.try_eat(T!['(']) {
let ps = params(p)?;