difftreelog
Merge pull request #27 from CertainLach/syntax-error-display
in: master
Syntax error display
8 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7,6 +7,7 @@
checksum = "5c96c3d1062ea7101741480185a6a1275eab01cbe8b20e378d1311bc056d2e08"
dependencies = [
"unicode-width",
+ "yansi-term",
]
[[package]]
@@ -513,3 +514,12 @@
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "yansi-term"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5c30ade05e61656247b2e334a031dfd0cc466fadef865bdcdea8d537951bf1"
+dependencies = [
+ "winapi",
+]
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -55,6 +55,7 @@
# Explaining traces
[dependencies.annotate-snippets]
version = "0.9.0"
+features = ["color"]
optional = true
[build-dependencies]
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -78,7 +78,11 @@
ImportBadFileUtf8(PathBuf),
#[error("tried to import {1} from {0}, but imports is not supported")]
ImportNotSupported(PathBuf, PathBuf),
- #[error("syntax error")]
+ #[error(
+ "syntax error, expected one of {}, got {:?}",
+ .error.expected,
+ .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())
+ )]
ImportSyntaxError {
path: Rc<PathBuf>,
source_code: Rc<str>,
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -419,18 +419,12 @@
use Expr::*;
let LocExpr(expr, loc) = expr;
Ok(match &**expr {
- Literal(LiteralType::This) => Val::Obj(
- context
- .this()
- .clone()
- .ok_or_else(|| CantUseSelfOutsideOfObject)?,
- ),
- Literal(LiteralType::Dollar) => Val::Obj(
- context
- .dollar()
- .clone()
- .ok_or_else(|| NoTopLevelObjectFound)?,
- ),
+ Literal(LiteralType::This) => {
+ Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)
+ }
+ Literal(LiteralType::Dollar) => {
+ Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)
+ }
Literal(LiteralType::True) => Val::Bool(true),
Literal(LiteralType::False) => Val::Bool(false),
Literal(LiteralType::Null) => Val::Null,
crates/jrsonnet-evaluator/src/trace/location.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/location.rs
+++ b/crates/jrsonnet-evaluator/src/trace/location.rs
@@ -1,5 +1,7 @@
#[derive(Clone, PartialEq, Debug)]
pub struct CodeLocation {
+ pub offset: usize,
+
pub line: usize,
pub column: usize,
@@ -25,6 +27,7 @@
let mut out = vec![
CodeLocation {
+ offset: 0,
column: 0,
line: 0,
line_start_offset: 0,
@@ -40,6 +43,7 @@
Some(x) if x.0 == pos => {
let out_idx = x.1;
with_no_known_line_ending.push(out_idx);
+ out[out_idx].offset = pos;
out[out_idx].line = line;
out[out_idx].column = column;
out[out_idx].line_start_offset = this_line_offset;
@@ -82,12 +86,14 @@
),
vec![
CodeLocation {
+ offset: 0,
line: 1,
column: 2,
line_start_offset: 0,
- line_end_offset: 11
+ line_end_offset: 11,
},
CodeLocation {
+ offset: 14,
line: 2,
column: 4,
line_start_offset: 12,
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -1,6 +1,6 @@
mod location;
-use crate::{EvaluationState, LocError};
+use crate::{error::Error, EvaluationState, LocError};
pub use location::*;
use std::path::PathBuf;
@@ -87,6 +87,33 @@
error: &LocError,
) -> Result<(), std::fmt::Error> {
writeln!(out, "{}", error.error())?;
+ if let Error::ImportSyntaxError {
+ path,
+ source_code,
+ error,
+ } = error.error()
+ {
+ use std::fmt::Write;
+ let mut n = self.resolver.resolve(path);
+ let mut offset = error.location.offset;
+ let is_eof = if offset >= source_code.len() {
+ offset = source_code.len() - 1;
+ true
+ } else {
+ false
+ };
+ let mut location = offset_to_location(source_code, &[offset])
+ .into_iter()
+ .next()
+ .unwrap();
+ if is_eof {
+ location.column += 1;
+ }
+
+ write!(n, ":").unwrap();
+ print_code_location(&mut n, &location, &location).unwrap();
+ write!(out, "{:<p$}{}", "", n, p = self.padding,)?;
+ }
let file_names = error
.trace()
.0
@@ -167,52 +194,101 @@
evaluation_state: &EvaluationState,
error: &LocError,
) -> Result<(), std::fmt::Error> {
- use annotate_snippets::{
- display_list::{DisplayList, FormatOptions},
- snippet::{AnnotationType, Slice, Snippet, SourceAnnotation},
- };
writeln!(out, "{}", error.error())?;
+ if let Error::ImportSyntaxError {
+ path,
+ source_code,
+ error,
+ } = error.error()
+ {
+ let mut offset = error.location.offset;
+ if offset >= source_code.len() {
+ offset = source_code.len() - 1;
+ }
+ let mut location = offset_to_location(source_code, &[offset])
+ .into_iter()
+ .next()
+ .unwrap();
+ if location.column >= 1 {
+ location.column -= 1;
+ }
+
+ self.print_snippet(
+ out,
+ source_code,
+ path,
+ &location,
+ &location,
+ "^ syntax error",
+ )?;
+ }
let trace = &error.trace();
for item in trace.0.iter() {
let desc = &item.desc;
let source = item.location.clone();
let start_end = evaluation_state.map_source_locations(&source.0, &[source.1, source.2]);
- let source_fragment: String = evaluation_state
- .get_source(&source.0)
- .unwrap()
- .chars()
- .skip(start_end[0].line_start_offset)
- .take(start_end[1].line_end_offset - start_end[0].line_start_offset)
- .collect();
+ self.print_snippet(
+ out,
+ &evaluation_state.get_source(&source.0).unwrap(),
+ &source.0,
+ &start_end[0],
+ &start_end[1],
+ desc,
+ )?;
+ }
+ Ok(())
+ }
+}
+
+impl ExplainingFormat {
+ fn print_snippet(
+ &self,
+ out: &mut dyn std::fmt::Write,
+ source: &str,
+ origin: &PathBuf,
+ start: &CodeLocation,
+ end: &CodeLocation,
+ desc: &str,
+ ) -> Result<(), std::fmt::Error> {
+ use annotate_snippets::{
+ display_list::{DisplayList, FormatOptions},
+ snippet::{AnnotationType, Slice, Snippet, SourceAnnotation},
+ };
+
+ let source_fragment: String = source
+ .chars()
+ .skip(start.line_start_offset)
+ .take(end.line_end_offset - end.line_start_offset)
+ .collect();
- let origin = self.resolver.resolve(&source.0);
- let snippet = Snippet {
- opt: FormatOptions {
- color: true,
- ..Default::default()
- },
- title: None,
- footer: vec![],
- slices: vec![Slice {
- source: &source_fragment,
- line_start: start_end[0].line,
- origin: Some(&origin),
- fold: false,
- annotations: vec![SourceAnnotation {
- label: desc,
- annotation_type: AnnotationType::Error,
- range: (
- source.1 - start_end[0].line_start_offset,
- source.2 - start_end[0].line_start_offset,
- ),
- }],
+ let origin = self.resolver.resolve(origin);
+ let snippet = Snippet {
+ opt: FormatOptions {
+ color: true,
+ ..Default::default()
+ },
+ title: None,
+ footer: vec![],
+ slices: vec![Slice {
+ source: &source_fragment,
+ line_start: start.line,
+ origin: Some(&origin),
+ fold: false,
+ annotations: vec![SourceAnnotation {
+ label: desc,
+ annotation_type: AnnotationType::Error,
+ range: (
+ start.offset - start.line_start_offset,
+ end.offset - start.line_start_offset,
+ ),
}],
- };
+ }],
+ };
- let dl = DisplayList::from(snippet);
- writeln!(out, "{}", dl)?;
- }
+ let dl = DisplayList::from(snippet);
+ writeln!(out, "{}", dl)?;
+
Ok(())
}
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::Error::*,7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};13use std::{14 cell::RefCell,15 collections::HashMap,16 fmt::{Debug, Display},17 rc::Rc,18};1920enum LazyValInternals {21 Computed(Val),22 Waiting(Box<dyn Fn() -> Result<Val>>),23}24#[derive(Clone)]25pub struct LazyVal(Rc<RefCell<LazyValInternals>>);26impl LazyVal {27 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {28 Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))29 }30 pub fn new_resolved(val: Val) -> Self {31 Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))32 }33 pub fn evaluate(&self) -> Result<Val> {34 let new_value = match &*self.0.borrow() {35 LazyValInternals::Computed(v) => return Ok(v.clone()),36 LazyValInternals::Waiting(f) => f()?,37 };38 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());39 Ok(new_value)40 }41}4243#[macro_export]44macro_rules! lazy_val {45 ($f: expr) => {46 $crate::LazyVal::new(Box::new($f))47 };48}49#[macro_export]50macro_rules! resolved_lazy_val {51 ($f: expr) => {52 $crate::LazyVal::new_resolved($f)53 };54}55impl Debug for LazyVal {56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {57 write!(f, "Lazy")58 }59}60impl PartialEq for LazyVal {61 fn eq(&self, other: &Self) -> bool {62 Rc::ptr_eq(&self.0, &other.0)63 }64}6566#[derive(Debug, PartialEq)]67pub struct FuncDesc {68 pub name: Rc<str>,69 pub ctx: Context,70 pub params: ParamsDesc,71 pub body: LocExpr,72}7374#[derive(Debug)]75pub enum FuncVal {76 /// Plain function implemented in jsonnet77 Normal(FuncDesc),78 /// Standard library function79 Intrinsic(Rc<str>),80 /// Library functions implemented in native81 NativeExt(Rc<str>, Rc<NativeCallback>),82}8384impl PartialEq for FuncVal {85 fn eq(&self, other: &Self) -> bool {86 match (self, other) {87 (Self::Normal(a), Self::Normal(b)) => a == b,88 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,89 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,90 (..) => false,91 }92 }93}94impl FuncVal {95 pub fn is_ident(&self) -> bool {96 matches!(&self, Self::Intrinsic(n) if n as &str == "id")97 }98 pub fn name(&self) -> Rc<str> {99 match self {100 Self::Normal(normal) => normal.name.clone(),101 Self::Intrinsic(name) => format!("std.{}", name).into(),102 Self::NativeExt(n, _) => format!("native.{}", n).into(),103 }104 }105 pub fn evaluate(106 &self,107 call_ctx: Context,108 loc: &Option<ExprLocation>,109 args: &ArgsDesc,110 tailstrict: bool,111 ) -> Result<Val> {112 match self {113 Self::Normal(func) => {114 let ctx = parse_function_call(115 call_ctx,116 Some(func.ctx.clone()),117 &func.params,118 args,119 tailstrict,120 )?;121 evaluate(ctx, &func.body)122 }123 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),124 Self::NativeExt(_name, handler) => {125 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;126 let mut out_args = Vec::with_capacity(handler.params.len());127 for p in handler.params.0.iter() {128 out_args.push(args.binding(p.0.clone())?.evaluate()?);129 }130 Ok(handler.call(&out_args)?)131 }132 }133 }134135 pub fn evaluate_map(136 &self,137 call_ctx: Context,138 args: &HashMap<Rc<str>, Val>,139 tailstrict: bool,140 ) -> Result<Val> {141 match self {142 Self::Normal(func) => {143 let ctx = parse_function_call_map(144 call_ctx,145 Some(func.ctx.clone()),146 &func.params,147 args,148 tailstrict,149 )?;150 evaluate(ctx, &func.body)151 }152 Self::Intrinsic(_) => todo!(),153 Self::NativeExt(_, _) => todo!(),154 }155 }156157 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {158 match self {159 Self::Normal(func) => {160 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;161 evaluate(ctx, &func.body)162 }163 Self::Intrinsic(_) => todo!(),164 Self::NativeExt(_, _) => todo!(),165 }166 }167}168169#[derive(Debug, Clone, Copy, PartialEq)]170pub enum ValType {171 Bool,172 Null,173 Str,174 Num,175 Arr,176 Obj,177 Func,178}179impl ValType {180 pub const fn name(&self) -> &'static str {181 use ValType::*;182 match self {183 Bool => "boolean",184 Null => "null",185 Str => "string",186 Num => "number",187 Arr => "array",188 Obj => "object",189 Func => "function",190 }191 }192}193impl Display for ValType {194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {195 write!(f, "{}", self.name())196 }197}198199#[derive(Clone)]200pub enum ManifestFormat {201 YamlStream(Box<ManifestFormat>),202 Yaml(usize),203 Json(usize),204 ToString,205 String,206}207208#[derive(Debug, Clone)]209pub enum Val {210 Bool(bool),211 Null,212 Str(Rc<str>),213 Num(f64),214 Lazy(LazyVal),215 Arr(Rc<Vec<Val>>),216 Obj(ObjValue),217 Func(Rc<FuncVal>),218}219220macro_rules! matches_unwrap {221 ($e: expr, $p: pat, $r: expr) => {222 match $e {223 $p => $r,224 _ => panic!("no match"),225 }226 };227}228impl Val {229 /// Creates `Val::Num` after checking for numeric overflow.230 /// As numbers are `f64`, we can just check for their finity.231 pub fn new_checked_num(num: f64) -> Result<Self> {232 if num.is_finite() {233 Ok(Self::Num(num))234 } else {235 throw!(RuntimeError("overflow".into()))236 }237 }238239 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {240 let this_type = self.value_type()?;241 if this_type != val_type {242 throw!(TypeMismatch(context, vec![val_type], this_type))243 } else {244 Ok(())245 }246 }247 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {248 self.assert_type(context, ValType::Bool)?;249 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Bool(v), v))250 }251 pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {252 self.assert_type(context, ValType::Str)?;253 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Str(v), v))254 }255 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {256 self.assert_type(context, ValType::Num)?;257 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Num(v), v))258 }259 pub fn inplace_unwrap(&mut self) -> Result<()> {260 while let Self::Lazy(lazy) = self {261 *self = lazy.evaluate()?;262 }263 Ok(())264 }265 pub fn unwrap_if_lazy(&self) -> Result<Self> {266 Ok(if let Self::Lazy(v) = self {267 v.evaluate()?.unwrap_if_lazy()?268 } else {269 self.clone()270 })271 }272 pub fn value_type(&self) -> Result<ValType> {273 Ok(match self {274 Self::Str(..) => ValType::Str,275 Self::Num(..) => ValType::Num,276 Self::Arr(..) => ValType::Arr,277 Self::Obj(..) => ValType::Obj,278 Self::Bool(_) => ValType::Bool,279 Self::Null => ValType::Null,280 Self::Func(..) => ValType::Func,281 Self::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,282 })283 }284285 pub fn to_string(&self) -> Result<Rc<str>> {286 Ok(match self.unwrap_if_lazy()? {287 Self::Bool(true) => "true".into(),288 Self::Bool(false) => "false".into(),289 Self::Null => "null".into(),290 Self::Str(s) => s,291 v => manifest_json_ex(292 &v,293 &ManifestJsonOptions {294 padding: "",295 mtype: ManifestType::ToString,296 },297 )?298 .into(),299 })300 }301302 /// Expects value to be object, outputs (key, manifested value) pairs303 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {304 let obj = match self {305 Self::Obj(obj) => obj,306 _ => throw!(MultiManifestOutputIsNotAObject),307 };308 let keys = obj.visible_fields();309 let mut out = Vec::with_capacity(keys.len());310 for key in keys {311 let value = obj312 .get(key.clone())?313 .expect("item in object")314 .manifest(ty)?;315 out.push((key, value));316 }317 Ok(out)318 }319320 /// Expects value to be array, outputs manifested values321 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {322 let arr = match self {323 Self::Arr(a) => a,324 _ => throw!(StreamManifestOutputIsNotAArray),325 };326 let mut out = Vec::with_capacity(arr.len());327 for i in arr.iter() {328 out.push(i.manifest(ty)?);329 }330 Ok(out)331 }332333 pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {334 Ok(match ty {335 ManifestFormat::YamlStream(format) => {336 let arr = match self {337 Self::Arr(a) => a,338 _ => throw!(StreamManifestOutputIsNotAArray),339 };340 let mut out = String::new();341342 match format as &ManifestFormat {343 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),344 ManifestFormat::String => throw!(StreamManifestCannotNestString),345 _ => {}346 };347348 if !arr.is_empty() {349 for v in arr.iter() {350 out.push_str("---\n");351 out.push_str(&v.manifest(format)?);352 out.push_str("\n");353 }354 out.push_str("...");355 }356357 out.into()358 }359 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,360 ManifestFormat::Json(padding) => self.to_json(*padding)?,361 ManifestFormat::ToString => self.to_string()?,362 ManifestFormat::String => match self {363 Self::Str(s) => s.clone(),364 _ => throw!(StringManifestOutputIsNotAString),365 },366 })367 }368369 /// For manifestification370 pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {371 manifest_json_ex(372 self,373 &ManifestJsonOptions {374 padding: &" ".repeat(padding),375 mtype: if padding == 0 {376 ManifestType::Minify377 } else {378 ManifestType::Manifest379 },380 },381 )382 .map(|s| s.into())383 }384385 /// Calls `std.manifestJson`386 #[cfg(feature = "faster")]387 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {388 manifest_json_ex(389 self,390 &ManifestJsonOptions {391 padding: &" ".repeat(padding),392 mtype: ManifestType::Std,393 },394 )395 .map(|s| s.into())396 }397398 /// Calls `std.manifestJson`399 #[cfg(not(feature = "faster"))]400 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {401 with_state(|s| {402 let ctx = s403 .create_default_context()?404 .with_var("__tmp__to_json__".into(), self.clone())?;405 Ok(evaluate(406 ctx,407 &el!(Expr::Apply(408 el!(Expr::Index(409 el!(Expr::Var("std".into())),410 el!(Expr::Str("manifestJsonEx".into()))411 )),412 ArgsDesc(vec![413 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),414 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))415 ]),416 false417 )),418 )?419 .try_cast_str("to json")?)420 })421 }422 pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {423 with_state(|s| {424 let ctx = s425 .create_default_context()?426 .with_var("__tmp__to_json__".into(), self.clone());427 Ok(evaluate(428 ctx,429 &el!(Expr::Apply(430 el!(Expr::Index(431 el!(Expr::Var("std".into())),432 el!(Expr::Str("manifestYamlDoc".into()))433 )),434 ArgsDesc(vec![435 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),436 Arg(437 None,438 el!(Expr::Literal(if padding != 0 {439 LiteralType::True440 } else {441 LiteralType::False442 }))443 )444 ]),445 false446 )),447 )?448 .try_cast_str("to json")?)449 })450 }451}452453const fn is_function_like(val: &Val) -> bool {454 matches!(val, Val::Func(_))455}456457/// Native implementation of `std.primitiveEquals`458pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {459 Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {460 (Val::Bool(a), Val::Bool(b)) => a == b,461 (Val::Null, Val::Null) => true,462 (Val::Str(a), Val::Str(b)) => a == b,463 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,464 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(465 "primitiveEquals operates on primitive types, got array".into(),466 )),467 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(468 "primitiveEquals operates on primitive types, got object".into(),469 )),470 (a, b) if is_function_like(&a) && is_function_like(&b) => {471 throw!(RuntimeError("cannot test equality of functions".into()))472 }473 (_, _) => false,474 })475}476477/// Native implementation of `std.equals`478pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {479 let val_a = val_a.unwrap_if_lazy()?;480 let val_b = val_b.unwrap_if_lazy()?;481482 if val_a.value_type()? != val_b.value_type()? {483 return Ok(false);484 }485 match (val_a, val_b) {486 // Cant test for ptr equality, because all fields needs to be evaluated487 (Val::Arr(a), Val::Arr(b)) => {488 if a.len() != b.len() {489 return Ok(false);490 }491 for (a, b) in a.iter().zip(b.iter()) {492 if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {493 return Ok(false);494 }495 }496 Ok(true)497 }498 (Val::Obj(a), Val::Obj(b)) => {499 let fields = a.visible_fields();500 if fields != b.visible_fields() {501 return Ok(false);502 }503 for field in fields {504 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {505 return Ok(false);506 }507 }508 Ok(true)509 }510 (a, b) => Ok(primitive_equals(&a, &b)?),511 }512}crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -37,7 +37,7 @@
rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()
rule id() = quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")
- rule keyword(id: &'static str)
+ rule keyword(id: &'static str) -> ()
= ##parse_string_literal(id) end_of_ident()
// Adds location data information to existing expression
rule l(s: &ParserSettings, x: rule<Expr>) -> LocExpr
@@ -85,11 +85,11 @@
[' ' | '\t']*<, {prefix.len() - 1}> "|||"
{let mut l = empty_lines.to_owned(); l.push_str(first_line); l.extend(lines); l}
pub rule string() -> String
- = "\"" str:$(("\\\"" / "\\\\" / (!['"'][_]))*) "\"" {unescape::unescape(str).unwrap()}
+ = quiet!{ "\"" str:$(("\\\"" / "\\\\" / (!['"'][_]))*) "\"" {unescape::unescape(str).unwrap()}
/ "'" str:$(("\\'" / "\\\\" / (!['\''][_]))*) "'" {unescape::unescape(str).unwrap()}
/ "@'" str:$(("''" / (!['\''][_]))*) "'" {str.replace("''", "'")}
/ "@\"" str:$(("\"\"" / (!['"'][_]))*) "\"" {str.replace("\"\"", "\"")}
- / string_block()
+ / string_block() } / expected!("<string>")
pub rule field_name(s: &ParserSettings) -> expr::FieldName
= name:$(id()) {expr::FieldName::Fixed(name.into())}
@@ -208,54 +208,59 @@
SliceDesc { start, end, step }
}
+ rule binop(x: rule<()>) -> ()
+ = quiet!{ x() } / expected!("<binary op>")
+ rule unaryop(x: rule<()>) -> ()
+ = quiet!{ x() } / expected!("<unary op>")
+
rule expr(s: &ParserSettings) -> LocExpr
= start:position!() a:precedence! {
- a:(@) _ "||" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Or, b))}
+ a:(@) _ binop(<"||">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Or, b))}
--
- a:(@) _ "&&" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::And, b))}
+ a:(@) _ binop(<"&&">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::And, b))}
--
- a:(@) _ "|" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitOr, b))}
+ a:(@) _ binop(<"|">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitOr, b))}
--
- a:@ _ "^" _ b:(@) {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitXor, b))}
+ a:@ _ binop(<"^">) _ b:(@) {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitXor, b))}
--
- a:(@) _ "&" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitAnd, b))}
+ a:(@) _ binop(<"&">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitAnd, b))}
--
- a:(@) _ "==" _ b:@ {loc_expr_todo!(Expr::Apply(
+ a:(@) _ binop(<"==">) _ b:@ {loc_expr_todo!(Expr::Apply(
el!(Expr::Intrinsic("equals".into())),
ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
true
))}
- a:(@) _ "!=" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, el!(Expr::Apply(
+ a:(@) _ binop(<"!=">) _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, el!(Expr::Apply(
el!(Expr::Intrinsic("equals".into())),
ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
true
))))}
--
- a:(@) _ "<" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lt, b))}
- a:(@) _ ">" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gt, b))}
- a:(@) _ "<=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lte, b))}
- a:(@) _ ">=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gte, b))}
- a:(@) _ keyword("in") _ b:@ {loc_expr_todo!(Expr::Apply(
+ a:(@) _ binop(<"<">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lt, b))}
+ a:(@) _ binop(<">">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gt, b))}
+ a:(@) _ binop(<"<=">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lte, b))}
+ a:(@) _ binop(<">=">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gte, b))}
+ a:(@) _ binop(<keyword("in")>) _ b:@ {loc_expr_todo!(Expr::Apply(
el!(Expr::Intrinsic("objectHasEx".into())), ArgsDesc(vec![Arg(None, b), Arg(None, a), Arg(None, el!(Expr::Literal(LiteralType::True)))]),
true
))}
--
- a:(@) _ "<<" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lhs, b))}
- a:(@) _ ">>" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Rhs, b))}
+ a:(@) _ binop(<"<<">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lhs, b))}
+ a:(@) _ binop(<">>">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Rhs, b))}
--
- a:(@) _ "+" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Add, b))}
- a:(@) _ "-" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Sub, b))}
+ a:(@) _ binop(<"+">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Add, b))}
+ a:(@) _ binop(<"-">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Sub, b))}
--
- a:(@) _ "*" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Mul, b))}
- a:(@) _ "/" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Div, b))}
- a:(@) _ "%" _ b:@ {loc_expr_todo!(Expr::Apply(
+ a:(@) _ binop(<"*">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Mul, b))}
+ a:(@) _ binop(<"/">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Div, b))}
+ a:(@) _ binop(<"%">) _ b:@ {loc_expr_todo!(Expr::Apply(
el!(Expr::Intrinsic("mod".into())), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
false
))}
--
- "-" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Minus, b))}
- "!" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, b))}
- "~" _ b:@ { loc_expr_todo!(Expr::UnaryOp(UnaryOpType::BitNot, b)) }
+ unaryop(<"-">) _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Minus, b))}
+ unaryop(<"!">) _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, b))}
+ unaryop(<"~">) _ b:@ { loc_expr_todo!(Expr::UnaryOp(UnaryOpType::BitNot, b)) }
--
a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Apply(
el!(Expr::Intrinsic("slice".into())),