git.delta.rocks / jrsonnet / refs/commits / 3e23ebe1b496

difftreelog

refactor add proper getters for LocExpr

Yaroslav Bolyukin2024-06-18parent: #ea44e44.patch.diff
in: master

10 files changed

modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
53serde.workspace = true53serde.workspace = true
5454
55anyhow = { workspace = true, optional = true }55anyhow = { workspace = true, optional = true }
56# Serialized stdlib
57bincode = { workspace = true, optional = true }
58# Explaining traces56# Explaining traces
59annotate-snippets = { workspace = true, optional = true }57annotate-snippets = { workspace = true, optional = true }
60# Better explaining traces58# Better explaining traces
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
77
8use jrsonnet_gcmodule::Trace;8use jrsonnet_gcmodule::Trace;
9use jrsonnet_interner::IStr;9use jrsonnet_interner::IStr;
10use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};10use jrsonnet_parser::{BinaryOpType, LocExpr, Source, SourcePath, Span, UnaryOpType};
11use jrsonnet_types::ValType;11use jrsonnet_types::ValType;
12use thiserror::Error;12use thiserror::Error;
1313
275pub struct StackTraceElement {275pub struct StackTraceElement {
276 /// Source of this frame276 /// Source of this frame
277 /// Some frames only act as description, without attached source277 /// Some frames only act as description, without attached source
278 pub location: Option<ExprLocation>,278 pub location: Option<Span>,
279 /// Frame description279 /// Frame description
280 pub desc: String,280 pub desc: String,
281}281}
324impl std::error::Error for Error {}324impl std::error::Error for Error {}
325325
326pub trait ErrorSource {326pub trait ErrorSource {
327 fn to_location(self) -> Option<ExprLocation>;327 fn to_location(self) -> Option<Span>;
328}328}
329impl ErrorSource for &LocExpr {329impl ErrorSource for &LocExpr {
330 fn to_location(self) -> Option<ExprLocation> {330 fn to_location(self) -> Option<Span> {
331 Some(self.1.clone())331 Some(self.span())
332 }332 }
333}333}
334impl ErrorSource for &ExprLocation {334impl ErrorSource for &Span {
335 fn to_location(self) -> Option<ExprLocation> {335 fn to_location(self) -> Option<Span> {
336 Some(self.clone())336 Some(self.clone())
337 }337 }
338}338}
339impl ErrorSource for CallLocation<'_> {339impl ErrorSource for CallLocation<'_> {
340 fn to_location(self) -> Option<ExprLocation> {340 fn to_location(self) -> Option<Span> {
341 self.0.cloned()341 self.0.cloned()
342 }342 }
343}343}
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
2626
27pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {27pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {
28 fn is_trivial(expr: &LocExpr) -> bool {28 fn is_trivial(expr: &LocExpr) -> bool {
29 match &*expr.0 {29 match expr.expr() {
30 Expr::Str(_)30 Expr::Str(_)
31 | Expr::Num(_)31 | Expr::Num(_)
32 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,32 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,
35 _ => false,35 _ => false,
36 }36 }
37 }37 }
38 Some(match &*expr.0 {38 Some(match expr.expr() {
39 Expr::Str(s) => Val::string(s.clone()),39 Expr::Str(s) => Val::string(s.clone()),
40 Expr::Num(n) => {40 Expr::Num(n) => {
41 Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))41 Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))
72 Ok(match field_name {72 Ok(match field_name {
73 FieldName::Fixed(n) => Some(n.clone()),73 FieldName::Fixed(n) => Some(n.clone()),
74 FieldName::Dyn(expr) => State::push(74 FieldName::Dyn(expr) => State::push(
75 CallLocation::new(&expr.1),75 CallLocation::new(&expr.span()),
76 || "evaluating field name".to_string(),76 || "evaluating field name".to_string(),
77 || {77 || {
78 let value = evaluate(ctx, expr)?;78 let value = evaluate(ctx, expr)?;
231 .field(name.clone())231 .field(name.clone())
232 .with_add(*plus)232 .with_add(*plus)
233 .with_visibility(*visibility)233 .with_visibility(*visibility)
234 .with_location(value.1.clone())234 .with_location(value.span())
235 .bindable(UnboundValue {235 .bindable(UnboundValue {
236 uctx,236 uctx,
237 value: value.clone(),237 value: value.clone(),
266 builder266 builder
267 .field(name.clone())267 .field(name.clone())
268 .with_visibility(*visibility)268 .with_visibility(*visibility)
269 .with_location(value.1.clone())269 .with_location(value.span())
270 .bindable(UnboundMethod {270 .bindable(UnboundMethod {
271 uctx,271 uctx,
272 value: value.clone(),272 value: value.clone(),
385 let value = &assertion.0;385 let value = &assertion.0;
386 let msg = &assertion.1;386 let msg = &assertion.1;
387 let assertion_result = State::push(387 let assertion_result = State::push(
388 CallLocation::new(&value.1),388 CallLocation::new(&value.span()),
389 || "assertion condition".to_owned(),389 || "assertion condition".to_owned(),
390 || bool::from_untyped(evaluate(ctx.clone(), value)?),390 || bool::from_untyped(evaluate(ctx.clone(), value)?),
391 )?;391 )?;
392 if !assertion_result {392 if !assertion_result {
393 State::push(393 State::push(
394 CallLocation::new(&value.1),394 CallLocation::new(&value.span()),
395 || "assertion failure".to_owned(),395 || "assertion failure".to_owned(),
396 || {396 || {
397 if let Some(msg) = msg {397 if let Some(msg) = msg {
406406
407pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {407pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {
408 use Expr::*;408 use Expr::*;
409 let LocExpr(raw_expr, _loc) = expr;
410 Ok(match &**raw_expr {409 Ok(match expr.expr() {
411 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),410 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),
412 _ => evaluate(ctx, expr)?,411 _ => evaluate(ctx, expr)?,
413 })412 })
420 if let Some(trivial) = evaluate_trivial(expr) {419 if let Some(trivial) = evaluate_trivial(expr) {
421 return Ok(trivial);420 return Ok(trivial);
422 }421 }
423 let LocExpr(expr, loc) = expr;422 let loc = expr.span();
424 Ok(match &**expr {423 Ok(match expr.expr() {
425 Literal(LiteralType::This) => {424 Literal(LiteralType::This) => {
426 Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())425 Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())
427 }426 }
448 // because the standalone super literal is not supported, that is because in other447 // because the standalone super literal is not supported, that is because in other
449 // implementations `in super` treated differently from in `smth_else`.448 // implementations `in super` treated differently from in `smth_else`.
450 BinaryOp(field, BinaryOpType::In, e)449 BinaryOp(field, BinaryOpType::In, e)
451 if matches!(&*e.0, Expr::Literal(LiteralType::Super)) =>450 if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>
452 {451 {
453 let Some(super_obj) = ctx.super_obj() else {452 let Some(super_obj) = ctx.super_obj() else {
454 return Ok(Val::Bool(false));453 return Ok(Val::Bool(false));
459 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,458 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
460 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,459 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
461 Var(name) => State::push(460 Var(name) => State::push(
462 CallLocation::new(loc),461 CallLocation::new(&loc),
463 || format!("variable <{name}> access"),462 || format!("variable <{name}> access"),
464 || ctx.binding(name.clone())?.evaluate(),463 || ctx.binding(name.clone())?.evaluate(),
465 )?,464 )?,
466 Index { indexable, parts } => {465 Index { indexable, parts } => {
467 let mut parts = parts.iter();466 let mut parts = parts.iter();
468 let mut indexable = match &indexable {467 let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {
469 // Cheaper to execute than creating object with overriden `this`
470 LocExpr(v, _) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {
471 let part = parts.next().expect("at least part should exist");468 let part = parts.next().expect("at least part should exist");
472 let Some(super_obj) = ctx.super_obj() else {469 let Some(super_obj) = ctx.super_obj() else {
473 #[cfg(feature = "exp-null-coaelse")]470 #[cfg(feature = "exp-null-coaelse")]
503 bail!(NoSuchField(name, suggestions))500 bail!(NoSuchField(name, suggestions))
504 }501 }
505 }502 }
506 }503 } else {
507 e => evaluate(ctx.clone(), e)?,504 evaluate(ctx.clone(), indexable)?
508 };505 };
509506
510 for part in parts {507 for part in parts {
511 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {508 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {
639 &Val::Obj(evaluate_object(ctx, b)?),636 &Val::Obj(evaluate_object(ctx, b)?),
640 )?,637 )?,
641 Apply(value, args, tailstrict) => {638 Apply(value, args, tailstrict) => {
642 evaluate_apply(ctx, value, args, CallLocation::new(loc), *tailstrict)?639 evaluate_apply(ctx, value, args, CallLocation::new(&loc), *tailstrict)?
643 }640 }
644 Function(params, body) => {641 Function(params, body) => {
645 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())642 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())
649 evaluate(ctx, returned)?646 evaluate(ctx, returned)?
650 }647 }
651 ErrorStmt(e) => State::push(648 ErrorStmt(e) => State::push(
652 CallLocation::new(loc),649 CallLocation::new(&loc),
653 || "error statement".to_owned(),650 || "error statement".to_owned(),
654 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),651 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
655 )?,652 )?,
659 cond_else,656 cond_else,
660 } => {657 } => {
661 if State::push(658 if State::push(
662 CallLocation::new(loc),659 CallLocation::new(&loc),
663 || "if condition".to_owned(),660 || "if condition".to_owned(),
664 || bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),661 || bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),
665 )? {662 )? {
690 }687 }
691688
692 let indexable = evaluate(ctx.clone(), value)?;689 let indexable = evaluate(ctx.clone(), value)?;
693 let loc = CallLocation::new(loc);690 let loc = CallLocation::new(&loc);
694691
695 let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;692 let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;
696 let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;693 let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;
699 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?696 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?
700 }697 }
701 i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {698 i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {
702 let Expr::Str(path) = &*path.0 else {699 let Expr::Str(path) = &path.expr() else {
703 bail!("computed imports are not supported")700 bail!("computed imports are not supported")
704 };701 };
705 let tmp = loc.clone().0;702 let tmp = loc.clone().0;
706 let s = ctx.state();703 let s = ctx.state();
707 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;704 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
708 match i {705 match i {
709 Import(_) => State::push(706 Import(_) => State::push(
710 CallLocation::new(loc),707 CallLocation::new(&loc),
711 || format!("import {:?}", path.clone()),708 || format!("import {:?}", path.clone()),
712 || s.import_resolved(resolved_path),709 || s.import_resolved(resolved_path),
713 )?,710 )?,
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
4use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_gcmodule::{Cc, Trace};
5use jrsonnet_interner::IStr;5use jrsonnet_interner::IStr;
6pub use jrsonnet_macros::builtin;6pub use jrsonnet_macros::builtin;
7use jrsonnet_parser::{Destruct, Expr, ExprLocation, LocExpr, ParamsDesc};7use jrsonnet_parser::{Destruct, Expr, LocExpr, ParamsDesc, Span};
88
9use self::{9use self::{
10 arglike::OptionalContext,10 arglike::OptionalContext,
22/// Function callsite location.22/// Function callsite location.
23/// Either from other jsonnet code, specified by expression location, or from native (without location).23/// Either from other jsonnet code, specified by expression location, or from native (without location).
24#[derive(Clone, Copy)]24#[derive(Clone, Copy)]
25pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);25pub struct CallLocation<'l>(pub Option<&'l Span>);
26impl<'l> CallLocation<'l> {26impl<'l> CallLocation<'l> {
27 /// Construct new location for calls coming from specified jsonnet expression location.27 /// Construct new location for calls coming from specified jsonnet expression location.
28 pub const fn new(loc: &'l ExprLocation) -> Self {28 pub const fn new(loc: &'l Span) -> Self {
29 Self(Some(loc))29 Self(Some(loc))
30 }30 }
31}31}
225 #[cfg(feature = "exp-destruct")]225 #[cfg(feature = "exp-destruct")]
226 _ => return false,226 _ => return false,
227 };227 };
228 &desc.body.0 as &Expr == &Expr::Var(id.clone())228 desc.body.expr() == &Expr::Var(id.clone())
229 }229 }
230 _ => false,230 _ => false,
231 }231 }
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
45#[doc(hidden)]45#[doc(hidden)]
46pub use jrsonnet_macros;46pub use jrsonnet_macros;
47pub use jrsonnet_parser as parser;47pub use jrsonnet_parser as parser;
48use jrsonnet_parser::{ExprLocation, LocExpr, ParserSettings, Source, SourcePath};48use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath, Span};
49pub use obj::*;49pub use obj::*;
50use stack::check_depth;50use stack::check_depth;
51pub use tla::apply_tla;51pub use tla::apply_tla;
369 /// Executes code creating a new stack frame369 /// Executes code creating a new stack frame
370 pub fn push_val(370 pub fn push_val(
371 &self,371 &self,
372 e: &ExprLocation,372 e: &Span,
373 frame_desc: impl FnOnce() -> String,373 frame_desc: impl FnOnce() -> String,
374 f: impl FnOnce() -> Result<Val>,374 f: impl FnOnce() -> Result<Val>,
375 ) -> Result<Val> {375 ) -> Result<Val> {
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
88
9use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_gcmodule::{Cc, Trace, Weak};
10use jrsonnet_interner::IStr;10use jrsonnet_interner::IStr;
11use jrsonnet_parser::{ExprLocation, Visibility};11use jrsonnet_parser::{Span, Visibility};
12use rustc_hash::FxHashMap;12use rustc_hash::FxHashMap;
1313
14use crate::{14use crate::{
135 flags: ObjFieldFlags,135 flags: ObjFieldFlags,
136 original_index: FieldIndex,136 original_index: FieldIndex,
137 pub invoke: MaybeUnbound,137 pub invoke: MaybeUnbound,
138 pub location: Option<ExprLocation>,138 pub location: Option<Span>,
139}139}
140140
141pub trait ObjectAssertion: Trace {141pub trait ObjectAssertion: Trace {
896 add: bool,896 add: bool,
897 visibility: Visibility,897 visibility: Visibility,
898 original_index: FieldIndex,898 original_index: FieldIndex,
899 location: Option<ExprLocation>,899 location: Option<Span>,
900}900}
901901
902#[allow(clippy::missing_const_for_fn)]902#[allow(clippy::missing_const_for_fn)]
926 pub fn hide(self) -> Self {926 pub fn hide(self) -> Self {
927 self.with_visibility(Visibility::Hidden)927 self.with_visibility(Visibility::Hidden)
928 }928 }
929 pub fn with_location(mut self, location: ExprLocation) -> Self {929 pub fn with_location(mut self, location: Span) -> Self {
930 self.location = Some(location);930 self.location = Some(location);
931 self931 self
932 }932 }
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
5};5};
66
7use jrsonnet_gcmodule::Trace;7use jrsonnet_gcmodule::Trace;
8use jrsonnet_parser::{CodeLocation, ExprLocation, Source};8use jrsonnet_parser::{CodeLocation, Source, Span};
99
10use crate::{error::ErrorKind, Error};10use crate::{error::ErrorKind, Error};
1111
380 error: &Error,380 error: &Error,
381 ) -> Result<(), std::fmt::Error> {381 ) -> Result<(), std::fmt::Error> {
382 struct ResetData {382 struct ResetData {
383 loc: ExprLocation,383 loc: Span,
384 }384 }
385 use hi_doc::{source_to_ansi, Formatting, SnippetBuilder, Text};385 use hi_doc::{source_to_ansi, Formatting, SnippetBuilder, Text};
386386
399 }399 }
400 let trace = &error.trace();400 let trace = &error.trace();
401 let snippet_builder: RefCell<Option<SnippetBuilder>> = RefCell::new(None);401 let snippet_builder: RefCell<Option<SnippetBuilder>> = RefCell::new(None);
402 let mut last_location: Option<ExprLocation> = None;402 let mut last_location: Option<Span> = None;
403 let mut flush_builder = |data: Option<ResetData>| {403 let mut flush_builder = |data: Option<ResetData>| {
404 use std::fmt::Write;404 use std::fmt::Write;
405 let mut out = String::new();405 let mut out = String::new();
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
376 State, Val,376 State, Val,
377 function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName, ParamDefault}, CallLocation, ArgsLike, parse::parse_builtin_call},377 function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName, ParamDefault}, CallLocation, ArgsLike, parse::parse_builtin_call},
378 Result, Context, typed::Typed,378 Result, Context, typed::Typed,
379 parser::ExprLocation,379 parser::Span,
380 };380 };
381 const PARAMS: &'static [BuiltinParam] = &[381 const PARAMS: &'static [BuiltinParam] = &[
382 #(#params_desc)*382 #(#params_desc)*
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
385#[derive(Clone, PartialEq, Eq, Trace)]385#[derive(Clone, PartialEq, Eq, Trace)]
386#[trace(skip)]386#[trace(skip)]
387#[repr(C)]387#[repr(C)]
388pub struct ExprLocation(pub Source, pub u32, pub u32);388pub struct Span(pub Source, pub u32, pub u32);
389impl ExprLocation {389impl Span {
390 pub fn belongs_to(&self, other: &ExprLocation) -> bool {390 pub fn belongs_to(&self, other: &Span) -> bool {
391 other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2391 other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2
392 }392 }
393}393}
394394
395#[cfg(target_pointer_width = "64")]
396static_assertions::assert_eq_size!(ExprLocation, [u8; 16]);395static_assertions::assert_eq_size!(Span, (usize, usize));
397396
398impl Debug for ExprLocation {397impl Debug for Span {
399 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400 write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)399 write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)
401 }400 }
402}401}
403402
404/// Holds AST expression and its location in source file403/// Holds AST expression and its location in source file
405#[derive(Clone, PartialEq, Trace)]404#[derive(Clone, PartialEq, Trace)]
406pub struct LocExpr(pub Rc<Expr>, pub ExprLocation);405pub struct LocExpr(Rc<(Expr, Span)>);
407406impl LocExpr {
408#[cfg(target_pointer_width = "64")]407 pub fn new(expr: Expr, span: Span) -> Self {
408 Self(Rc::new((expr, span)))
409 }
410 #[inline]
411 pub fn span(&self) -> Span {
412 self.0 .1.clone()
413 }
414 #[inline]
415 pub fn expr(&self) -> &Expr {
416 &self.0 .0
417 }
418}
419
409static_assertions::assert_eq_size!(LocExpr, [u8; 24]);420static_assertions::assert_eq_size!(LocExpr, usize);
410421
411impl Debug for LocExpr {422impl Debug for LocExpr {
412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {423 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424 let expr = self.expr();
413 if f.alternate() {425 if f.alternate() {
414 write!(f, "{:#?}", self.0)?;426 write!(f, "{:#?}", expr)?;
415 } else {427 } else {
416 write!(f, "{:?}", self.0)?;428 write!(f, "{:?}", expr)?;
417 }429 }
418 write!(f, " from {:?}", self.1)?;430 write!(f, " from {:?}", self.span())?;
419 Ok(())431 Ok(())
420 }432 }
421}433}
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
232 pub rule var_expr(s: &ParserSettings) -> Expr232 pub rule var_expr(s: &ParserSettings) -> Expr
233 = n:id() { expr::Expr::Var(n) }233 = n:id() { expr::Expr::Var(n) }
234 pub rule id_loc(s: &ParserSettings) -> LocExpr234 pub rule id_loc(s: &ParserSettings) -> LocExpr
235 = a:position!() n:id() b:position!() { LocExpr(Rc::new(expr::Expr::Str(n)), ExprLocation(s.source.clone(), a as u32,b as u32)) }235 = a:position!() n:id() b:position!() { LocExpr::new(expr::Expr::Str(n), Span(s.source.clone(), a as u32,b as u32)) }
236 pub rule if_then_else_expr(s: &ParserSettings) -> Expr236 pub rule if_then_else_expr(s: &ParserSettings) -> Expr
237 = cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{237 = cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{
238 cond,238 cond,
299 use UnaryOpType::*;299 use UnaryOpType::*;
300 rule expr(s: &ParserSettings) -> LocExpr300 rule expr(s: &ParserSettings) -> LocExpr
301 = precedence! {301 = precedence! {
302 start:position!() v:@ end:position!() { LocExpr(Rc::new(v), ExprLocation(s.source.clone(), start as u32, end as u32)) }302 start:position!() v:@ end:position!() { LocExpr::new(v, Span(s.source.clone(), start as u32, end as u32)) }
303 --303 --
304 a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}304 a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}
305 a:(@) _ binop(<"??">) _ ensure_null_coaelse() b:@ {305 a:(@) _ binop(<"??">) _ ensure_null_coaelse() b:@ {
370/// Used for importstr values370/// Used for importstr values
371pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> LocExpr {371pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> LocExpr {
372 let len = str.len();372 let len = str.len();
373 LocExpr(373 LocExpr::new(Expr::Str(str), Span(settings.source.clone(), 0, len as u32))
374 Rc::new(Expr::Str(str)),
375 ExprLocation(settings.source.clone(), 0, len as u32),
376 )
377}374}
378375
379#[cfg(test)]376#[cfg(test)]
398395
399 macro_rules! el {396 macro_rules! el {
400 ($expr:expr, $from:expr, $to:expr$(,)?) => {397 ($expr:expr, $from:expr, $to:expr$(,)?) => {
401 LocExpr(398 LocExpr::new(
402 std::rc::Rc::new($expr),399 $expr,
403 ExprLocation(400 Span(
404 Source::new_virtual("<test>".into(), IStr::empty()),401 Source::new_virtual("<test>".into(), IStr::empty()),
405 $from,402 $from,
406 $to,403 $to,
407 ),404 ),
408 )405 )
409 };406 };
410 }407 }
411408