git.delta.rocks / jrsonnet / refs/commits / b4d71ecb32b0

difftreelog

refactor(treewide) custom path support

Yaroslav Bolyukin2022-08-27parent: #bf006f5.patch.diff
in: master

15 files changed

modifiedbindings/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);
 }
modifiedcmds/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" }
modifiedcmds/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(&current_dir().expect("cwd"), &input)?
+		s.import(&input)?
 	};
 
 	let val = s.with_tla(val)?;
modifiedcrates/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 = [
modifiedcrates/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(())
modifiedcrates/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());
 		}
modifiedcrates/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()
modifiedcrates/jrsonnet-interner/src/inner.rsdiffbeforeafterboth
--- a/crates/jrsonnet-interner/src/inner.rs
+++ b/crates/jrsonnet-interner/src/inner.rs
@@ -84,7 +84,9 @@
 		unsafe { Self::new_raw(str.as_bytes(), true) }
 	}
 
-	pub const fn as_slice(&self) -> &[u8] {
+	// `slice::from_raw_parts` is not yet stabilized
+	#[allow(clippy::missing_const_for_fn)]
+	pub fn as_slice(&self) -> &[u8] {
 		let header = Self::header(self);
 		// SAFETY: data is not null, and it is correctly initialized
 		let size = unsafe { (*header).size };
@@ -99,7 +101,7 @@
 
 	/// # Safety
 	/// Data should be checked to be utf8 via [`check_utf8`] first
-	pub const unsafe fn as_str_unchecked(&self) -> &str {
+	pub unsafe fn as_str_unchecked(&self) -> &str {
 		// SAFETY: data is checked
 		unsafe { str::from_utf8_unchecked(self.as_slice()) }
 	}
modifiedcrates/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()
 	}
 }
modifiedcrates/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(),
 			),
 		},
modifiedcrates/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::*;
 }
modifiedcrates/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()
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/std.jsonnet
1{2  local std = self,3  local id = std.id,45  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',67  toString(a):: '' + a,89  lstripChars(str, chars)::10    if std.length(str) > 0 && std.member(chars, str[0]) then11      std.lstripChars(str[1:], chars)12    else13      str,1415  rstripChars(str, chars)::16    local len = std.length(str);17    if len > 0 && std.member(chars, str[len - 1]) then18      std.rstripChars(str[:len - 1], chars)19    else20      str,2122  stripChars(str, chars)::23    std.lstripChars(std.rstripChars(str, chars), chars),2425  stringChars(str)::26    std.makeArray(std.length(str), function(i) str[i]),2728  local parse_nat(str, base) =29    assert base > 0 && base <= 16 : 'integer base %d invalid' % base;30    // These codepoints are in ascending order:31    local zero_code = std.codepoint('0');32    local upper_a_code = std.codepoint('A');33    local lower_a_code = std.codepoint('a');34    local addDigit(aggregate, char) =35      local code = std.codepoint(char);36      local digit = if code >= lower_a_code then37        code - lower_a_code + 1038      else if code >= upper_a_code then39        code - upper_a_code + 1040      else41        code - zero_code;42      assert digit >= 0 && digit < base : '%s is not a base %d integer' % [str, base];43      base * aggregate + digit;44    std.foldl(addDigit, std.stringChars(str), 0),4546  parseInt(str)::47    assert std.isString(str) : 'Expected string, got ' + std.type(str);48    assert std.length(str) > 0 && str != '-' : 'Not an integer: "%s"' % [str];49    if str[0] == '-' then50      -parse_nat(str[1:], 10)51    else52      parse_nat(str, 10),5354  parseOctal(str)::55    assert std.isString(str) : 'Expected string, got ' + std.type(str);56    assert std.length(str) > 0 : 'Not an octal number: ""';57    parse_nat(str, 8),5859  parseHex(str)::60    assert std.isString(str) : 'Expected string, got ' + std.type(str);61    assert std.length(str) > 0 : 'Not hexadecimal: ""';62    parse_nat(str, 16),6364  split(str, c):: std.splitLimit(str, c, -1),6566  repeat(what, count)::67    local joiner =68      if std.isString(what) then ''69      else if std.isArray(what) then []70      else error 'std.repeat first argument must be an array or a string';71    std.join(joiner, std.makeArray(count, function(i) what)),7273  mapWithIndex(func, arr)::74    if !std.isFunction(func) then75      error ('std.mapWithIndex first param must be function, got ' + std.type(func))76    else if !std.isArray(arr) && !std.isString(arr) then77      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))78    else79      std.makeArray(std.length(arr), function(i) func(i, arr[i])),8081  mapWithKey(func, obj)::82    if !std.isFunction(func) then83      error ('std.mapWithKey first param must be function, got ' + std.type(func))84    else if !std.isObject(obj) then85      error ('std.mapWithKey second param must be object, got ' + std.type(obj))86    else87      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },8889  lines(arr)::90    std.join('\n', arr + ['']),9192  deepJoin(arr)::93    if std.isString(arr) then94      arr95    else if std.isArray(arr) then96      std.join('', [std.deepJoin(x) for x in arr])97    else98      error 'Expected string or array, got %s' % std.type(arr),99100  filterMap(filter_func, map_func, arr)::101    if !std.isFunction(filter_func) then102      error ('std.filterMap first param must be function, got ' + std.type(filter_func))103    else if !std.isFunction(map_func) then104      error ('std.filterMap second param must be function, got ' + std.type(map_func))105    else if !std.isArray(arr) then106      error ('std.filterMap third param must be array, got ' + std.type(arr))107    else108      std.map(map_func, std.filter(filter_func, arr)),109110  assertEqual(a, b)::111    if a == b then112      true113    else114      error 'Assertion failed. ' + a + ' != ' + b,115116  abs(n)::117    if !std.isNumber(n) then118      error 'std.abs expected number, got ' + std.type(n)119    else120      if n > 0 then n else -n,121122  sign(n)::123    if !std.isNumber(n) then124      error 'std.sign expected number, got ' + std.type(n)125    else126      if n > 0 then127        1128      else if n < 0 then129        -1130      else 0,131132  max(a, b)::133    if !std.isNumber(a) then134      error 'std.max first param expected number, got ' + std.type(a)135    else if !std.isNumber(b) then136      error 'std.max second param expected number, got ' + std.type(b)137    else138      if a > b then a else b,139140  min(a, b)::141    if !std.isNumber(a) then142      error 'std.min first param expected number, got ' + std.type(a)143    else if !std.isNumber(b) then144      error 'std.min second param expected number, got ' + std.type(b)145    else146      if a < b then a else b,147148  clamp(x, minVal, maxVal)::149    if x < minVal then minVal150    else if x > maxVal then maxVal151    else x,152153  flattenArrays(arrs)::154    std.foldl(function(a, b) a + b, arrs, []),155156  manifestIni(ini)::157    local body_lines(body) =158      std.join([], [159        local value_or_values = body[k];160        if std.isArray(value_or_values) then161          ['%s = %s' % [k, value] for value in value_or_values]162        else163          ['%s = %s' % [k, value_or_values]]164165        for k in std.objectFields(body)166      ]);167168    local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),169          main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],170          all_sections = [171      section_lines(k, ini.sections[k])172      for k in std.objectFields(ini.sections)173    ];174    std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),175176  manifestToml(value):: std.manifestTomlEx(value, '  '),177178  manifestTomlEx(value, indent)::179    local180      escapeStringToml = std.escapeStringJson,181      escapeKeyToml(key) =182        local bare_allowed = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'));183        if std.setUnion(std.set(std.stringChars(key)), bare_allowed) == bare_allowed then key else escapeStringToml(key),184      isTableArray(v) = std.isArray(v) && std.length(v) > 0 && std.foldl(function(a, b) a && std.isObject(b), v, true),185      isSection(v) = std.isObject(v) || isTableArray(v),186      renderValue(v, indexedPath, inline, cindent) =187        if v == true then188          'true'189        else if v == false then190          'false'191        else if v == null then192          error 'Tried to manifest "null" at ' + indexedPath193        else if std.isNumber(v) then194          '' + v195        else if std.isString(v) then196          escapeStringToml(v)197        else if std.isFunction(v) then198          error 'Tried to manifest function at ' + indexedPath199        else if std.isArray(v) then200          if std.length(v) == 0 then201            '[]'202          else203            local range = std.range(0, std.length(v) - 1);204            local new_indent = if inline then '' else cindent + indent;205            local separator = if inline then ' ' else '\n';206            local lines = ['[' + separator]207                          + std.join([',' + separator],208                                     [209                                       [new_indent + renderValue(v[i], indexedPath + [i], true, '')]210                                       for i in range211                                     ])212                          + [separator + (if inline then '' else cindent) + ']'];213            std.join('', lines)214        else if std.isObject(v) then215          local lines = ['{ ']216                        + std.join([', '],217                                   [218                                     [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]219                                     for k in std.objectFields(v)220                                   ])221                        + [' }'];222          std.join('', lines),223      renderTableInternal(v, path, indexedPath, cindent) =224        local kvp = std.flattenArrays([225          [cindent + escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], false, cindent)]226          for k in std.objectFields(v)227          if !isSection(v[k])228        ]);229        local sections = [std.join('\n', kvp)] + [230          (231            if std.isObject(v[k]) then232              renderTable(v[k], path + [k], indexedPath + [k], cindent)233            else234              renderTableArray(v[k], path + [k], indexedPath + [k], cindent)235          )236          for k in std.objectFields(v)237          if isSection(v[k])238        ];239        std.join('\n\n', sections),240      renderTable(v, path, indexedPath, cindent) =241        cindent + '[' + std.join('.', std.map(escapeKeyToml, path)) + ']'242        + (if v == {} then '' else '\n')243        + renderTableInternal(v, path, indexedPath, cindent + indent),244      renderTableArray(v, path, indexedPath, cindent) =245        local range = std.range(0, std.length(v) - 1);246        local sections = [247          (cindent + '[[' + std.join('.', std.map(escapeKeyToml, path)) + ']]'248           + (if v[i] == {} then '' else '\n')249           + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))250          for i in range251        ];252        std.join('\n\n', sections);253    if std.isObject(value) then254      renderTableInternal(value, [], [], '')255    else256      error 'TOML body must be an object. Got ' + std.type(value),257258  escapeStringPython(str)::259    std.escapeStringJson(str),260261  escapeStringBash(str_)::262    local str = std.toString(str_);263    local trans(ch) =264      if ch == "'" then265        "'\"'\"'"266      else267        ch;268    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),269270  escapeStringDollars(str_)::271    local str = std.toString(str_);272    local trans(ch) =273      if ch == '$' then274        '$$'275      else276        ch;277    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),278279  manifestJson(value):: std.manifestJsonEx(value, '    ') tailstrict,280281  manifestJsonMinified(value):: std.manifestJsonEx(value, '', '', ':'),282283  manifestYamlStream(value, indent_array_in_object=false, c_document_end=true)::284    if !std.isArray(value) then285      error 'manifestYamlStream only takes arrays, got ' + std.type(value)286    else287      '---\n' + std.join(288        '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object) for e in value]289      ) + if c_document_end then '\n...\n' else '\n',290291292  manifestPython(v)::293    if std.isObject(v) then294      local fields = [295        '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]296        for k in std.objectFields(v)297      ];298      '{%s}' % [std.join(', ', fields)]299    else if std.isArray(v) then300      '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]301    else if std.isString(v) then302      '%s' % [std.escapeStringPython(v)]303    else if std.isFunction(v) then304      error 'cannot manifest function'305    else if std.isNumber(v) then306      std.toString(v)307    else if v == true then308      'True'309    else if v == false then310      'False'311    else if v == null then312      'None',313314  manifestPythonVars(conf)::315    local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];316    std.join('\n', vars + ['']),317318  manifestXmlJsonml(value)::319    if !std.isArray(value) then320      error 'Expected a JSONML value (an array), got %s' % std.type(value)321    else322      local aux(v) =323        if std.isString(v) then324          v325        else326          local tag = v[0];327          local has_attrs = std.length(v) > 1 && std.isObject(v[1]);328          local attrs = if has_attrs then v[1] else {};329          local children = if has_attrs then v[2:] else v[1:];330          local attrs_str =331            std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);332          std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);333334      aux(value),335336  uniq(arr, keyF=id)::337    local f(a, b) =338      if std.length(a) == 0 then339        [b]340      else if keyF(a[std.length(a) - 1]) == keyF(b) then341        a342      else343        a + [b];344    std.foldl(f, arr, []),345346  set(arr, keyF=id)::347    std.uniq(std.sort(arr, keyF), keyF),348349  setMember(x, arr, keyF=id)::350    // TODO(dcunnin): Binary chop for O(log n) complexity351    std.length(std.setInter([x], arr, keyF)) > 0,352353  setUnion(a, b, keyF=id)::354    // NOTE: order matters, values in `a` win355    local aux(a, b, i, j, acc) =356      if i >= std.length(a) then357        acc + b[j:]358      else if j >= std.length(b) then359        acc + a[i:]360      else361        local ak = keyF(a[i]);362        local bk = keyF(b[j]);363        if ak == bk then364          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict365        else if ak < bk then366          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict367        else368          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;369    aux(a, b, 0, 0, []),370371  setInter(a, b, keyF=id)::372    local aux(a, b, i, j, acc) =373      if i >= std.length(a) || j >= std.length(b) then374        acc375      else376        if keyF(a[i]) == keyF(b[j]) then377          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict378        else if keyF(a[i]) < keyF(b[j]) then379          aux(a, b, i + 1, j, acc) tailstrict380        else381          aux(a, b, i, j + 1, acc) tailstrict;382    aux(a, b, 0, 0, []) tailstrict,383384  setDiff(a, b, keyF=id)::385    local aux(a, b, i, j, acc) =386      if i >= std.length(a) then387        acc388      else if j >= std.length(b) then389        acc + a[i:]390      else391        if keyF(a[i]) == keyF(b[j]) then392          aux(a, b, i + 1, j + 1, acc) tailstrict393        else if keyF(a[i]) < keyF(b[j]) then394          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict395        else396          aux(a, b, i, j + 1, acc) tailstrict;397    aux(a, b, 0, 0, []) tailstrict,398399  mergePatch(target, patch)::400    if std.isObject(patch) then401      local target_object =402        if std.isObject(target) then target else {};403404      local target_fields =405        if std.isObject(target_object) then std.objectFields(target_object) else [];406407      local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];408      local both_fields = std.setUnion(target_fields, std.objectFields(patch));409410      {411        [k]:412          if !std.objectHas(patch, k) then413            target_object[k]414          else if !std.objectHas(target_object, k) then415            std.mergePatch(null, patch[k]) tailstrict416          else417            std.mergePatch(target_object[k], patch[k]) tailstrict418        for k in std.setDiff(both_fields, null_fields)419      }420    else421      patch,422423  get(o, f, default=null, inc_hidden=true)::424    if std.objectHasEx(o, f, inc_hidden) then o[f] else default,425426  objectFields(o)::427    std.objectFieldsEx(o, false),428429  objectFieldsAll(o)::430    std.objectFieldsEx(o, true),431432  objectHas(o, f)::433    std.objectHasEx(o, f, false),434435  objectHasAll(o, f)::436    std.objectHasEx(o, f, true),437438  objectValues(o)::439    [o[k] for k in std.objectFields(o)],440441  objectValuesAll(o)::442    [o[k] for k in std.objectFieldsAll(o)],443444  resolvePath(f, r)::445    local arr = std.split(f, '/');446    std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),447448  prune(a)::449    local isContent(b) =450      if b == null then451        false452      else if std.isArray(b) then453        std.length(b) > 0454      else if std.isObject(b) then455        std.length(b) > 0456      else457        true;458    if std.isArray(a) then459      [std.prune(x) for x in a if isContent($.prune(x))]460    else if std.isObject(a) then {461      [x]: $.prune(a[x])462      for x in std.objectFields(a)463      if isContent(std.prune(a[x]))464    } else465      a,466467  find(value, arr)::468    if !std.isArray(arr) then469      error 'find second parameter should be an array, got ' + std.type(arr)470    else471      std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),472}
modifiedtests/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),
 	};
modifiedtests/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()),