difftreelog
feat std.parseYaml intrinsic
in: master
6 files changed
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -7,11 +7,9 @@
edition = "2018"
[features]
-default = ["serialized-stdlib", "explaining-traces", "serde-json"]
+default = ["serialized-stdlib", "explaining-traces"]
# Serializes standard library AST instead of parsing them every run
-serialized-stdlib = ["serde", "bincode", "jrsonnet-parser/deserialize"]
-# Allow to convert Val into serde_json::Value and backwards
-serde-json = ["serde", "serde_json"]
+serialized-stdlib = ["bincode", "jrsonnet-parser/deserialize"]
# Rustc-like trace visualization
explaining-traces = ["annotate-snippets"]
# Allows library authors to throw custom errors
@@ -34,21 +32,17 @@
thiserror = "1.0"
gcmodule = { git = "https://github.com/CertainLach/gcmodule", branch = "jrsonnet" }
+serde = "1.0"
+serde_json = "1.0"
+serde_yaml = { git = "https://github.com/CertainLach/serde-yaml", branch = "feature/old-octals-quirk" }
+
[dependencies.anyhow]
version = "1.0"
optional = true
# Serialized stdlib
-[dependencies.serde]
-version = "1.0"
-optional = true
[dependencies.bincode]
version = "1.3.1"
-optional = true
-
-# Serde json
-[dependencies.serde_json]
-version = "1.0"
optional = true
# Explaining traces
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth4 error::{Error::*, Result},4 error::{Error::*, Result},5 operator::evaluate_mod_op,5 operator::evaluate_mod_op,6 parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context,6 parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,7 EvaluationState, FuncVal, IndexableVal, LazyVal, Val,7 IndexableVal, LazyVal, Val,8};8};9use format::{format_arr, format_obj};9use format::{format_arr, format_obj};10use gcmodule::Cc;10use gcmodule::Cc;11use jrsonnet_interner::IStr;11use jrsonnet_interner::IStr;12use jrsonnet_parser::{ArgsDesc, ExprLocation};12use jrsonnet_parser::{ArgsDesc, ExprLocation};13use jrsonnet_types::ty;13use jrsonnet_types::ty;14use serde::Deserialize;15use serde_yaml::DeserializingQuirks;14use std::{collections::HashMap, path::PathBuf, rc::Rc};16use std::{collections::HashMap, convert::TryFrom, path::PathBuf, rc::Rc};151716pub mod stdlib;18pub mod stdlib;17pub use stdlib::*;19pub use stdlib::*;128 ("strReplace".into(), builtin_str_replace),130 ("strReplace".into(), builtin_str_replace),129 ("splitLimit".into(), builtin_splitlimit),131 ("splitLimit".into(), builtin_splitlimit),130 ("parseJson".into(), builtin_parse_json),132 ("parseJson".into(), builtin_parse_json),133 ("parseYaml".into(), builtin_parse_yaml),131 ("asciiUpper".into(), builtin_ascii_upper),134 ("asciiUpper".into(), builtin_ascii_upper),132 ("asciiLower".into(), builtin_ascii_lower),135 ("asciiLower".into(), builtin_ascii_lower),133 ("member".into(), builtin_member),136 ("member".into(), builtin_member),206 })209 })207}210}208211209fn builtin_parse_json(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {212fn builtin_parse_json(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {213 parse_args!(context, "parseJson", args, 1, [214 0, s: ty!(string) => Val::Str;215 ], {216 let value: serde_json::Value = serde_json::from_str(&s).map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;217 Ok(Val::try_from(&value)?)218 })219}220221fn builtin_parse_yaml(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {210 parse_args!(context, "parseJson", args, 1, [222 parse_args!(context, "parseYaml", args, 1, [211 0, s: ty!(string) => Val::Str;223 0, s: ty!(string) => Val::Str;212 ], {224 ], {213 let state = EvaluationState::default();225 let value = serde_yaml::Deserializer::from_str_with_quirks(&s, DeserializingQuirks { old_octals: true });214 let path = PathBuf::from("std.parseJson").into();226 let mut out = vec![];227 for item in value {228 let value = serde_json::Value::deserialize(item)229 .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;230 let val = Val::try_from(&value)?;231 out.push(val);232 }233 if out.is_empty() {234 Ok(Val::Null)215 state.evaluate_snippet_raw(path ,s)235 } else if out.len() == 1 {236 Ok(out.into_iter().next().unwrap())237 } else {238 Ok(Val::Arr(out.into()))239 }216 })240 })217}241}218242crates/jrsonnet-evaluator/src/integrations/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/mod.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/mod.rs
@@ -1,2 +1 @@
-#[cfg(feature = "serde-json")]
pub mod serde;
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -15,7 +15,7 @@
Val::Num(n) => Self::Number(if n.fract() <= f64::EPSILON {
(*n as i64).into()
} else {
- Number::from_f64(*n).expect("to json number")
+ Number::from_f64(*n).expect("jsonnet numbers can't be infinite or NaN")
}),
Val::Arr(a) => {
let mut out = Vec::with_capacity(a.len());
@@ -29,7 +29,9 @@
for key in o.fields() {
out.insert(
(&key as &str).into(),
- (&o.get(key)?.expect("field exists")).try_into()?,
+ (&o.get(key)?
+ .expect("key is present in fields, so value should exist"))
+ .try_into()?,
);
}
Self::Object(out)
@@ -39,27 +41,30 @@
}
}
-impl From<&Value> for Val {
- fn from(v: &Value) -> Self {
- match v {
+impl TryFrom<&Value> for Val {
+ type Error = LocError;
+ fn try_from(v: &Value) -> Result<Self> {
+ Ok(match v {
Value::Null => Self::Null,
Value::Bool(v) => Self::Bool(*v),
- Value::Number(n) => Self::Num(n.as_f64().expect("as f64")),
+ Value::Number(n) => Self::Num(n.as_f64().ok_or_else(|| {
+ RuntimeError(format!("json number can't be represented as jsonnet: {}", n).into())
+ })?),
Value::String(s) => Self::Str((s as &str).into()),
Value::Array(a) => {
let mut out: Vec<Self> = Vec::with_capacity(a.len());
for v in a {
- out.push(v.into());
+ out.push(v.try_into()?);
}
Self::Arr(out.into())
}
Value::Object(o) => {
let mut builder = ObjValueBuilder::with_capacity(o.len());
for (k, v) in o {
- builder.member((k as &str).into()).value(v.into());
+ builder.member((k as &str).into()).value(v.try_into()?);
}
Self::Obj(builder.build())
}
- }
+ })
}
}
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -98,7 +98,7 @@
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;
+ offset = source_code.len().saturating_sub(1);
true
} else {
false
crates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -23,6 +23,7 @@
trace:: $intrinsic(trace),
id:: $intrinsic(id),
parseJson:: $intrinsic(parseJson),
+ parseYaml:: $intrinsic(parseYaml),
log:: $intrinsic(log),
pow:: $intrinsic(pow),