git.delta.rocks / jrsonnet / refs/commits / 9f8d4fc520b3

difftreelog

feat friendlier errors

Yaroslav Bolyukin2022-05-26parent: #96da6f3.patch.diff
in: master

8 files changed

modifiedCargo.lockdiffbeforeafterboth
2# It is not intended for manual editing.2# It is not intended for manual editing.
3version = 33version = 3
4
5[[package]]
6name = "ahash"
7version = "0.7.6"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47"
10dependencies = [
11 "getrandom",
12 "once_cell",
13 "version_check",
14]
415
5[[package]]16[[package]]
6name = "annotate-snippets"17name = "annotate-snippets"
68source = "registry+https://github.com/rust-lang/crates.io-index"79source = "registry+https://github.com/rust-lang/crates.io-index"
69checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"80checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
81
82[[package]]
83name = "cfg-if"
84version = "1.0.0"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
7087
71[[package]]88[[package]]
72name = "clap"89name = "clap"
151 "synstructure",168 "synstructure",
152]169]
170
171[[package]]
172name = "getrandom"
173version = "0.2.6"
174source = "registry+https://github.com/rust-lang/crates.io-index"
175checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"
176dependencies = [
177 "cfg-if 1.0.0",
178 "libc",
179 "wasi",
180]
153181
154[[package]]182[[package]]
155name = "hashbrown"183name = "hashbrown"
156version = "0.11.2"184version = "0.11.2"
157source = "registry+https://github.com/rust-lang/crates.io-index"185source = "registry+https://github.com/rust-lang/crates.io-index"
158checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"186checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
187
188[[package]]
189name = "hashbrown"
190version = "0.12.1"
191source = "registry+https://github.com/rust-lang/crates.io-index"
192checksum = "db0d4cf898abf0081f964436dc980e96670a0f36863e4b83aaacdb65c9d7ccc3"
193dependencies = [
194 "ahash",
195]
159196
160[[package]]197[[package]]
161name = "heck"198name = "heck"
179checksum = "bc633605454125dec4b66843673f01c7df2b89479b32e0ed634e43a91cff62a5"216checksum = "bc633605454125dec4b66843673f01c7df2b89479b32e0ed634e43a91cff62a5"
180dependencies = [217dependencies = [
181 "autocfg",218 "autocfg",
182 "hashbrown",219 "hashbrown 0.11.2",
183]220]
184221
185[[package]]222[[package]]
221 "base64",258 "base64",
222 "bincode",259 "bincode",
223 "gcmodule",260 "gcmodule",
261 "hashbrown 0.12.1",
224 "jrsonnet-interner",262 "jrsonnet-interner",
225 "jrsonnet-macros",263 "jrsonnet-macros",
226 "jrsonnet-parser",264 "jrsonnet-parser",
232 "serde",270 "serde",
233 "serde_json",271 "serde_json",
234 "serde_yaml",272 "serde_yaml",
273 "static_assertions",
274 "strsim",
235 "thiserror",275 "thiserror",
236]276]
237277
240version = "0.4.2"280version = "0.4.2"
241dependencies = [281dependencies = [
242 "gcmodule",282 "gcmodule",
283 "hashbrown 0.12.1",
243 "rustc-hash",284 "rustc-hash",
244 "serde",285 "serde",
245]286]
262 "jrsonnet-stdlib",303 "jrsonnet-stdlib",
263 "peg",304 "peg",
264 "serde",305 "serde",
306 "static_assertions",
265]307]
266308
267[[package]]309[[package]]
293335
294[[package]]336[[package]]
295name = "libc"337name = "libc"
296version = "0.2.108"338version = "0.2.125"
297source = "registry+https://github.com/rust-lang/crates.io-index"339source = "registry+https://github.com/rust-lang/crates.io-index"
298checksum = "8521a1b57e76b1ec69af7599e75e38e7b7fad6610f037db8c79b127201b5d119"340checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b"
299341
300[[package]]342[[package]]
301name = "linked-hash-map"343name = "linked-hash-map"
337 "mimalloc-sys",379 "mimalloc-sys",
338]380]
381
382[[package]]
383name = "once_cell"
384version = "1.10.0"
385source = "registry+https://github.com/rust-lang/crates.io-index"
386checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9"
339387
340[[package]]388[[package]]
341name = "os_str_bytes"389name = "os_str_bytes"
359source = "registry+https://github.com/rust-lang/crates.io-index"407source = "registry+https://github.com/rust-lang/crates.io-index"
360checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3"408checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3"
361dependencies = [409dependencies = [
362 "cfg-if",410 "cfg-if 0.1.10",
363 "cloudabi",411 "cloudabi",
364 "libc",412 "libc",
365 "redox_syscall",413 "redox_syscall",
515source = "registry+https://github.com/rust-lang/crates.io-index"563source = "registry+https://github.com/rust-lang/crates.io-index"
516checksum = "1ecab6c735a6bb4139c0caafd0cc3635748bbb3acf4550e8138122099251f309"564checksum = "1ecab6c735a6bb4139c0caafd0cc3635748bbb3acf4550e8138122099251f309"
565
566[[package]]
567name = "static_assertions"
568version = "1.1.0"
569source = "registry+https://github.com/rust-lang/crates.io-index"
570checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
517571
518[[package]]572[[package]]
519name = "strsim"573name = "strsim"
597source = "registry+https://github.com/rust-lang/crates.io-index"651source = "registry+https://github.com/rust-lang/crates.io-index"
598checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe"652checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe"
653
654[[package]]
655name = "wasi"
656version = "0.10.2+wasi-snapshot-preview1"
657source = "registry+https://github.com/rust-lang/crates.io-index"
658checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
599659
600[[package]]660[[package]]
601name = "winapi"661name = "winapi"
modifiedCargo.tomldiffbeforeafterboth
2members = [2members = ["crates/*", "bindings/jsonnet", "cmds/jrsonnet"]
3 "crates/*",
4 "bindings/jsonnet",
5 "cmds/jrsonnet",
6]
73
8[profile.test]4[profile.test]
14codegen-units = 110codegen-units = 1
15debug = 011debug = 0
16panic = "abort"12panic = "abort"
13strip = true
1714
modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
32 out: RefCell<HashMap<PathBuf, Vec<u8>>>,32 out: RefCell<HashMap<PathBuf, Vec<u8>>>,
33}33}
34impl ImportResolver for CallbackImportResolver {34impl ImportResolver for CallbackImportResolver {
35 fn resolve_file(&self, from: &Path, path: &Path) -> Result<PathBuf> {35 fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {
36 let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();36 let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();
37 let rel = CString::new(path.to_str().unwrap()).unwrap().into_raw();37 let rel = CString::new(path).unwrap().into_raw();
38 let found_here: *mut c_char = null_mut();38 let found_here: *mut c_char = null_mut();
39 let mut success: i32 = 0;39 let mut success: i32 = 0;
40 let result_ptr = unsafe {40 let result_ptr = unsafe {
108 }108 }
109}109}
110impl ImportResolver for NativeImportResolver {110impl ImportResolver for NativeImportResolver {
111 fn resolve_file(&self, from: &Path, path: &Path) -> Result<PathBuf> {111 fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {
112 let mut new_path = from.to_owned();112 let mut new_path = from.to_owned();
113 new_path.push(path);113 new_path.push(path);
114 if new_path.exists() {114 if new_path.exists() {
115 Ok(new_path.into())115 Ok(new_path)
116 } else {116 } else {
117 for library_path in self.library_paths.borrow().iter() {117 for library_path in self.library_paths.borrow().iter() {
118 let mut cloned = library_path.clone();118 let mut cloned = library_path.clone();
119 cloned.push(path);119 cloned.push(path);
120 if cloned.exists() {120 if cloned.exists() {
121 return Ok(cloned.into());121 return Ok(cloned);
122 }122 }
123 }123 }
124 throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))124 throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
modifiedbindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth
21 let name = CStr::from_ptr(name);21 let name = CStr::from_ptr(name);
22 let value = CStr::from_ptr(value);22 let value = CStr::from_ptr(value);
23 vm.add_ext_code(23 vm.add_ext_code(name.to_str().unwrap(), value.to_str().unwrap().into())
24 name.to_str().unwrap().into(),
25 value.to_str().unwrap().into(),
26 )
27 .unwrap()24 .unwrap()
43 let value = CStr::from_ptr(value);40 let value = CStr::from_ptr(value);
44 vm.add_tla_code(41 vm.add_tla_code(name.to_str().unwrap().into(), value.to_str().unwrap())
45 name.to_str().unwrap().into(),
46 value.to_str().unwrap().into(),
47 )
48 .unwrap()42 .unwrap()
49}43}
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
7edition = "2021"7edition = "2021"
88
9[features]9[features]
10default = ["serialized-stdlib", "explaining-traces"]10default = ["serialized-stdlib", "explaining-traces", "friendly-errors"]
11# Serializes standard library AST instead of parsing them every run11# Serializes standard library AST instead of parsing them every run
12serialized-stdlib = ["bincode", "jrsonnet-parser/serde"]12serialized-stdlib = ["bincode", "jrsonnet-parser/serde"]
13# Rustc-like trace visualization13# Rustc-like trace visualization
14explaining-traces = ["annotate-snippets"]14explaining-traces = ["annotate-snippets"]
15# Allows library authors to throw custom errors15# Allows library authors to throw custom errors
16anyhow-error = ["anyhow"]16anyhow-error = ["anyhow"]
17# Provides helpful explaintations to errors, at cost of adding
18# more dependencies and slowing down error path
19friendly-errors = ["strsim"]
1720
18# Allows to preserve field order in objects21# Allows to preserve field order in objects
19exp-preserve-order = []22exp-preserve-order = []
42serde_json = "1.0"45serde_json = "1.0"
43serde_yaml = { git = "https://github.com/CertainLach/serde-yaml", branch = "feature/old-octals-quirk" }46serde_yaml = { git = "https://github.com/CertainLach/serde-yaml", branch = "feature/old-octals-quirk" }
4447
45[dependencies.anyhow]48anyhow = { version = "1.0", optional = true }
46version = "1.0"49# Friendly errors
47optional = true50strsim = { version = "0.10.0", optional = true }
4851# Serialized stdlib
49# Serialized stdlib52bincode = { version = "1.3", optional = true }
50[dependencies.bincode]53# Explaining traces
51version = "1.3"54annotate-snippets = { version = "0.9.1", features = ["color"], optional = true }
52optional = true
53
54# Explaining traces
55[dependencies.annotate-snippets]
56version = "0.9.1"
57features = ["color"]
58optional = true
5955
60[build-dependencies]56[build-dependencies]
61jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }57jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
49 }))49 }))
50 }50 }
5151
52 #[cfg(not(feature = "friendly-errors"))]
52 pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {53 pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
53 Ok(self54 Ok(self
54 .055 .0
55 .bindings56 .bindings
56 .get(&name)57 .get(&name)
57 .cloned()58 .cloned()
58 .ok_or(VariableIsNotDefined(name))?)59 .ok_or(VariableIsNotDefined(name, vec![]))?)
59 }60 }
61
62 #[cfg(feature = "friendly-errors")]
63 pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
64 use std::cmp::Ordering;
65
66 use crate::throw;
67
68 if let Some(val) = self.0.bindings.get(&name).cloned() {
69 return Ok(val);
70 }
71
72 let mut heap = Vec::new();
73 self.0.bindings.clone().iter_keys(|k| {
74 let conf = strsim::jaro_winkler(&k as &str, &name as &str);
75 if conf < 0.8 {
76 return;
77 }
78 heap.push((conf, k));
79 });
80 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
81
82 throw!(VariableIsNotDefined(
83 name,
84 heap.into_iter().map(|(_, k)| k).collect()
85 ))
86 }
60 pub fn contains_binding(&self, name: IStr) -> bool {87 pub fn contains_binding(&self, name: IStr) -> bool {
61 self.0.bindings.contains_key(&name)88 self.0.bindings.contains_key(&name)
62 }89 }
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
11 typed::TypeLocError,11 typed::TypeLocError,
12};12};
13
14fn format_found(list: &[IStr], what: &str) -> String {
15 if list.is_empty() {
16 return String::new();
17 }
18 let mut out = String::new();
19 out.push_str("\nThere is ");
20 out.push_str(what);
21 if list.len() > 1 {
22 out.push('s');
23 }
24 out.push_str(" with similar name");
25 if list.len() > 1 {
26 out.push('s');
27 }
28 out.push_str(" present: ");
29 for (i, v) in list.iter().enumerate() {
30 if i != 0 {
31 out.push_str(", ");
32 }
33 out.push_str(v as &str);
34 }
35 out
36}
1337
14#[derive(Error, Debug, Clone, Trace)]38#[derive(Error, Debug, Clone, Trace)]
15pub enum Error {39pub enum Error {
39 #[error("assert failed: {0}")]63 #[error("assert failed: {0}")]
40 AssertionFailed(IStr),64 AssertionFailed(IStr),
4165
42 #[error("variable is not defined: {0}")]66 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]
43 VariableIsNotDefined(IStr),67 VariableIsNotDefined(IStr, Vec<IStr>),
44 #[error("duplicate local var: {0}")]68 #[error("duplicate local var: {0}")]
45 DuplicateLocalVar(IStr),69 DuplicateLocalVar(IStr),
4670
47 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]71 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]
48 TypeMismatch(&'static str, Vec<ValType>, ValType),72 TypeMismatch(&'static str, Vec<ValType>, ValType),
49 #[error("no such field: {0}")]73 #[error("no such field: {0}{}", format_found(.1, "field"))]
50 NoSuchField(IStr),74 NoSuchField(IStr, Vec<IStr>),
5175
52 #[error("only functions can be called, got {0}")]76 #[error("only functions can be called, got {0}")]
53 OnlyFunctionsCanBeCalledGot(ValType),77 OnlyFunctionsCanBeCalledGot(ValType),
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
1use std::rc::Rc;1use std::{cmp::Ordering, rc::Rc};
22
3use gcmodule::{Cc, Trace};3use gcmodule::{Cc, Trace};
4use jrsonnet_interner::IStr;4use jrsonnet_interner::IStr;
450 || format!("field <{}> access", key),450 || format!("field <{}> access", key),
451 || match v.get(s.clone(), key.clone()) {451 || match v.get(s.clone(), key.clone()) {
452 Ok(Some(v)) => Ok(v),452 Ok(Some(v)) => Ok(v),
453 #[cfg(not(feature = "friendly-errors"))]
453 Ok(None) => throw!(NoSuchField(key.clone())),454 Ok(None) => throw!(NoSuchField(key.clone(), vec![])),
455 #[cfg(feature = "friendly-errors")]
456 Ok(None) => {
457 let mut heap = Vec::new();
458 for field in v.fields_ex(
459 true,
460 #[cfg(feature = "exp-preserve-order")]
461 false,
462 ) {
463 let conf = strsim::jaro_winkler(&field as &str, &key as &str);
464 if conf < 0.8 {
465 continue;
466 }
467 heap.push((conf, field));
468 }
469 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
470
471 throw!(NoSuchField(
472 key.clone(),
473 heap.into_iter().map(|(_, v)| v).collect()
474 ))
475 }
454 Err(e) if matches!(e.error(), MagicThisFileUsed) => {476 Err(e) if matches!(e.error(), MagicThisFileUsed) => {
455 Ok(Val::Str(loc.0.full_path().into()))477 Ok(Val::Str(loc.0.full_path().into()))
456 }478 }