difftreelog
refactor(treewide) custom path support
in: master
15 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -4,19 +4,18 @@
any::Any,
cell::RefCell,
collections::HashMap,
+ env::current_dir,
ffi::{c_void, CStr, CString},
- fs::File,
- io::Read,
os::raw::{c_char, c_int},
- path::{Path, PathBuf},
+ path::PathBuf,
ptr::null_mut,
};
use jrsonnet_evaluator::{
error::{Error::*, Result},
- throw, ImportResolver, State,
+ throw, FileImportResolver, ImportResolver, State,
};
-use jrsonnet_parser::SourcePath;
+use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
pub type JsonnetImportCallback = unsafe extern "C" fn(
ctx: *mut c_void,
@@ -33,25 +32,31 @@
out: RefCell<HashMap<SourcePath, Vec<u8>>>,
}
impl ImportResolver for CallbackImportResolver {
- fn resolve_file_relative(&self, from: &Path, path: &str) -> Result<SourcePath> {
- let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();
- let rel = CString::new(path).unwrap().into_raw();
+ fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
+ let base = if let Some(p) = from.downcast_ref::<SourceFile>() {
+ let mut o = p.path().to_owned();
+ o.pop();
+ o
+ } else if let Some(d) = from.downcast_ref::<SourceDirectory>() {
+ d.path().to_owned()
+ } else if from.is_default() {
+ current_dir().map_err(|e| ImportIo(e.to_string()))?
+ } else {
+ unreachable!("can't resolve this path");
+ };
+ let base = unsafe { crate::unparse_path(&base) };
+ let rel = CString::new(path).unwrap();
let found_here: *mut c_char = null_mut();
let mut success: i32 = 0;
let result_ptr = unsafe {
(self.cb)(
self.ctx,
- base,
- rel,
+ base.as_ptr(),
+ rel.as_ptr(),
&mut (found_here as *const _),
&mut success,
)
};
- // Release memory occipied by arguments passed
- unsafe {
- let _ = CString::from_raw(base);
- let _ = CString::from_raw(rel);
- }
let result_raw = unsafe { CStr::from_ptr(result_ptr) };
let result_str = result_raw.to_str().unwrap();
assert!(success == 0 || success == 1);
@@ -62,7 +67,9 @@
}
let found_here_raw = unsafe { CStr::from_ptr(found_here) };
- let found_here_buf = SourcePath::Path(PathBuf::from(found_here_raw.to_str().unwrap()));
+ let found_here_buf = SourcePath::new(SourceFile::new(PathBuf::from(
+ found_here_raw.to_str().unwrap(),
+ )));
unsafe {
let _ = CString::from_raw(found_here);
}
@@ -79,12 +86,14 @@
Ok(self.out.borrow().get(resolved).unwrap().clone())
}
- unsafe fn as_any(&self) -> &dyn Any {
+ fn as_any(&self) -> &dyn Any {
self
}
}
/// # Safety
+///
+/// Caller should pass correct callback function
#[no_mangle]
pub unsafe extern "C" fn jsonnet_import_callback(
vm: &State,
@@ -96,54 +105,11 @@
ctx,
out: RefCell::new(HashMap::new()),
}))
-}
-
-/// Standard FS import resolver
-#[derive(Default)]
-pub struct NativeImportResolver {
- library_paths: RefCell<Vec<PathBuf>>,
-}
-impl NativeImportResolver {
- fn add_jpath(&self, path: PathBuf) {
- self.library_paths.borrow_mut().push(path);
- }
}
-impl ImportResolver for NativeImportResolver {
- fn resolve_file_relative(&self, from: &Path, path: &str) -> Result<SourcePath> {
- let mut new_path = from.to_owned();
- new_path.push(path);
- if new_path.exists() {
- Ok(SourcePath::Path(new_path))
- } else {
- for library_path in self.library_paths.borrow().iter() {
- let mut cloned = library_path.clone();
- cloned.push(path);
- if cloned.exists() {
- return Ok(SourcePath::Path(cloned));
- }
- }
- throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
- }
- }
- fn load_file_contents(&self, id: &SourcePath) -> Result<Vec<u8>> {
- let path = match id {
- SourcePath::Path(path) => path,
- _ => unreachable!("NativeImportResolver::resolve_file may only return plain paths"),
- };
- let mut file = File::open(path).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
- let mut out = Vec::new();
- file.read_to_end(&mut out)
- .map_err(|e| ImportIo(e.to_string()))?;
- Ok(out)
- }
- unsafe fn as_any(&self) -> &dyn Any {
- self
- }
-}
/// # Safety
///
-/// This function is safe, if received v is a pointer to normal C string
+/// Caller should pass correct path: it should contain correct utf-8, and be \0-terminated
#[no_mangle]
pub unsafe extern "C" fn jsonnet_jpath_add(vm: &State, v: *const c_char) {
let cstr = CStr::from_ptr(v);
@@ -151,7 +117,7 @@
let any_resolver = vm.import_resolver();
let resolver = any_resolver
.as_any()
- .downcast_ref::<NativeImportResolver>()
+ .downcast_ref::<FileImportResolver>()
.expect("jpaths are not compatible with callback imports!");
resolver.add_jpath(path);
}
cmds/jrsonnet/Cargo.tomldiffbeforeafterboth--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -19,6 +19,8 @@
]
# Destructuring of locals
exp-destruct = ["jrsonnet-evaluator/exp-destruct"]
+# std.thisFile support
+legacy-this-file = ["jrsonnet-cli/legacy-this-file"]
[dependencies]
jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2" }
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -1,5 +1,4 @@
use std::{
- env::current_dir,
fs::{create_dir_all, File},
io::{Read, Write},
};
@@ -140,7 +139,7 @@
let input_str = std::str::from_utf8(&input)?;
s.evaluate_snippet("<stdin>".to_owned(), input_str)?
} else {
- s.import(¤t_dir().expect("cwd"), &input)?
+ s.import(&input)?
};
let val = s.with_tla(val)?;
crates/jrsonnet-cli/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-cli/Cargo.toml
+++ b/crates/jrsonnet-cli/Cargo.toml
@@ -15,6 +15,7 @@
"jrsonnet-evaluator/exp-serde-preserve-order",
"jrsonnet-stdlib/exp-serde-preserve-order",
]
+legacy-this-file = ["jrsonnet-stdlib/legacy-this-file"]
[dependencies]
jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2", features = [
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -51,7 +51,7 @@
library_paths.extend(env::split_paths(path.as_os_str()));
}
- s.set_import_resolver(Box::new(FileImportResolver { library_paths }));
+ s.set_import_resolver(Box::new(FileImportResolver::new(library_paths)));
s.set_max_stack(self.max_stack);
Ok(())
crates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -1,7 +1,7 @@
use std::{fs::read_to_string, str::FromStr};
use clap::Parser;
-use jrsonnet_evaluator::{error::Result, State};
+use jrsonnet_evaluator::{error::Result, trace::PathResolver, State};
use crate::ConfigureState;
@@ -110,7 +110,8 @@
if self.no_stdlib {
return Ok(());
}
- let ctx = jrsonnet_stdlib::ContextInitializer::new(s.clone());
+ let ctx =
+ jrsonnet_stdlib::ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());
for ext in self.ext_str.iter() {
ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
}
crates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -42,11 +42,7 @@
}
impl ConfigureState for TraceOpts {
fn configure(&self, s: &State) -> Result<()> {
- let resolver = if let Ok(dir) = std::env::current_dir() {
- PathResolver::Relative(dir)
- } else {
- PathResolver::Absolute
- };
+ let resolver = PathResolver::new_cwd_fallback();
match self
.trace_format
.as_ref()
crates/jrsonnet-interner/src/inner.rsdiffbeforeafterboth1use std::{2 alloc::{self, Layout},3 borrow::Borrow,4 cmp,5 hash::{Hash, Hasher},6 mem,7 ptr::{self, NonNull},8 slice, str,9};1011const UTF8_MASK: u32 = 1 << 31;12const REFCNT_MASK: u32 = !UTF8_MASK;1314#[repr(C)]15struct InnerHeader {16 size: u32,17 // MSB is checked utf8 flag, rest - refcnt18 utf8_refcnt: u32,19}20impl InnerHeader {21 const fn new(size: u32, is_utf8: bool) -> Self {22 Self {23 size,24 utf8_refcnt: 1 | (if is_utf8 { UTF8_MASK } else { 0 }),25 }26 }2728 const fn refcnt(&self) -> u32 {29 self.utf8_refcnt & REFCNT_MASK30 }31 const fn is_utf8(&self) -> bool {32 self.utf8_refcnt & UTF8_MASK != 033 }3435 fn set_refcnt(&mut self, cnt: u32) {36 assert_eq!(cnt & UTF8_MASK, 0);37 // Reset all bits expect last38 self.utf8_refcnt &= UTF8_MASK;39 // Store refcnt40 self.utf8_refcnt |= cnt;41 }42 fn set_is_utf8(&mut self) {43 self.utf8_refcnt |= UTF8_MASK;44 }45}4647/// Similar to Rc<[u8]>, but stores all data (refcnt, size) inline, instead of being DST48pub struct Inner(NonNull<u8>);49impl Inner {50 /// # Safety51 /// `is_utf8` should only be set if data is really checked to be utf852 /// # Panics53 /// If data is larger than 4GB54 // we allocate with correct alignment55 #[allow(clippy::cast_ptr_alignment)]56 unsafe fn new_raw(bytes: &[u8], is_utf8: bool) -> Self {57 // SAFETY:58 // - layout has non-zero size, and correct align59 // - data is written right after allocation60 // - new allocation can't overlap with passed slice61 unsafe {62 let data = alloc::alloc(Layout::from_size_align_unchecked(63 mem::size_of::<InnerHeader>() + bytes.len(),64 mem::align_of::<InnerHeader>(),65 ));66 assert!(!data.is_null());67 *data.cast::<InnerHeader>() =68 InnerHeader::new(bytes.len().try_into().expect("bytes > 4GB"), is_utf8);69 ptr::copy_nonoverlapping(70 bytes.as_ptr(),71 data.add(mem::size_of::<InnerHeader>()),72 bytes.len(),73 );74 Self(NonNull::new_unchecked(data))75 }76 }77 pub fn new_bytes(bytes: &[u8]) -> Self {78 // SAFETY: is_utf8 is not set79 unsafe { Self::new_raw(bytes, false) }80 }81 #[allow(dead_code)]82 pub fn new_str(str: &str) -> Self {83 // SAFETY: strings always utf884 unsafe { Self::new_raw(str.as_bytes(), true) }85 }8687 pub const fn as_slice(&self) -> &[u8] {88 let header = Self::header(self);89 // SAFETY: data is not null, and it is correctly initialized90 let size = unsafe { (*header).size };91 // SAFETY: bytes after data is allocated to be exactly data.size in length92 unsafe {93 slice::from_raw_parts(94 self.0.as_ptr().add(mem::size_of::<InnerHeader>()),95 size as usize,96 )97 }98 }99100 /// # Safety101 /// Data should be checked to be utf8 via [`check_utf8`] first102 pub const unsafe fn as_str_unchecked(&self) -> &str {103 // SAFETY: data is checked104 unsafe { str::from_utf8_unchecked(self.as_slice()) }105 }106107 /// Check data to be utf-8108 ///109 /// Positive results are cached110 pub fn check_utf8(this: &Self) -> bool {111 let header = Self::header_mut(this);112 // SAFETY: header is initialized113 if unsafe { (*header).is_utf8() } {114 return true;115 }116117 if str::from_utf8(this.as_slice()).is_ok() {118 // SAFETY: header is initialized119 unsafe { (*header).set_is_utf8() };120 true121 } else {122 false123 }124 }125126 /// Marks data as utf-8127 ///128 /// # Safety129 /// data should be really utf-8130 pub unsafe fn assume_utf8(this: &Self) {131 let header = Self::header_mut(this);132 // SAFETY: header is correct133 unsafe { (*header).set_is_utf8() }134 }135136 const fn header(this: &Self) -> *const InnerHeader {137 // in `new`, we allocate with correct alignment138 #![allow(clippy::cast_ptr_alignment)]139 this.0.as_ptr() as *const InnerHeader140 }141 const fn header_mut(this: &Self) -> *mut InnerHeader {142 // in `new`, we allocate with correct alignment143 #![allow(clippy::cast_ptr_alignment)]144 this.0.as_ptr().cast::<InnerHeader>()145 }146147 fn clone(this: &Self) -> Self {148 let header = Self::header_mut(this);149 // SAFETY: header is initialized150 unsafe {151 let refcnt = (*header).refcnt() + 1;152 (*header).set_refcnt(refcnt);153 }154 Self(this.0)155 }156157 pub fn ptr_eq(a: &Self, b: &Self) -> bool {158 a.0 == b.0159 }160 pub const fn as_ptr(this: &Self) -> *const u8 {161 // SAFETY: data is initialized162 unsafe { this.0.as_ptr().add(mem::size_of::<InnerHeader>()) }163 }164165 pub const fn strong_count(this: &Self) -> u32 {166 let header = Self::header(this);167 // SAFETY: header is initialized168 unsafe { (*header).refcnt() }169 }170}171172impl Clone for Inner {173 fn clone(&self) -> Self {174 Self::clone(self)175 }176}177178impl Drop for Inner {179 fn drop(&mut self) {180 #[cold]181 #[inline(never)]182 fn dealloc(val: &Inner) {183 let header = Inner::header_mut(val);184 // SAFETY: size is correct, layout is valid185 unsafe {186 alloc::dealloc(187 val.0.as_ptr(),188 Layout::from_size_align_unchecked(189 mem::size_of::<InnerHeader>() + (*header).size as usize,190 mem::align_of::<InnerHeader>(),191 ),192 );193 }194 }195 let header = Self::header_mut(self);196 // SAFETY: header is initialized197 let refcnt = unsafe {198 let refcnt = (*header).refcnt() - 1;199 (*header).set_refcnt(refcnt);200 refcnt201 };202 if refcnt == 0 {203 dealloc(self);204 }205 }206}207208impl PartialEq for Inner {209 fn eq(&self, other: &Self) -> bool {210 self.0 == other.0 || self.as_slice().eq(other.as_slice())211 }212}213impl Hash for Inner {214 fn hash<H: Hasher>(&self, state: &mut H) {215 self.as_slice().hash(state);216 }217}218impl Eq for Inner {}219impl PartialOrd for Inner {220 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {221 self.as_slice().partial_cmp(other.as_slice())222 }223}224impl Ord for Inner {225 fn cmp(&self, other: &Self) -> cmp::Ordering {226 self.as_slice().cmp(other.as_slice())227 }228}229230impl Borrow<[u8]> for Inner {231 fn borrow(&self) -> &[u8] {232 self.as_slice()233 }234}1use std::{2 alloc::{self, Layout},3 borrow::Borrow,4 cmp,5 hash::{Hash, Hasher},6 mem,7 ptr::{self, NonNull},8 slice, str,9};1011const UTF8_MASK: u32 = 1 << 31;12const REFCNT_MASK: u32 = !UTF8_MASK;1314#[repr(C)]15struct InnerHeader {16 size: u32,17 // MSB is checked utf8 flag, rest - refcnt18 utf8_refcnt: u32,19}20impl InnerHeader {21 const fn new(size: u32, is_utf8: bool) -> Self {22 Self {23 size,24 utf8_refcnt: 1 | (if is_utf8 { UTF8_MASK } else { 0 }),25 }26 }2728 const fn refcnt(&self) -> u32 {29 self.utf8_refcnt & REFCNT_MASK30 }31 const fn is_utf8(&self) -> bool {32 self.utf8_refcnt & UTF8_MASK != 033 }3435 fn set_refcnt(&mut self, cnt: u32) {36 assert_eq!(cnt & UTF8_MASK, 0);37 // Reset all bits expect last38 self.utf8_refcnt &= UTF8_MASK;39 // Store refcnt40 self.utf8_refcnt |= cnt;41 }42 fn set_is_utf8(&mut self) {43 self.utf8_refcnt |= UTF8_MASK;44 }45}4647/// Similar to Rc<[u8]>, but stores all data (refcnt, size) inline, instead of being DST48pub struct Inner(NonNull<u8>);49impl Inner {50 /// # Safety51 /// `is_utf8` should only be set if data is really checked to be utf852 /// # Panics53 /// If data is larger than 4GB54 // we allocate with correct alignment55 #[allow(clippy::cast_ptr_alignment)]56 unsafe fn new_raw(bytes: &[u8], is_utf8: bool) -> Self {57 // SAFETY:58 // - layout has non-zero size, and correct align59 // - data is written right after allocation60 // - new allocation can't overlap with passed slice61 unsafe {62 let data = alloc::alloc(Layout::from_size_align_unchecked(63 mem::size_of::<InnerHeader>() + bytes.len(),64 mem::align_of::<InnerHeader>(),65 ));66 assert!(!data.is_null());67 *data.cast::<InnerHeader>() =68 InnerHeader::new(bytes.len().try_into().expect("bytes > 4GB"), is_utf8);69 ptr::copy_nonoverlapping(70 bytes.as_ptr(),71 data.add(mem::size_of::<InnerHeader>()),72 bytes.len(),73 );74 Self(NonNull::new_unchecked(data))75 }76 }77 pub fn new_bytes(bytes: &[u8]) -> Self {78 // SAFETY: is_utf8 is not set79 unsafe { Self::new_raw(bytes, false) }80 }81 #[allow(dead_code)]82 pub fn new_str(str: &str) -> Self {83 // SAFETY: strings always utf884 unsafe { Self::new_raw(str.as_bytes(), true) }85 }8687 // `slice::from_raw_parts` is not yet stabilized88 #[allow(clippy::missing_const_for_fn)]89 pub fn as_slice(&self) -> &[u8] {90 let header = Self::header(self);91 // SAFETY: data is not null, and it is correctly initialized92 let size = unsafe { (*header).size };93 // SAFETY: bytes after data is allocated to be exactly data.size in length94 unsafe {95 slice::from_raw_parts(96 self.0.as_ptr().add(mem::size_of::<InnerHeader>()),97 size as usize,98 )99 }100 }101102 /// # Safety103 /// Data should be checked to be utf8 via [`check_utf8`] first104 pub unsafe fn as_str_unchecked(&self) -> &str {105 // SAFETY: data is checked106 unsafe { str::from_utf8_unchecked(self.as_slice()) }107 }108109 /// Check data to be utf-8110 ///111 /// Positive results are cached112 pub fn check_utf8(this: &Self) -> bool {113 let header = Self::header_mut(this);114 // SAFETY: header is initialized115 if unsafe { (*header).is_utf8() } {116 return true;117 }118119 if str::from_utf8(this.as_slice()).is_ok() {120 // SAFETY: header is initialized121 unsafe { (*header).set_is_utf8() };122 true123 } else {124 false125 }126 }127128 /// Marks data as utf-8129 ///130 /// # Safety131 /// data should be really utf-8132 pub unsafe fn assume_utf8(this: &Self) {133 let header = Self::header_mut(this);134 // SAFETY: header is correct135 unsafe { (*header).set_is_utf8() }136 }137138 const fn header(this: &Self) -> *const InnerHeader {139 // in `new`, we allocate with correct alignment140 #![allow(clippy::cast_ptr_alignment)]141 this.0.as_ptr() as *const InnerHeader142 }143 const fn header_mut(this: &Self) -> *mut InnerHeader {144 // in `new`, we allocate with correct alignment145 #![allow(clippy::cast_ptr_alignment)]146 this.0.as_ptr().cast::<InnerHeader>()147 }148149 fn clone(this: &Self) -> Self {150 let header = Self::header_mut(this);151 // SAFETY: header is initialized152 unsafe {153 let refcnt = (*header).refcnt() + 1;154 (*header).set_refcnt(refcnt);155 }156 Self(this.0)157 }158159 pub fn ptr_eq(a: &Self, b: &Self) -> bool {160 a.0 == b.0161 }162 pub const fn as_ptr(this: &Self) -> *const u8 {163 // SAFETY: data is initialized164 unsafe { this.0.as_ptr().add(mem::size_of::<InnerHeader>()) }165 }166167 pub const fn strong_count(this: &Self) -> u32 {168 let header = Self::header(this);169 // SAFETY: header is initialized170 unsafe { (*header).refcnt() }171 }172}173174impl Clone for Inner {175 fn clone(&self) -> Self {176 Self::clone(self)177 }178}179180impl Drop for Inner {181 fn drop(&mut self) {182 #[cold]183 #[inline(never)]184 fn dealloc(val: &Inner) {185 let header = Inner::header_mut(val);186 // SAFETY: size is correct, layout is valid187 unsafe {188 alloc::dealloc(189 val.0.as_ptr(),190 Layout::from_size_align_unchecked(191 mem::size_of::<InnerHeader>() + (*header).size as usize,192 mem::align_of::<InnerHeader>(),193 ),194 );195 }196 }197 let header = Self::header_mut(self);198 // SAFETY: header is initialized199 let refcnt = unsafe {200 let refcnt = (*header).refcnt() - 1;201 (*header).set_refcnt(refcnt);202 refcnt203 };204 if refcnt == 0 {205 dealloc(self);206 }207 }208}209210impl PartialEq for Inner {211 fn eq(&self, other: &Self) -> bool {212 self.0 == other.0 || self.as_slice().eq(other.as_slice())213 }214}215impl Hash for Inner {216 fn hash<H: Hasher>(&self, state: &mut H) {217 self.as_slice().hash(state);218 }219}220impl Eq for Inner {}221impl PartialOrd for Inner {222 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {223 self.as_slice().partial_cmp(other.as_slice())224 }225}226impl Ord for Inner {227 fn cmp(&self, other: &Self) -> cmp::Ordering {228 self.as_slice().cmp(other.as_slice())229 }230}231232impl Borrow<[u8]> for Inner {233 fn borrow(&self) -> &[u8] {234 self.as_slice()235 }236}crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -133,7 +133,7 @@
}
#[must_use]
- pub const fn as_slice(&self) -> &[u8] {
+ pub fn as_slice(&self) -> &[u8] {
self.0.as_slice()
}
}
crates/jrsonnet-stdlib/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/build.rs
+++ b/crates/jrsonnet-stdlib/build.rs
@@ -1,4 +1,4 @@
-use std::{borrow::Cow, env, fs::File, io::Write, path::Path};
+use std::{env, fs::File, io::Write, path::Path};
use jrsonnet_parser::{parse, ParserSettings, Source};
use structdump::CodegenResult;
@@ -8,7 +8,7 @@
include_str!("./src/std.jsonnet"),
&ParserSettings {
file_name: Source::new_virtual(
- Cow::Borrowed("<std>"),
+ "<std>".into(),
include_str!("./src/std.jsonnet").into(),
),
},
crates/jrsonnet-stdlib/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/expr.rs
+++ b/crates/jrsonnet-stdlib/src/expr.rs
@@ -1,7 +1,7 @@
use jrsonnet_parser::LocExpr;
mod structdump_import {
- pub(super) use std::{borrow::Cow, option::Option, rc::Rc, vec};
+ pub(super) use std::{option::Option, rc::Rc, vec};
pub(super) use jrsonnet_parser::*;
}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -1,5 +1,4 @@
use std::{
- borrow::Cow,
cell::{Ref, RefCell, RefMut},
collections::HashMap,
rc::Rc,
@@ -10,6 +9,7 @@
function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},
gc::{GcHashMap, TraceBox},
tb, throw_runtime,
+ trace::PathResolver,
typed::{Any, Either, Either2, Either4, VecVal, M1},
val::{equals, ArrValue},
Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,
@@ -184,13 +184,27 @@
fn print_trace(&self, s: State, loc: CallLocation, value: IStr);
}
-pub struct StdTracePrinter;
+pub struct StdTracePrinter {
+ resolver: PathResolver,
+}
+impl StdTracePrinter {
+ pub fn new(resolver: PathResolver) -> Self {
+ Self { resolver }
+ }
+}
impl TracePrinter for StdTracePrinter {
fn print_trace(&self, _s: State, loc: CallLocation, value: IStr) {
eprint!("TRACE:");
if let Some(loc) = loc.0 {
let locs = loc.0.map_source_locations(&[loc.1]);
- eprint!(" {}:{}", loc.0.short_display(), locs[0].line);
+ eprint!(
+ " {}:{}",
+ match loc.0.source_path().path() {
+ Some(p) => self.resolver.resolve(p),
+ None => loc.0.source_path().to_string(),
+ },
+ locs[0].line
+ );
}
eprintln!(" {}", value);
}
@@ -205,22 +219,13 @@
pub globals: GcHashMap<IStr, Thunk<Val>>,
/// Used for `std.trace`
pub trace_printer: Box<dyn TracePrinter>,
-}
-
-impl Default for Settings {
- fn default() -> Self {
- Self {
- ext_vars: Default::default(),
- ext_natives: Default::default(),
- globals: Default::default(),
- trace_printer: Box::new(StdTracePrinter),
- }
- }
+ /// Used for `std.thisFile`
+ pub path_resolver: PathResolver,
}
pub fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {
let source_name = format!("<extvar:{}>", name);
- Source::new_virtual(Cow::Owned(source_name), code.into())
+ Source::new_virtual(source_name.into(), code.into())
}
pub struct ContextInitializer {
@@ -233,8 +238,15 @@
settings: Rc<RefCell<Settings>>,
}
impl ContextInitializer {
- pub fn new(s: State) -> Self {
- let settings = Rc::new(RefCell::new(Settings::default()));
+ pub fn new(s: State, resolver: PathResolver) -> Self {
+ let settings = Settings {
+ ext_vars: Default::default(),
+ ext_natives: Default::default(),
+ globals: Default::default(),
+ trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),
+ path_resolver: resolver,
+ };
+ let settings = Rc::new(RefCell::new(settings));
Self {
#[cfg(not(feature = "legacy-this-file"))]
context: {
@@ -313,13 +325,10 @@
.hide()
.value(
s,
- Val::Str(
- source
- .path()
- .map(|p| p.display().to_string())
- .unwrap_or_else(String::new)
- .into(),
- ),
+ Val::Str(match source.source_path().path() {
+ Some(p) => self.settings().path_resolver.resolve(p).into(),
+ None => source.source_path().to_string().into(),
+ }),
)
.expect("this object builder is empty");
let stdlib_with_this_file = builder.build();
@@ -329,12 +338,12 @@
"std".into(),
Thunk::evaluated(Val::Obj(stdlib_with_this_file)),
);
- for (k, v) in &self.settings().globals {
- context.bind(k.clone(), v.clone())
+ for (k, v) in self.settings().globals.iter() {
+ context.bind(k.clone(), v.clone());
}
context.build()
}
- unsafe fn as_any(&self) -> &dyn std::any::Any {
+ fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -540,12 +549,13 @@
impl StateExt for State {
fn with_stdlib(&self) {
- let initializer = ContextInitializer::new(self.clone());
+ let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());
self.settings_mut().context_initializer = Box::new(initializer)
}
fn add_global(&self, name: IStr, value: Thunk<Val>) {
- // Safety:
- unsafe { self.settings().context_initializer.as_any() }
+ self.settings()
+ .context_initializer
+ .as_any()
.downcast_ref::<ContextInitializer>()
.expect("not standard context initializer")
.settings_mut()
crates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -2,7 +2,7 @@
local std = self,
local id = std.id,
- thisFile:: error 'std.thisFile is deprecated, to enable its support in jrsonnet - recompile it with "legacy-this-file" support. This will slow down stdlib caching a bit, though',
+ thisFile:: error 'std.thisFile is deprecated, to enable its support in jrsonnet - recompile it with "legacy-this-file" support.\nThis will slow down stdlib caching a bit, though',
toString(a):: '' + a,
tests/tests/golden.rsdiffbeforeafterboth--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -21,7 +21,7 @@
common::with_test(&s);
s.set_import_resolver(Box::new(FileImportResolver::default()));
- let v = match s.import(root, &file.display().to_string()) {
+ let v = match s.import(file) {
Ok(v) => v,
Err(e) => return s.stringify_err(&e),
};
tests/tests/suite.rsdiffbeforeafterboth--- a/tests/tests/suite.rs
+++ b/tests/tests/suite.rs
@@ -21,7 +21,7 @@
common::with_test(&s);
s.set_import_resolver(Box::new(FileImportResolver::default()));
- match s.import(root, &file.display().to_string()) {
+ match s.import(file) {
Ok(Val::Bool(true)) => {}
Ok(Val::Bool(false)) => panic!("test {} returned false", file.display()),
Ok(_) => panic!("test {} returned wrong type as result", file.display()),