difftreelog
refactor saner imports from TLA/std.extVars
in: master
13 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -14,7 +14,7 @@
use jrsonnet_evaluator::{
bail,
error::{ErrorKind::*, Result},
- ImportResolver,
+ AsPathLike, ImportResolver, ResolvePath,
};
use jrsonnet_gcmodule::Acyclic;
use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
@@ -38,7 +38,7 @@
out: RefCell<HashMap<SourcePath, Vec<u8>>>,
}
impl ImportResolver for CallbackImportResolver {
- fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
+ fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
let base = if let Some(p) = from.downcast_ref::<SourceFile>() {
let mut o = p.path().to_owned();
o.pop();
@@ -51,7 +51,11 @@
unreachable!("can't resolve this path");
};
let base = unsafe { crate::unparse_path(&base) };
- let rel = CString::new(path).unwrap();
+ let rel = path.as_path();
+ let rel = match rel {
+ ResolvePath::Str(s) => CString::new(s.as_bytes()).unwrap(),
+ ResolvePath::Path(p) => unsafe { crate::unparse_path(p) },
+ };
let found_here: *mut c_char = null_mut();
let mut buf = null_mut();
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -28,7 +28,7 @@
rustc_hash::FxHashMap,
stack::set_stack_depth_limit,
trace::{CompactFormat, PathResolver, TraceFormat},
- FileImportResolver, IStr, ImportResolver, Result, State, Val,
+ AsPathLike, FileImportResolver, IStr, ImportResolver, Result, State, Val,
};
use jrsonnet_gcmodule::Acyclic;
use jrsonnet_parser::SourcePath;
@@ -62,18 +62,18 @@
}
}
-unsafe fn unparse_path(input: &Path) -> Cow<'_, CStr> {
+unsafe fn unparse_path(input: &Path) -> CString {
#[cfg(target_family = "unix")]
{
use std::os::unix::ffi::OsStrExt;
let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");
- Cow::Owned(str)
+ str
}
#[cfg(not(target_family = "unix"))]
{
let str = input.as_os_str().to_str().expect("bad utf-8");
let cstr = CString::new(str).expect("input has NUL inside");
- Cow::Owned(cstr)
+ cstr
}
}
@@ -93,16 +93,12 @@
self.inner.borrow().load_file_contents(resolved)
}
- fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
+ fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
self.inner.borrow().resolve_from(from, path)
}
- fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+ fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {
self.inner.borrow().resolve_from_default(path)
- }
-
- fn resolve(&self, path: &Path) -> Result<SourcePath> {
- self.inner.borrow().resolve(path)
}
}
bindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -3,7 +3,6 @@
use std::{ffi::CStr, os::raw::c_char};
use jrsonnet_evaluator::{function::TlaArg, IStr};
-use jrsonnet_parser::{ParserSettings, Source};
use crate::VM;
@@ -84,14 +83,7 @@
let code = unsafe { CStr::from_ptr(code) };
let name: IStr = name.to_str().expect("name is not utf-8").into();
- let code: IStr = code.to_str().expect("code is not utf-8").into();
- let code = jrsonnet_parser::parse(
- &code,
- &ParserSettings {
- source: Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.clone()),
- },
- )
- .expect("can't parse TLA code");
+ let code: String = code.to_str().expect("code is not utf-8").to_owned();
- vm.tla_args.insert(name, TlaArg::Code(code));
+ vm.tla_args.insert(name, TlaArg::InlineCode(code));
}
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -182,7 +182,7 @@
let input_str = std::str::from_utf8(&input)?;
s.evaluate_snippet("<stdin>".to_owned(), input_str)?
} else {
- s.import(&input)?
+ s.import(input.as_str())?
};
let tla = opts.tla.tla_opts()?;
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 std::str::FromStr;
use clap::Parser;
-use jrsonnet_evaluator::{trace::PathResolver, Result};
+use jrsonnet_evaluator::{function::TlaArg, trace::PathResolver, Result};
use jrsonnet_stdlib::ContextInitializer;
#[derive(Clone)]
@@ -54,25 +54,20 @@
#[derive(Clone)]
pub struct ExtFile {
pub name: String,
- pub value: String,
+ pub path: String,
}
impl FromStr for ExtFile {
type Err = String;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
- let out: Vec<&str> = s.split('=').collect();
- if out.len() != 2 {
+ let Some((name, path)) = s.split_once('=') else {
return Err("bad ext-file syntax".to_owned());
- }
- let file = read_to_string(out[1]);
- match file {
- Ok(content) => Ok(Self {
- name: out[0].into(),
- value: content,
- }),
- Err(e) => Err(format!("{e}")),
- }
+ };
+ Ok(Self {
+ name: name.into(),
+ path: path.into(),
+ })
}
}
@@ -110,16 +105,27 @@
}
let ctx = ContextInitializer::new(PathResolver::new_cwd_fallback());
for ext in &self.ext_str {
- ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
+ ctx.settings_mut().ext_vars.insert(
+ ext.name.as_str().into(),
+ TlaArg::String(ext.value.as_str().into()),
+ );
}
for ext in &self.ext_str_file {
- ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
+ ctx.settings_mut().ext_vars.insert(
+ ext.name.as_str().into(),
+ TlaArg::ImportStr(ext.path.clone()),
+ );
}
for ext in &self.ext_code {
- ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;
+ ctx.settings_mut().ext_vars.insert(
+ ext.name.as_str().into(),
+ TlaArg::InlineCode(ext.value.clone()),
+ );
}
for ext in &self.ext_code_file {
- ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;
+ ctx.settings_mut()
+ .ext_vars
+ .insert(ext.name.as_str().into(), TlaArg::Import(ext.path.clone()));
}
Ok(Some(ctx))
}
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,12 +1,5 @@
use clap::Parser;
-use jrsonnet_evaluator::{
- error::{ErrorKind, Result},
- function::TlaArg,
- gc::WithCapacityExt as _,
- rustc_hash::FxHashMap,
- IStr,
-};
-use jrsonnet_parser::{ParserSettings, Source};
+use jrsonnet_evaluator::{IStr, error::Result, function::TlaArg, gc::WithCapacityExt as _, rustc_hash::FxHashMap};
use crate::{ExtFile, ExtStr};
@@ -35,37 +28,27 @@
impl TlaOpts {
pub fn tla_opts(&self) -> Result<FxHashMap<IStr, TlaArg>> {
let mut out = FxHashMap::new();
- for (name, value) in self
- .tla_str
- .iter()
- .map(|c| (&c.name, &c.value))
- .chain(self.tla_str_file.iter().map(|c| (&c.name, &c.value)))
- {
- out.insert(name.into(), TlaArg::String(value.into()));
+ for ext in &self.tla_str {
+ out.insert(
+ ext.name.as_str().into(),
+ TlaArg::String(ext.value.as_str().into()),
+ );
}
- for (name, code) in self
- .tla_code
- .iter()
- .map(|c| (&c.name, &c.value))
- .chain(self.tla_code_file.iter().map(|c| (&c.name, &c.value)))
- {
- let source = Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.into());
+ for ext in &self.tla_str_file {
out.insert(
- (name as &str).into(),
- TlaArg::Code(
- jrsonnet_parser::parse(
- code,
- &ParserSettings {
- source: source.clone(),
- },
- )
- .map_err(|e| ErrorKind::ImportSyntaxError {
- path: source,
- error: Box::new(e),
- })?,
- ),
+ ext.name.as_str().into(),
+ TlaArg::ImportStr(ext.name.as_str().into()),
+ );
+ }
+ for ext in &self.tla_code {
+ out.insert(
+ ext.name.as_str().into(),
+ TlaArg::InlineCode(ext.value.clone()),
);
}
+ for ext in &self.tla_code_file {
+ out.insert(ext.name.as_str().into(), TlaArg::Import(ext.path.clone()));
+ }
Ok(out)
}
}
crates/jrsonnet-evaluator/src/async_import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/async_import.rs
+++ b/crates/jrsonnet-evaluator/src/async_import.rs
@@ -1,7 +1,6 @@
-use std::{any::Any, cell::RefCell, future::Future, path::Path};
+use std::{any::Any, cell::RefCell, future::Future};
use jrsonnet_gcmodule::Acyclic;
-use jrsonnet_interner::IStr;
use jrsonnet_parser::{
ArgsDesc, AssertStmt, BindSpec, CompSpec, Destruct, Expr, FieldMember, FieldName, ForSpecData,
IfSpecData, LocExpr, Member, ObjBody, Param, ParamsDesc, ParserSettings, SliceDesc, Source,
@@ -9,10 +8,10 @@
};
use rustc_hash::FxHashMap;
-use crate::{bail, FileData, ImportResolver, State};
+use crate::{AsPathLike, FileData, ImportResolver, ResolvePathOwned, State};
pub struct Import {
- path: IStr,
+ path: ResolvePathOwned,
expression: bool,
}
@@ -137,7 +136,7 @@
Expr::Import(v) | Expr::ImportStr(v) | Expr::ImportBin(v) => {
if let Expr::Str(s) = &*v.expr() {
out.0.push(Import {
- path: s.clone(),
+ path: ResolvePathOwned::Str(s.to_string()),
expression: matches!(&*expr.expr(), Expr::Import(_)),
});
}
@@ -229,16 +228,14 @@
fn resolve_from(
&self,
from: &SourcePath,
- path: &str,
+ path: &dyn AsPathLike,
) -> impl Future<Output = Result<SourcePath, Self::Error>>;
fn resolve_from_default(
&self,
- path: &str,
+ path: &dyn AsPathLike,
) -> impl Future<Output = Result<SourcePath, Self::Error>> {
async { self.resolve_from(&SourcePath::default(), path).await }
}
- /// Resolves absolute path, doesn't supports jpath and other fancy things
- fn resolve(&self, path: &Path) -> impl Future<Output = Result<SourcePath, Self::Error>>;
/// Load resolved file
/// This should only be called with value returned
@@ -253,31 +250,25 @@
#[derive(Acyclic)]
struct ResolvedImportResolver {
- resolved: RefCell<FxHashMap<(SourcePath, IStr), (SourcePath, bool)>>,
+ resolved: RefCell<FxHashMap<(SourcePath, ResolvePathOwned), (SourcePath, bool)>>,
}
impl ImportResolver for ResolvedImportResolver {
fn load_file_contents(&self, _resolved: &SourcePath) -> crate::Result<Vec<u8>> {
unreachable!("all files should be loaded at this point");
}
- fn resolve_from(&self, from: &SourcePath, path: &str) -> crate::Result<SourcePath> {
+ fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> crate::Result<SourcePath> {
Ok(self
.resolved
.borrow()
- .get(&(from.clone(), path.into()))
+ .get(&(from.clone(), path.as_path().to_owned()))
.expect("all imports should be resolved at this point")
.0
.clone())
}
- fn resolve_from_default(&self, path: &str) -> crate::Result<SourcePath> {
+ fn resolve_from_default(&self, path: &dyn AsPathLike) -> crate::Result<SourcePath> {
self.resolve_from(&SourcePath::default(), path)
- }
-
- fn resolve(&self, path: &Path) -> crate::Result<SourcePath> {
- bail!(crate::error::ErrorKind::AbsoluteImportNotSupported(
- path.to_owned()
- ))
}
}
@@ -288,7 +279,7 @@
}
#[allow(clippy::future_not_send)]
-pub async fn async_import<H>(s: State, handler: H, path: impl AsRef<Path>) -> Result<(), H::Error>
+pub async fn async_import<H>(s: State, handler: H, path: &dyn AsPathLike) -> Result<(), H::Error>
where
H: AsyncImportResolver,
{
@@ -299,7 +290,7 @@
let mut resolved_map = resolved.resolved.borrow_mut();
let mut queue = vec![Job::LoadFile {
- path: handler.resolve(path.as_ref()).await?,
+ path: handler.resolve_from_default(path).await?,
parse: true,
}];
while let Some(job) = queue.pop() {
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use std::{2 cmp::Ordering,3 convert::Infallible,4 fmt::{Debug, Display},5 path::PathBuf,6};78use jrsonnet_gcmodule::Trace;9use jrsonnet_interner::IStr;10use jrsonnet_parser::{BinaryOpType, LocExpr, Source, SourcePath, Span, UnaryOpType};11use jrsonnet_types::ValType;12use thiserror::Error;1314use crate::{15 function::{builtin::ParamDefault, CallLocation},16 stdlib::format::FormatError,17 typed::TypeLocError,18 val::ConvertNumValueError,19 ObjValue,20};2122pub(crate) fn format_found(list: &[IStr], what: &str) -> String {23 if list.is_empty() {24 return String::new();25 }26 let mut out = String::new();27 out.push_str("\nThere ");28 if list.len() > 1 {29 out.push_str("are ");30 } else {31 out.push_str("is a ");32 }33 out.push_str(what);34 if list.len() > 1 {35 out.push('s');36 }37 out.push_str(" with similar name");38 if list.len() > 1 {39 out.push('s');40 }41 out.push_str(" present: ");42 for (i, v) in list.iter().enumerate() {43 if i != 0 {44 out.push_str(", ");45 }46 out.push_str(v as &str);47 }48 out49}5051fn format_signature(sig: &FunctionSignature) -> String {52 let mut out = String::new();53 out.push_str("\nFunction has the following signature: ");54 out.push('(');55 if sig.is_empty() {56 out.push_str("/*no arguments*/");57 } else {58 for (i, (name, default)) in sig.iter().enumerate() {59 if i != 0 {60 out.push_str(", ");61 }62 if let Some(name) = name {63 out.push_str(name);64 } else {65 out.push_str("<unnamed>");66 }67 match default {68 ParamDefault::None => {}69 ParamDefault::Exists => out.push_str(" = <default>"),70 ParamDefault::Literal(lit) => {71 out.push_str(" = ");72 out.push_str(lit);73 }74 }75 }76 }77 out.push(')');78 out79}8081const fn format_empty_str(str: &str) -> &str {82 if str.is_empty() {83 "\"\" (empty string)"84 } else {85 str86 }87}8889pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {90 let mut heap = Vec::new();91 for field in v.fields_ex(92 true,93 #[cfg(feature = "exp-preserve-order")]94 false,95 ) {96 let conf = strsim::jaro_winkler(field.as_str(), key.as_str());97 if conf < 0.8 {98 continue;99 }100 assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");101102 heap.push((conf, field));103 }104 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));105 heap.into_iter().map(|v| v.1).collect()106}107108type FunctionSignature = Vec<(Option<IStr>, ParamDefault)>;109110/// Possible errors111#[allow(missing_docs)]112#[derive(Error, Debug, Clone, Trace)]113#[non_exhaustive]114pub enum ErrorKind {115 #[error("intrinsic not found: {0}")]116 IntrinsicNotFound(IStr),117118 #[error("operator {0} does not operate on type {1}")]119 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),120 #[error("binary operation {1} {0} {2} is not implemented")]121 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),122123 #[error("no top level object in this context")]124 NoTopLevelObjectFound,125 #[error("self is only usable inside objects")]126 CantUseSelfOutsideOfObject,127 #[error("no super found")]128 NoSuperFound,129130 #[error("for loop can only iterate over arrays")]131 InComprehensionCanOnlyIterateOverArray,132133 #[error("array out of bounds: {0} is not within [0,{1})")]134 ArrayBoundsError(isize, usize),135 #[error("string out of bounds: {0} is not within [0,{1})")]136 StringBoundsError(usize, usize),137138 #[error("assert failed: {}", format_empty_str(.0))]139 AssertionFailed(IStr),140141 #[error("local is not defined: {0}{found}", found = format_found(.1, "local"))]142 VariableIsNotDefined(IStr, Vec<IStr>),143 #[error("duplicate local var: {0}")]144 DuplicateLocalVar(IStr),145146 #[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]147 TypeMismatch(&'static str, Vec<ValType>, ValType),148 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]149 NoSuchField(IStr, Vec<IStr>),150151 #[error("only functions can be called, got {0}")]152 OnlyFunctionsCanBeCalledGot(ValType),153 #[error("parameter {0} is not defined")]154 UnknownFunctionParameter(String),155 #[error("argument {0} is already bound")]156 BindingParameterASecondTime(IStr),157 #[error("too many args, function has {0}{sig}", sig = format_signature(.1))]158 TooManyArgsFunctionHas(usize, FunctionSignature),159 #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]160 FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),161162 #[error("external variable is not defined: {0}")]163 UndefinedExternalVariable(IStr),164165 #[error("field name should be string, got {0}")]166 FieldMustBeStringGot(ValType),167 #[error("duplicate field name: {}", format_empty_str(.0))]168 DuplicateFieldName(IStr),169170 #[error("attempted to index array with string {}", format_empty_str(.0))]171 AttemptedIndexAnArrayWithString(IStr),172 #[error("{0} index type should be {1}, got {2}")]173 ValueIndexMustBeTypeGot(ValType, ValType, ValType),174 #[error("cant index into {0}")]175 CantIndexInto(ValType),176 #[error("{0} is not indexable")]177 ValueIsNotIndexable(ValType),178179 #[error("super can't be used standalone")]180 StandaloneSuper,181182 #[error("can't resolve {1} from {0}")]183 ImportFileNotFound(SourcePath, String),184 #[error("can't resolve absolute {0}")]185 AbsoluteImportFileNotFound(PathBuf),186 #[error("resolved file not found: {:?}", .0)]187 ResolvedFileNotFound(SourcePath),188 #[error("can't import {0}: is a directory")]189 ImportIsADirectory(SourcePath),190 #[error("imported file is not valid utf-8: {0:?}")]191 ImportBadFileUtf8(SourcePath),192 #[error("import io error: {0}")]193 ImportIo(String),194 #[error("tried to import {1} from {0}, but imports are not supported")]195 ImportNotSupported(SourcePath, String),196 #[error("tried to import {0}, but absolute imports are not supported")]197 AbsoluteImportNotSupported(PathBuf),198 #[error("can't import from virtual file")]199 CantImportFromVirtualFile,200 #[error(201 "syntax error: {}",202 // Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225203 {.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {204 format!(205 "expected {}, got {:?}",206 .error.expected,207 .path.code().chars().nth(error.location.offset)208 .map_or_else(|| "EOF".into(), |c| c.to_string())209 )210 }, |v| v[3..].into())}211 )]212 ImportSyntaxError {213 path: Source,214 #[trace(skip)]215 error: Box<jrsonnet_parser::ParseError>,216 },217218 #[error("runtime error: {}", format_empty_str(.0))]219 RuntimeError(IStr),220 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]221 StackOverflow,222 #[error("infinite recursion detected")]223 InfiniteRecursionDetected,224 #[error("tried to index by fractional value")]225 FractionalIndex,226 #[error("attempted to divide by zero")]227 DivisionByZero,228229 #[error("string manifest output is not an string")]230 StringManifestOutputIsNotAString,231 #[error("stream manifest output is not an array")]232 StreamManifestOutputIsNotAArray,233 #[error("multi manifest output is not an object")]234 MultiManifestOutputIsNotAObject,235236 #[error("cant recurse stream manifest")]237 StreamManifestOutputCannotBeRecursed,238 #[error("stream manifest output cannot consist of raw strings")]239 StreamManifestCannotNestString,240241 #[error("{}", format_empty_str(.0))]242 ImportCallbackError(String),243 #[error("invalid unicode codepoint: {0}")]244 InvalidUnicodeCodepointGot(u32),245246 #[error("convert num value: {0}")]247 ConvertNumValue(#[from] ConvertNumValueError),248249 #[error("format error: {0}")]250 Format(#[from] FormatError),251 #[error("type error: {0}")]252 TypeError(TypeLocError),253254 #[cfg(feature = "anyhow-error")]255 #[error(transparent)]256 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),257}258259#[cfg(feature = "anyhow-error")]260impl From<anyhow::Error> for Error {261 fn from(e: anyhow::Error) -> Self {262 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))263 }264}265266impl From<ErrorKind> for Error {267 fn from(e: ErrorKind) -> Self {268 Self::new(e)269 }270}271272impl From<Infallible> for Error {273 fn from(_value: Infallible) -> Self {274 unreachable!()275 }276}277278/// Single stack trace frame279#[derive(Clone, Debug, Trace)]280pub struct StackTraceElement {281 /// Source of this frame282 /// Some frames only act as description, without attached source283 pub location: Option<Span>,284 /// Frame description285 pub desc: String,286}287#[derive(Debug, Clone, Trace)]288pub struct StackTrace(pub Vec<StackTraceElement>);289290#[derive(Clone, Trace)]291pub struct Error(Box<(ErrorKind, StackTrace)>);292impl Error {293 pub fn new(e: ErrorKind) -> Self {294 Self(Box::new((e, StackTrace(vec![]))))295 }296297 pub const fn error(&self) -> &ErrorKind {298 &(self.0).0299 }300 pub fn error_mut(&mut self) -> &mut ErrorKind {301 &mut (self.0).0302 }303 pub const fn trace(&self) -> &StackTrace {304 &(self.0).1305 }306 pub fn trace_mut(&mut self) -> &mut StackTrace {307 &mut (self.0).1308 }309}310impl Display for Error {311 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {312 writeln!(f, "{}", self.0 .0)?;313 for el in &self.0 .1 .0 {314 write!(f, "\t{}", el.desc)?;315 if let Some(loc) = &el.location {316 write!(f, "at {}", loc.0 .0 .0)?;317 loc.0.map_source_locations(&[loc.1, loc.2]);318 }319 writeln!(f)?;320 }321 Ok(())322 }323}324impl Debug for Error {325 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {326 f.debug_tuple("LocError").field(&self.0).finish()327 }328}329impl std::error::Error for Error {}330331pub trait ErrorSource {332 fn to_location(self) -> Option<Span>;333}334impl ErrorSource for &LocExpr {335 fn to_location(self) -> Option<Span> {336 Some(self.span())337 }338}339impl ErrorSource for &Span {340 fn to_location(self) -> Option<Span> {341 Some(self.clone())342 }343}344impl ErrorSource for CallLocation<'_> {345 fn to_location(self) -> Option<Span> {346 self.0.cloned()347 }348}349350pub type Result<V, E = Error> = std::result::Result<V, E>;351pub trait ResultExt: Sized {352 #[must_use]353 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;354 #[must_use]355 fn description(self, msg: &str) -> Self {356 self.with_description(|| msg)357 }358359 #[must_use]360 fn with_description_src<O: Into<String>>(361 self,362 src: impl ErrorSource,363 msg: impl FnOnce() -> O,364 ) -> Self;365 #[must_use]366 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {367 self.with_description_src(src, || msg)368 }369}370impl<T> ResultExt for Result<T, Error> {371 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {372 if let Err(e) = &mut self {373 let trace = e.trace_mut();374 trace.0.push(StackTraceElement {375 location: None,376 desc: msg().into(),377 });378 }379 self380 }381382 fn with_description_src<O: Into<String>>(383 mut self,384 src: impl ErrorSource,385 msg: impl FnOnce() -> O,386 ) -> Self {387 if let Err(e) = &mut self {388 let trace = e.trace_mut();389 trace.0.push(StackTraceElement {390 location: src.to_location(),391 desc: msg().into(),392 });393 }394 self395 }396}397398#[macro_export]399macro_rules! bail {400 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {401 return Err($w$(::$i)*$(($($tt)*))?.into())402 };403 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {404 return Err($w$(::$i)*$({$($tt)*})?.into())405 };406 ($l:literal$(, $($tt:tt)*)?) => {407 return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())408 };409}410411#[macro_export]412macro_rules! runtime_error {413 ($l:literal$(, $($tt:tt)*)?) => {414 $crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))415 };416}1use std::{2 cmp::Ordering,3 convert::Infallible,4 fmt::{Debug, Display},5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, LocExpr, Source, SourcePath, Span, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{14 function::{builtin::ParamDefault, CallLocation},15 stdlib::format::FormatError,16 typed::TypeLocError,17 val::ConvertNumValueError,18 ObjValue, ResolvePathOwned,19};2021pub(crate) fn format_found(list: &[IStr], what: &str) -> String {22 if list.is_empty() {23 return String::new();24 }25 let mut out = String::new();26 out.push_str("\nThere ");27 if list.len() > 1 {28 out.push_str("are ");29 } else {30 out.push_str("is a ");31 }32 out.push_str(what);33 if list.len() > 1 {34 out.push('s');35 }36 out.push_str(" with similar name");37 if list.len() > 1 {38 out.push('s');39 }40 out.push_str(" present: ");41 for (i, v) in list.iter().enumerate() {42 if i != 0 {43 out.push_str(", ");44 }45 out.push_str(v as &str);46 }47 out48}4950fn format_signature(sig: &FunctionSignature) -> String {51 let mut out = String::new();52 out.push_str("\nFunction has the following signature: ");53 out.push('(');54 if sig.is_empty() {55 out.push_str("/*no arguments*/");56 } else {57 for (i, (name, default)) in sig.iter().enumerate() {58 if i != 0 {59 out.push_str(", ");60 }61 if let Some(name) = name {62 out.push_str(name);63 } else {64 out.push_str("<unnamed>");65 }66 match default {67 ParamDefault::None => {}68 ParamDefault::Exists => out.push_str(" = <default>"),69 ParamDefault::Literal(lit) => {70 out.push_str(" = ");71 out.push_str(lit);72 }73 }74 }75 }76 out.push(')');77 out78}7980const fn format_empty_str(str: &str) -> &str {81 if str.is_empty() {82 "\"\" (empty string)"83 } else {84 str85 }86}8788pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {89 let mut heap = Vec::new();90 for field in v.fields_ex(91 true,92 #[cfg(feature = "exp-preserve-order")]93 false,94 ) {95 let conf = strsim::jaro_winkler(field.as_str(), key.as_str());96 if conf < 0.8 {97 continue;98 }99 assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");100101 heap.push((conf, field));102 }103 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));104 heap.into_iter().map(|v| v.1).collect()105}106107type FunctionSignature = Vec<(Option<IStr>, ParamDefault)>;108109/// Possible errors110#[allow(missing_docs)]111#[derive(Error, Debug, Clone, Trace)]112#[non_exhaustive]113pub enum ErrorKind {114 #[error("intrinsic not found: {0}")]115 IntrinsicNotFound(IStr),116117 #[error("operator {0} does not operate on type {1}")]118 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),119 #[error("binary operation {1} {0} {2} is not implemented")]120 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),121122 #[error("no top level object in this context")]123 NoTopLevelObjectFound,124 #[error("self is only usable inside objects")]125 CantUseSelfOutsideOfObject,126 #[error("no super found")]127 NoSuperFound,128129 #[error("for loop can only iterate over arrays")]130 InComprehensionCanOnlyIterateOverArray,131132 #[error("array out of bounds: {0} is not within [0,{1})")]133 ArrayBoundsError(isize, usize),134 #[error("string out of bounds: {0} is not within [0,{1})")]135 StringBoundsError(usize, usize),136137 #[error("assert failed: {}", format_empty_str(.0))]138 AssertionFailed(IStr),139140 #[error("local is not defined: {0}{found}", found = format_found(.1, "local"))]141 VariableIsNotDefined(IStr, Vec<IStr>),142 #[error("duplicate local var: {0}")]143 DuplicateLocalVar(IStr),144145 #[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]146 TypeMismatch(&'static str, Vec<ValType>, ValType),147 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]148 NoSuchField(IStr, Vec<IStr>),149150 #[error("only functions can be called, got {0}")]151 OnlyFunctionsCanBeCalledGot(ValType),152 #[error("parameter {0} is not defined")]153 UnknownFunctionParameter(String),154 #[error("argument {0} is already bound")]155 BindingParameterASecondTime(IStr),156 #[error("too many args, function has {0}{sig}", sig = format_signature(.1))]157 TooManyArgsFunctionHas(usize, FunctionSignature),158 #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]159 FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),160161 #[error("external variable is not defined: {0}")]162 UndefinedExternalVariable(IStr),163164 #[error("field name should be string, got {0}")]165 FieldMustBeStringGot(ValType),166 #[error("duplicate field name: {}", format_empty_str(.0))]167 DuplicateFieldName(IStr),168169 #[error("attempted to index array with string {}", format_empty_str(.0))]170 AttemptedIndexAnArrayWithString(IStr),171 #[error("{0} index type should be {1}, got {2}")]172 ValueIndexMustBeTypeGot(ValType, ValType, ValType),173 #[error("cant index into {0}")]174 CantIndexInto(ValType),175 #[error("{0} is not indexable")]176 ValueIsNotIndexable(ValType),177178 #[error("super can't be used standalone")]179 StandaloneSuper,180181 #[error("can't resolve {1} from {0}")]182 ImportFileNotFound(SourcePath, ResolvePathOwned),183 #[error("resolved file not found: {:?}", .0)]184 ResolvedFileNotFound(SourcePath),185 #[error("can't import {0}: is a directory")]186 ImportIsADirectory(SourcePath),187 #[error("imported file is not valid utf-8: {0:?}")]188 ImportBadFileUtf8(SourcePath),189 #[error("import io error: {0}")]190 ImportIo(String),191 #[error("tried to import {1} from {0}, but imports are not supported")]192 ImportNotSupported(SourcePath, ResolvePathOwned),193 #[error("can't import from virtual file")]194 CantImportFromVirtualFile,195 #[error(196 "syntax error: {}",197 // Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225198 {.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {199 format!(200 "expected {}, got {:?}",201 .error.expected,202 .path.code().chars().nth(error.location.offset)203 .map_or_else(|| "EOF".into(), |c| c.to_string())204 )205 }, |v| v[3..].into())}206 )]207 ImportSyntaxError {208 path: Source,209 #[trace(skip)]210 error: Box<jrsonnet_parser::ParseError>,211 },212213 #[error("runtime error: {}", format_empty_str(.0))]214 RuntimeError(IStr),215 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]216 StackOverflow,217 #[error("infinite recursion detected")]218 InfiniteRecursionDetected,219 #[error("tried to index by fractional value")]220 FractionalIndex,221 #[error("attempted to divide by zero")]222 DivisionByZero,223224 #[error("string manifest output is not an string")]225 StringManifestOutputIsNotAString,226 #[error("stream manifest output is not an array")]227 StreamManifestOutputIsNotAArray,228 #[error("multi manifest output is not an object")]229 MultiManifestOutputIsNotAObject,230231 #[error("cant recurse stream manifest")]232 StreamManifestOutputCannotBeRecursed,233 #[error("stream manifest output cannot consist of raw strings")]234 StreamManifestCannotNestString,235236 #[error("{}", format_empty_str(.0))]237 ImportCallbackError(String),238 #[error("invalid unicode codepoint: {0}")]239 InvalidUnicodeCodepointGot(u32),240241 #[error("convert num value: {0}")]242 ConvertNumValue(#[from] ConvertNumValueError),243244 #[error("format error: {0}")]245 Format(#[from] FormatError),246 #[error("type error: {0}")]247 TypeError(TypeLocError),248249 #[cfg(feature = "anyhow-error")]250 #[error(transparent)]251 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),252}253254#[cfg(feature = "anyhow-error")]255impl From<anyhow::Error> for Error {256 fn from(e: anyhow::Error) -> Self {257 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))258 }259}260261impl From<ErrorKind> for Error {262 fn from(e: ErrorKind) -> Self {263 Self::new(e)264 }265}266267impl From<Infallible> for Error {268 fn from(_value: Infallible) -> Self {269 unreachable!()270 }271}272273/// Single stack trace frame274#[derive(Clone, Debug, Trace)]275pub struct StackTraceElement {276 /// Source of this frame277 /// Some frames only act as description, without attached source278 pub location: Option<Span>,279 /// Frame description280 pub desc: String,281}282#[derive(Debug, Clone, Trace)]283pub struct StackTrace(pub Vec<StackTraceElement>);284285#[derive(Clone, Trace)]286pub struct Error(Box<(ErrorKind, StackTrace)>);287impl Error {288 pub fn new(e: ErrorKind) -> Self {289 Self(Box::new((e, StackTrace(vec![]))))290 }291292 pub const fn error(&self) -> &ErrorKind {293 &(self.0).0294 }295 pub fn error_mut(&mut self) -> &mut ErrorKind {296 &mut (self.0).0297 }298 pub const fn trace(&self) -> &StackTrace {299 &(self.0).1300 }301 pub fn trace_mut(&mut self) -> &mut StackTrace {302 &mut (self.0).1303 }304}305impl Display for Error {306 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {307 writeln!(f, "{}", self.0 .0)?;308 for el in &self.0 .1 .0 {309 write!(f, "\t{}", el.desc)?;310 if let Some(loc) = &el.location {311 write!(f, "at {}", loc.0 .0 .0)?;312 loc.0.map_source_locations(&[loc.1, loc.2]);313 }314 writeln!(f)?;315 }316 Ok(())317 }318}319impl Debug for Error {320 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {321 f.debug_tuple("LocError").field(&self.0).finish()322 }323}324impl std::error::Error for Error {}325326pub trait ErrorSource {327 fn to_location(self) -> Option<Span>;328}329impl ErrorSource for &LocExpr {330 fn to_location(self) -> Option<Span> {331 Some(self.span())332 }333}334impl ErrorSource for &Span {335 fn to_location(self) -> Option<Span> {336 Some(self.clone())337 }338}339impl ErrorSource for CallLocation<'_> {340 fn to_location(self) -> Option<Span> {341 self.0.cloned()342 }343}344345pub type Result<V, E = Error> = std::result::Result<V, E>;346pub trait ResultExt: Sized {347 #[must_use]348 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;349 #[must_use]350 fn description(self, msg: &str) -> Self {351 self.with_description(|| msg)352 }353354 #[must_use]355 fn with_description_src<O: Into<String>>(356 self,357 src: impl ErrorSource,358 msg: impl FnOnce() -> O,359 ) -> Self;360 #[must_use]361 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {362 self.with_description_src(src, || msg)363 }364}365impl<T> ResultExt for Result<T, Error> {366 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {367 if let Err(e) = &mut self {368 let trace = e.trace_mut();369 trace.0.push(StackTraceElement {370 location: None,371 desc: msg().into(),372 });373 }374 self375 }376377 fn with_description_src<O: Into<String>>(378 mut self,379 src: impl ErrorSource,380 msg: impl FnOnce() -> O,381 ) -> Self {382 if let Err(e) = &mut self {383 let trace = e.trace_mut();384 trace.0.push(StackTraceElement {385 location: src.to_location(),386 desc: msg().into(),387 });388 }389 self390 }391}392393#[macro_export]394macro_rules! bail {395 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {396 return Err($w$(::$i)*$(($($tt)*))?.into())397 };398 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {399 return Err($w$(::$i)*$({$($tt)*})?.into())400 };401 ($l:literal$(, $($tt:tt)*)?) => {402 return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())403 };404}405406#[macro_export]407macro_rules! runtime_error {408 ($l:literal$(, $($tt:tt)*)?) => {409 $crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))410 };411}crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -682,7 +682,7 @@
};
let tmp = loc.clone().0;
let s = ctx.state();
- let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
+ let resolved_path = s.resolve_from(tmp.source_path(), path)?;
match i {
Import(_) => in_frame(
CallLocation::new(&loc),
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -2,7 +2,7 @@
use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ArgsDesc, LocExpr};
+use jrsonnet_parser::{ArgsDesc, LocExpr, SourceFifo, SourcePath};
use crate::{evaluate, typed::Typed, Context, Result, Thunk, Val};
@@ -41,22 +41,34 @@
#[derive(Clone, Trace)]
pub enum TlaArg {
String(IStr),
- Code(LocExpr),
Val(Val),
Lazy(Thunk<Val>),
+ Import(String),
+ ImportStr(String),
+ InlineCode(String),
}
impl ArgLike for TlaArg {
- fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
+ fn evaluate_arg(&self, ctx: Context, _tailstrict: bool) -> Result<Thunk<Val>> {
match self {
Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
- Self::Code(code) => Ok(if tailstrict {
- Thunk::evaluated(evaluate(ctx, code)?)
- } else {
- let code = code.clone();
- Thunk!(move || evaluate(ctx, &code))
- }),
Self::Val(val) => Ok(Thunk::evaluated(val.clone())),
Self::Lazy(lazy) => Ok(lazy.clone()),
+ Self::Import(p) => {
+ let resolved = ctx.state().resolve_from_default(&p.as_str())?;
+ Ok(Thunk!(move || ctx.state().import_resolved(resolved)))
+ }
+ Self::ImportStr(p) => {
+ let resolved = ctx.state().resolve_from_default(&p.as_str())?;
+ Ok(Thunk!(move || ctx
+ .state()
+ .import_resolved_str(resolved)
+ .map(Val::string)))
+ }
+ Self::InlineCode(p) => {
+ let resolved =
+ SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
+ Ok(Thunk!(move || ctx.state().import_resolved(resolved)))
+ }
}
}
}
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,7 +1,8 @@
use std::{
any::Any,
+ borrow::Cow,
env::current_dir,
- fs,
+ fmt, fs,
io::{ErrorKind, Read},
path::{Path, PathBuf},
};
@@ -9,12 +10,85 @@
use fs::File;
use jrsonnet_gcmodule::Acyclic;
use jrsonnet_interner::IBytes;
-use jrsonnet_parser::{SourceDirectory, SourceFifo, SourceFile, SourcePath};
+use jrsonnet_parser::{IStr, SourceDirectory, SourceFifo, SourceFile, SourcePath};
use crate::{
bail,
error::{ErrorKind::*, Result},
};
+#[derive(Clone, Debug, Acyclic, Eq, Hash, PartialEq)]
+pub enum ResolvePathOwned {
+ Str(String),
+ Path(PathBuf),
+}
+impl fmt::Display for ResolvePathOwned {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ ResolvePathOwned::Str(s) => write!(f, "{s}"),
+ ResolvePathOwned::Path(p) => write!(f, "{}", p.display()),
+ }
+ }
+}
+#[derive(Clone, Copy)]
+pub enum ResolvePath<'s> {
+ Str(&'s str),
+ Path(&'s Path),
+}
+impl ResolvePath<'_> {
+ pub fn to_owned(self) -> ResolvePathOwned {
+ match self {
+ ResolvePath::Str(s) => ResolvePathOwned::Str(s.to_owned()),
+ ResolvePath::Path(p) => ResolvePathOwned::Path(p.to_owned()),
+ }
+ }
+}
+impl AsRef<Path> for ResolvePath<'_> {
+ fn as_ref(&self) -> &Path {
+ match self {
+ ResolvePath::Str(s) => s.as_ref(),
+ ResolvePath::Path(p) => p,
+ }
+ }
+}
+pub trait AsPathLike {
+ fn as_path(&self) -> ResolvePath<'_>;
+}
+impl<T> AsPathLike for &T
+where
+ T: AsPathLike + ?Sized,
+{
+ fn as_path(&self) -> ResolvePath<'_> {
+ (*self).as_path()
+ }
+}
+impl AsPathLike for str {
+ fn as_path(&self) -> ResolvePath<'_> {
+ ResolvePath::Str(self)
+ }
+}
+impl AsPathLike for IStr {
+ fn as_path(&self) -> ResolvePath<'_> {
+ ResolvePath::Str(self)
+ }
+}
+impl AsPathLike for Cow<'_, Path> {
+ fn as_path(&self) -> ResolvePath<'_> {
+ ResolvePath::Path(self.as_ref())
+ }
+}
+impl AsPathLike for Path {
+ fn as_path(&self) -> ResolvePath<'_> {
+ ResolvePath::Path(self)
+ }
+}
+impl AsPathLike for ResolvePathOwned {
+ fn as_path(&self) -> ResolvePath<'_> {
+ match self {
+ ResolvePathOwned::Str(s) => ResolvePath::Str(s),
+ ResolvePathOwned::Path(path_buf) => ResolvePath::Path(path_buf),
+ }
+ }
+}
/// Implements file resolution logic for `import` and `importStr`
pub trait ImportResolver: Acyclic + Any {
@@ -24,15 +98,11 @@
///
/// `from` should only be returned from [`ImportResolver::resolve`], or from other defined file, any other value
/// may result in panic
- fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
- bail!(ImportNotSupported(from.clone(), path.into()))
+ fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
+ bail!(ImportNotSupported(from.clone(), path.as_path().to_owned()))
}
- fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+ fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {
self.resolve_from(&SourcePath::default(), path)
- }
- /// Resolves absolute path, doesn't supports jpath and other fancy things
- fn resolve(&self, path: &Path) -> Result<SourcePath> {
- bail!(AbsoluteImportNotSupported(path.to_owned()))
}
/// Load resolved file
@@ -105,7 +175,8 @@
}
impl ImportResolver for FileImportResolver {
- fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
+ fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
+ let path = path.as_path();
let mut direct = if let Some(f) = from.downcast_ref::<SourceFile>() {
let mut o = f.path().to_owned();
o.pop();
@@ -130,12 +201,6 @@
}
}
bail!(ImportFileNotFound(from.clone(), path.to_owned()))
- }
- fn resolve(&self, path: &Path) -> Result<SourcePath> {
- let Some(source) = check_path(path)? else {
- bail!(AbsoluteImportFileNotFound(path.to_owned()))
- };
- Ok(source)
}
fn load_file_contents(&self, id: &SourcePath) -> Result<Vec<u8>> {
@@ -155,7 +220,7 @@
Ok(out)
}
- fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+ fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {
self.resolve_from(&SourcePath::default(), path)
}
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -29,7 +29,6 @@
cell::{RefCell, RefMut},
collections::hash_map::Entry,
fmt::{self, Debug},
- path::Path,
rc::Rc,
};
@@ -349,12 +348,12 @@
}
/// Has same semantics as `import 'path'` called from `from` file
- pub fn import_from(&self, from: &SourcePath, path: &str) -> Result<Val> {
- let resolved = self.resolve_from(from, path)?;
+ pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {
+ let resolved = self.resolve_from(from, &path)?;
self.import_resolved(resolved)
}
- pub fn import(&self, path: impl AsRef<Path>) -> Result<Val> {
- let resolved = self.resolve(path)?;
+ pub fn import(&self, path: impl AsPathLike) -> Result<Val> {
+ let resolved = self.resolve_from_default(&path)?;
self.import_resolved(resolved)
}
@@ -468,14 +467,12 @@
impl State {
// Only panics in case of [`ImportResolver`] contract violation
#[allow(clippy::missing_panics_doc)]
- pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
- self.import_resolver().resolve_from(from, path.as_ref())
+ pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
+ self.import_resolver().resolve_from(from, path)
}
-
- // Only panics in case of [`ImportResolver`] contract violation
#[allow(clippy::missing_panics_doc)]
- pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {
- self.import_resolver().resolve(path.as_ref())
+ pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {
+ self.import_resolver().resolve_from_default(path)
}
pub fn import_resolver(&self) -> &dyn ImportResolver {
&*self.0.import_resolver
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -12,7 +12,7 @@
pub use encoding::*;
pub use hash::*;
use jrsonnet_evaluator::{
- error::{ErrorKind::*, Result},
+ error::Result,
function::{CallLocation, FuncVal, TlaArg},
trace::PathResolver,
val::NumValue,
@@ -377,23 +377,11 @@
.ext_vars
.insert(name, TlaArg::String(value));
}
- pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {
- let code = code.into();
- let source = extvar_source(name, code.clone());
- let parsed = jrsonnet_parser::parse(
- &code,
- &jrsonnet_parser::ParserSettings {
- source: source.clone(),
- },
- )
- .map_err(|e| ImportSyntaxError {
- path: source,
- error: Box::new(e),
- })?;
+ pub fn add_ext_code(&self, name: &str, code: impl AsRef<str>) -> Result<()> {
// self.data_mut().volatile_files.insert(source_name, code);
self.settings_mut()
.ext_vars
- .insert(name.into(), TlaArg::Code(parsed));
+ .insert(name.into(), TlaArg::InlineCode(code.as_ref().to_owned()));
Ok(())
}
pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {