difftreelog
doc: review issues
in: master
19 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -93,7 +93,7 @@
/// # Safety
///
-/// Caller should pass correct callback function
+/// It should be safe to call `cb` using valid values with passed `ctx`
#[no_mangle]
pub unsafe extern "C" fn jsonnet_import_callback(
vm: &State,
@@ -109,10 +109,10 @@
/// # Safety
///
-/// Caller should pass correct path: it should contain correct utf-8, and be \0-terminated
+/// `path` should be a NUL-terminated string
#[no_mangle]
-pub unsafe extern "C" fn jsonnet_jpath_add(vm: &State, v: *const c_char) {
- let cstr = CStr::from_ptr(v);
+pub unsafe extern "C" fn jsonnet_jpath_add(vm: &State, path: *const c_char) {
+ let cstr = CStr::from_ptr(path);
let path = PathBuf::from(cstr.to_str().unwrap());
let any_resolver = vm.import_resolver();
let resolver = any_resolver
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -41,17 +41,10 @@
let str = OsStr::from_bytes(input.to_bytes());
Cow::Borrowed(Path::new(str))
}
- #[cfg(target_family = "windows")]
+ #[cfg(not(target_family = "unix"))]
{
- use std::os::windows::ffi::OsStringExt;
- let str = input.to_str().expect("input is not utf8");
- let wide = str.encode_utf16().collect::<Vec<_>>();
- let wide = OsString::from_wide(&wide);
- Cow::Owned(PathBuf::new(wide))
- }
- #[cfg(not(any(target_family = "unix", target_family = "windows")))]
- {
- compile_error!("unsupported os")
+ let string = input.to_str().expect("bad utf-8");
+ Cow::Borrowed(string.as_ref())
}
}
@@ -62,9 +55,11 @@
let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");
Cow::Owned(str)
}
- #[cfg(not(any(target_family = "unix", target_family = "windows")))]
+ #[cfg(not(target_family = "unix"))]
{
- compile_error!("unsupported os")
+ 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)
}
}
@@ -169,7 +164,7 @@
///
/// # Safety
///
-/// `filename` should be a \0-terminated string
+/// `filename` should be a NUL-terminated string
#[no_mangle]
pub unsafe extern "C" fn jsonnet_evaluate_file(
vm: &State,
@@ -200,7 +195,7 @@
///
/// # Safety
///
-/// `filename`, `snippet` should be a \0-terminated strings
+/// `filename`, `snippet` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_evaluate_snippet(
vm: &State,
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -65,9 +65,9 @@
/// # Safety
///
/// `vm` should be a vm allocated by `jsonnet_make`
-/// `cb` should be a correct function pointer
-/// `raw_params` should point to a NULL-terminated string array
-/// `name`, `raw_params` elements should be a \0-terminated strings
+/// `name` should be a NUL-terminated string
+/// `cb` should be a function pointer
+/// `raw_params` should point to a NULL-terminated array of NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_native_callback(
vm: &State,
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -12,7 +12,7 @@
///
/// # Safety
///
-/// `v` should be a \0-terminated string
+/// `v` should be a NUL-terminated string
#[no_mangle]
pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &State, val: *const c_char) -> *mut Val {
let val = CStr::from_ptr(val);
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -11,8 +11,8 @@
///
/// # Safety
///
-/// `arr` should be correct pointer to array value allocated by make_array, or returned by other library call
-/// `val` should be correct pointer to value allocated using this library
+/// `arr` should be a pointer to array value allocated by make_array, or returned by other library call
+/// `val` should be a pointer to value allocated using this library
#[no_mangle]
pub unsafe extern "C" fn jsonnet_json_array_append(_vm: &State, arr: &mut Val, val: &Val) {
match arr {
@@ -35,8 +35,8 @@
///
/// # Safety
///
-/// `obj` should be a valid pointer to object value allocated by `make_object`, or returned by other library call
-/// `name` should be \0-terminated string
+/// `obj` should be a pointer to object value allocated by `make_object`, or returned by other library call
+/// `name` should be NUL-terminated string
#[no_mangle]
pub unsafe extern "C" fn jsonnet_json_object_append(
_vm: &State,
bindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -4,13 +4,13 @@
use jrsonnet_evaluator::State;
-/// Bind a Jsonnet external var to the given string.
+/// Binds a Jsonnet external variable to the given string.
///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
///
/// # Safety
///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_ext_var(vm: &State, name: *const c_char, value: *const c_char) {
let name = CStr::from_ptr(name);
@@ -27,13 +27,13 @@
)
}
-/// Bind a Jsonnet external var to the given code.
+/// Binds a Jsonnet external variable to the given code.
///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
///
/// # Safety
///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_ext_code(vm: &State, name: *const c_char, code: *const c_char) {
let name = CStr::from_ptr(name);
@@ -51,13 +51,13 @@
.expect("can't parse ext code")
}
-/// Bind a string top-level argument for a top-level parameter.
+/// Binds a top-level string argument for a top-level parameter.
///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
///
/// # Safety
///
-/// Caller should pass correct pointers as `name` and `value`, they need to be \0-terminated strings
+/// `name`, `value` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_tla_var(vm: &State, name: *const c_char, value: *const c_char) {
let name = CStr::from_ptr(name);
@@ -68,13 +68,13 @@
)
}
-/// Bind a code top-level argument for a top-level parameter.
+/// Binds a top-level code argument for a top-level parameter.
///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
///
/// # Safety
///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_tla_code(vm: &State, name: *const c_char, code: *const c_char) {
let name = CStr::from_ptr(name);
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -20,6 +20,9 @@
}
}
+/// Context keeps information about current lexical code location
+///
+/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
#[derive(Debug, Clone, Trace)]
pub struct Context(Cc<ContextInternals>);
impl Context {
@@ -160,8 +163,11 @@
extend: Some(parent),
}
}
+ /// # Panics
+ /// If `name` is already bound
pub fn bind(&mut self, name: IStr, value: Thunk<Val>) -> &mut Self {
- self.bindings.insert(name, value);
+ let old = self.bindings.insert(name, value);
+ assert!(old.is_none(), "variable bound twice in single context call");
self
}
pub fn build(self) -> Context {
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -67,7 +67,10 @@
type FunctionSignature = Vec<(Option<IStr>, bool)>;
+/// Possible errors
+#[allow(missing_docs)]
#[derive(Error, Debug, Clone, Trace)]
+#[non_exhaustive]
pub enum Error {
#[error("intrinsic not found: {0}")]
IntrinsicNotFound(IStr),
@@ -217,9 +220,13 @@
}
}
+/// Single stack trace frame
#[derive(Clone, Debug, Trace)]
pub struct StackTraceElement {
+ /// Source of this frame
+ /// Some frames only act as description, without attached source
pub location: Option<ExprLocation>,
+ /// Frame description
pub desc: String,
}
#[derive(Debug, Clone, Trace)]
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -269,9 +269,7 @@
}
}
let this = builder.build();
- let _ctx = ctx
- .extend(GcHashMap::new(), None, None, Some(this.clone()))
- .into_future(fctx);
+ fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));
Ok(this)
}
@@ -356,7 +354,7 @@
ctx: Context,
value: &LocExpr,
args: &ArgsDesc,
- loc: CallLocation,
+ loc: CallLocation<'_>,
tailstrict: bool,
) -> Result<Val> {
let value = evaluate(s.clone(), ctx.clone(), value)?;
@@ -602,7 +600,7 @@
}
Slice(value, desc) => {
fn parse_idx<T: Typed>(
- loc: CallLocation,
+ loc: CallLocation<'_>,
s: State,
ctx: &Context,
expr: &Option<LocExpr>,
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -24,7 +24,13 @@
/// Parameter names for named calls
fn params(&self) -> &[BuiltinParam];
/// Call the builtin
- fn call(&self, s: State, ctx: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val>;
+ fn call(
+ &self,
+ s: State,
+ ctx: Context,
+ loc: CallLocation<'_>,
+ args: &dyn ArgsLike,
+ ) -> Result<Val>;
}
pub trait StaticBuiltin: Builtin + Send + Sync
@@ -70,7 +76,13 @@
&self.params
}
- fn call(&self, s: State, ctx: Context, _loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
+ fn call(
+ &self,
+ s: State,
+ ctx: Context,
+ _loc: CallLocation<'_>,
+ args: &dyn ArgsLike,
+ ) -> Result<Val> {
let args = parse_builtin_call(s.clone(), ctx, &self.params, args, true)?;
let args = args
.into_iter()
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -18,43 +18,50 @@
pub mod native;
pub mod parse;
+/// Function callsite location.
+/// Either from other jsonnet code, specified by expression location, or from native (without location).
#[derive(Clone, Copy)]
pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
impl<'l> CallLocation<'l> {
+ /// Construct new location for calls coming from specified jsonnet expression location.
pub const fn new(loc: &'l ExprLocation) -> Self {
Self(Some(loc))
}
}
impl CallLocation<'static> {
+ /// Construct new location for calls coming from native code.
pub const fn native() -> Self {
Self(None)
}
}
-/// Function implemented in jsonnet
+/// Represents Jsonnet function defined in code.
#[derive(Debug, PartialEq, Trace)]
pub struct FuncDesc {
- /// In expressions like
+ /// # Example
+ ///
+ /// In expressions like this, deducted to `a`, unspecified otherwise.
/// ```jsonnet
/// local a = function() ...
/// local a() ...
/// { a: function() ... }
/// { a() = ... }
/// ```
- ///
- /// Deducted to `a`, unspecified otherwise
pub name: IStr,
- /// Context, in which this function was evaluated
+ /// Context, in which this function was evaluated.
///
- /// I.e in
+ /// # Example
+ /// In
/// ```jsonnet
/// local a = 2;
/// function() ...
/// ```
- /// context will contain `a`
+ /// context will contain `a`.
pub ctx: Context,
+ /// Function parameter definition
pub params: ParamsDesc,
+ /// Function body
pub body: LocExpr,
}
impl FuncDesc {
@@ -82,17 +89,17 @@
}
}
-/// Any possible function value, including plain functions and user-provided builtins
+/// Represents a Jsonnet function value, including plain functions and user-provided builtins.
#[allow(clippy::module_name_repetitions)]
#[derive(Trace, Clone)]
pub enum FuncVal {
- /// std.id
+ /// Identity function, kept this way for comparsions.
Id,
- /// Plain function implemented in jsonnet
+ /// Plain function implemented in jsonnet.
Normal(Cc<FuncDesc>),
- /// Standard library function
+ /// Standard library function.
StaticBuiltin(#[trace(skip)] &'static dyn StaticBuiltin),
- /// User-provided function
+ /// User-provided function.
Builtin(Cc<TraceBox<dyn Builtin>>),
}
@@ -110,9 +117,7 @@
}
impl FuncVal {
- pub fn into_native<D: NativeDesc>(self) -> D::Value {
- D::into_native(self)
- }
+ /// Amount of non-default required arguments
pub fn params_len(&self) -> usize {
match self {
Self::Id => 1,
@@ -121,6 +126,7 @@
Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),
}
}
+ /// Function name, as defined in code.
pub fn name(&self) -> IStr {
match self {
Self::Id => "id".into(),
@@ -129,11 +135,14 @@
Self::Builtin(builtin) => builtin.name().into(),
}
}
+ /// Call function using arguments evaluated in specified `call_ctx` [`Context`].
+ ///
+ /// If `tailstrict` is specified - then arguments will be evaluated before being passed to function body.
pub fn evaluate(
&self,
s: State,
call_ctx: Context,
- loc: CallLocation,
+ loc: CallLocation<'_>,
args: &dyn ArgsLike,
tailstrict: bool,
) -> Result<Val> {
@@ -156,13 +165,22 @@
Self::Builtin(b) => b.call(s, call_ctx, loc, args),
}
}
+ /// Helper method, which calls [`Self::evaluate`] with sensible defaults for native code.
pub fn evaluate_simple(&self, s: State, args: &dyn ArgsLike) -> Result<Val> {
self.evaluate(s, Context::default(), CallLocation::native(), args, true)
}
+ /// Convert jsonnet function to plain `Fn` value.
+ pub fn into_native<D: NativeDesc>(self) -> D::Value {
+ D::into_native(self)
+ }
+ /// Is this function an indentity function.
+ ///
+ /// Currently only works for builtin `std.id`, aka `Self::Id` value, `function(x) x` defined by jsonnet will not count as identity.
pub const fn is_identity(&self) -> bool {
matches!(self, Self::Id)
}
+ /// Identity function value.
pub const fn identity() -> Self {
Self::Id
}
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -22,7 +22,7 @@
}
impl<T: ?Sized + Trace> Trace for TraceBox<T> {
- fn trace(&self, tracer: &mut Tracer) {
+ fn trace(&self, tracer: &mut Tracer<'_>) {
self.0.trace(tracer);
}
@@ -92,7 +92,7 @@
where
V: Trace,
{
- fn trace(&self, tracer: &mut jrsonnet_gcmodule::Tracer) {
+ fn trace(&self, tracer: &mut Tracer<'_>) {
for v in &self.0 {
v.trace(tracer);
}
@@ -133,7 +133,7 @@
K: Trace,
V: Trace,
{
- fn trace(&self, tracer: &mut jrsonnet_gcmodule::Tracer) {
+ fn trace(&self, tracer: &mut Tracer<'_>) {
for (k, v) in &self.0 {
k.trace(tracer);
v.trace(tracer);
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,4 +1,18 @@
-#![warn(clippy::all, clippy::nursery, clippy::pedantic)]
+//! jsonnet interpreter implementation
+
+#![deny(unsafe_op_in_unsafe_fn)]
+#![warn(
+ clippy::all,
+ clippy::nursery,
+ clippy::pedantic,
+ // missing_docs,
+ elided_lifetimes_in_paths,
+ explicit_outlives_requirements,
+ noop_method_call,
+ single_use_lifetimes,
+ variant_size_differences,
+ rustdoc::all
+)]
#![allow(
macro_expanded_macro_exports_accessed_by_absolute_paths,
clippy::ptr_arg,
@@ -67,23 +81,32 @@
use trace::{CompactFormat, TraceFormat};
pub use val::{ManifestFormat, Thunk, Val};
+/// Thunk without bound `super`/`this`
+/// object inheritance may be overriden multiple times, and will be fixed only on field read
pub trait Unbound: Trace {
+ /// Type of value after object context is bound
type Bound;
+ /// Create value bound to specified object context
fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
}
+/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code
+/// Standard jsonnet fields are always unbound
#[derive(Clone, Trace)]
-pub enum LazyBinding {
- Bindable(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
+pub enum MaybeUnbound {
+ /// Value needs to be bound to `this`/`super`
+ Unbound(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
+ /// Value is object-independent
Bound(Thunk<Val>),
}
-impl Debug for LazyBinding {
+impl Debug for MaybeUnbound {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "LazyBinding")
+ write!(f, "MaybeUnbound")
}
}
-impl LazyBinding {
+impl MaybeUnbound {
+ /// Attach object context to value, if required
pub fn evaluate(
&self,
s: State,
@@ -91,17 +114,19 @@
this: Option<ObjValue>,
) -> Result<Thunk<Val>> {
match self {
- Self::Bindable(v) => v.bind(s, sup, this),
+ Self::Unbound(v) => v.bind(s, sup, this),
Self::Bound(v) => Ok(v.clone()),
}
}
}
-/// During import, this trait will be called to create initial context for file
-/// It may initialize global variables, stdlib for example
+/// During import, this trait will be called to create initial context for file.
+/// It may initialize global variables, stdlib for example.
pub trait ContextInitializer {
+ /// Initialize default file context.
fn initialize(&self, state: State, for_file: Source) -> Context;
-
+ /// Allows upcasting from abstract to concrete context initializer.
+ /// jrsonnet by itself doesn't use this method, it is allowed for it to panic.
fn as_any(&self) -> &dyn Any;
}
@@ -116,6 +141,7 @@
}
}
+/// Dynamically reconfigurable evaluation settings
pub struct EvaluationSettings {
/// Limits recursion by limiting the number of stack frames
pub max_stack: usize,
@@ -401,7 +427,7 @@
/// Executes code creating a new stack frame
pub fn push<T>(
&self,
- e: CallLocation,
+ e: CallLocation<'_>,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
@@ -547,16 +573,13 @@
/// Internals
impl State {
- // fn data(&self) -> Ref<EvaluationData> {
- // self.0.data.borrow()
- // }
- fn data_mut(&self) -> RefMut<EvaluationData> {
+ fn data_mut(&self) -> RefMut<'_, EvaluationData> {
self.0.data.borrow_mut()
}
- pub fn settings(&self) -> Ref<EvaluationSettings> {
+ pub fn settings(&self) -> Ref<'_, EvaluationSettings> {
self.0.settings.borrow()
}
- pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {
+ pub fn settings_mut(&self) -> RefMut<'_, EvaluationSettings> {
self.0.settings.borrow_mut()
}
}
@@ -623,13 +646,13 @@
pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {
self.import_resolver().resolve(path.as_ref())
}
- pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {
+ pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {
Ref::map(self.settings(), |s| &*s.import_resolver)
}
pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {
self.settings_mut().import_resolver = resolver;
}
- pub fn context_initializer(&self) -> Ref<dyn ContextInitializer> {
+ pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {
Ref::map(self.settings(), |s| &*s.context_initializer)
}
@@ -640,7 +663,7 @@
self.settings_mut().manifest_format = format;
}
- pub fn trace_format(&self) -> Ref<dyn TraceFormat> {
+ pub fn trace_format(&self) -> Ref<'_, dyn TraceFormat> {
Ref::map(self.settings(), |s| &*s.trace_format)
}
pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -15,7 +15,7 @@
function::CallLocation,
gc::{GcHashMap, GcHashSet, TraceBox},
operator::evaluate_add_op,
- throw, LazyBinding, Result, State, Thunk, Unbound, Val,
+ throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,
};
#[cfg(not(feature = "exp-preserve-order"))]
@@ -100,7 +100,7 @@
pub add: bool,
pub visibility: Visibility,
original_index: FieldIndex,
- pub invoke: LazyBinding,
+ pub invoke: MaybeUnbound,
pub location: Option<ExprLocation>,
}
@@ -208,7 +208,7 @@
new.insert(key, value);
Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))
}
- pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {
+ pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {
ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
}
@@ -239,6 +239,8 @@
}
/// Run callback for every field found in object
+ ///
+ /// Returns true if ended prematurely
pub(crate) fn enum_fields(
&self,
depth: SuperDepth,
@@ -500,7 +502,7 @@
self.assertions.push(assertion);
self
}
- pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {
+ pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {
let field_index = self.next_field_index;
self.next_field_index = self.next_field_index.next();
ObjMemberBuilder::new(ValueBuilder(self), name, field_index)
@@ -558,7 +560,7 @@
self.location = Some(location);
self
}
- fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {
+ fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {
(
self.kind,
self.name,
@@ -574,18 +576,18 @@
}
pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
-impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {
+impl ObjMemberBuilder<ValueBuilder<'_>> {
pub fn value(self, s: State, value: Val) -> Result<()> {
- self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))
+ self.binding(s, MaybeUnbound::Bound(Thunk::evaluated(value)))
}
pub fn bindable(
self,
s: State,
bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,
) -> Result<()> {
- self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))
+ self.binding(s, MaybeUnbound::Unbound(Cc::new(bindable)))
}
- pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {
+ pub fn binding(self, s: State, binding: MaybeUnbound) -> Result<()> {
let (receiver, name, member) = self.build_member(binding);
let location = member.location.clone();
let old = receiver.0.map.insert(name.clone(), member);
@@ -601,14 +603,14 @@
}
pub struct ExtendBuilder<'v>(&'v mut ObjValue);
-impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {
+impl ObjMemberBuilder<ExtendBuilder<'_>> {
pub fn value(self, value: Val) {
- self.binding(LazyBinding::Bound(Thunk::evaluated(value)));
+ self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));
}
pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {
- self.binding(LazyBinding::Bindable(Cc::new(bindable)));
+ self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));
}
- pub fn binding(self, binding: LazyBinding) {
+ pub fn binding(self, binding: MaybeUnbound) {
let (receiver, name, member) = self.build_member(binding);
let new = receiver.0.clone();
*receiver.0 = new.extend_with_raw_member(name, member);
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use jrsonnet_gcmodule::Trace;5use jrsonnet_interner::IStr;6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{error::Error::*, throw, typed::Typed, LocError, ObjValue, Result, State, Val};1011#[derive(Debug, Clone, Error, Trace)]12pub enum FormatError {13 #[error("truncated format code")]14 TruncatedFormatCode,15 #[error("unrecognized conversion type: {0}")]16 UnrecognizedConversionType(char),1718 #[error("not enough values")]19 NotEnoughValues,2021 #[error("cannot use * width with object")]22 CannotUseStarWidthWithObject,23 #[error("mapping keys required")]24 MappingKeysRequired,25 #[error("no such format field: {0}")]26 NoSuchFormatField(IStr),27}2829impl From<FormatError> for LocError {30 fn from(e: FormatError) -> Self {31 Self::new(Format(e))32 }33}3435use FormatError::*;3637type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;3839pub fn try_parse_mapping_key(str: &str) -> ParseResult<&str> {40 if str.is_empty() {41 return Err(TruncatedFormatCode);42 }43 let bytes = str.as_bytes();44 if bytes[0] == b'(' {45 let mut i = 1;46 while i < bytes.len() {47 if bytes[i] == b')' {48 return Ok((&str[1..i], &str[i + 1..]));49 }50 i += 1;51 }52 Err(TruncatedFormatCode)53 } else {54 Ok(("", str))55 }56}5758#[cfg(test)]59pub mod tests_key {60 use super::*;6162 #[test]63 fn parse_key() {64 assert_eq!(65 try_parse_mapping_key("(hello ) world").unwrap(),66 ("hello ", " world")67 );68 assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));69 assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));70 assert_eq!(71 try_parse_mapping_key(" () world").unwrap(),72 ("", " () world")73 );74 }7576 #[test]77 #[should_panic]78 fn parse_key_missing_start() {79 try_parse_mapping_key("").unwrap();80 }8182 #[test]83 #[should_panic]84 fn parse_key_missing_end() {85 try_parse_mapping_key("( ").unwrap();86 }87}8889#[allow(clippy::struct_excessive_bools)]90#[derive(Default, Debug)]91pub struct CFlags {92 pub alt: bool,93 pub zero: bool,94 pub left: bool,95 pub blank: bool,96 pub sign: bool,97}9899pub fn try_parse_cflags(str: &str) -> ParseResult<CFlags> {100 if str.is_empty() {101 return Err(TruncatedFormatCode);102 }103 let bytes = str.as_bytes();104 let mut i = 0;105 let mut out = CFlags::default();106 loop {107 if bytes.len() == i {108 return Err(TruncatedFormatCode);109 }110 match bytes[i] {111 b'#' => out.alt = true,112 b'0' => out.zero = true,113 b'-' => out.left = true,114 b' ' => out.blank = true,115 b'+' => out.sign = true,116 _ => break,117 }118 i += 1;119 }120 Ok((out, &str[i..]))121}122123#[derive(Debug, PartialEq, Eq)]124pub enum Width {125 Star,126 Fixed(usize),127}128pub fn try_parse_field_width(str: &str) -> ParseResult<Width> {129 if str.is_empty() {130 return Err(TruncatedFormatCode);131 }132 let bytes = str.as_bytes();133 if bytes[0] == b'*' {134 return Ok((Width::Star, &str[1..]));135 }136 let mut out: usize = 0;137 let mut digits = 0;138 while let Some(digit) = (bytes[digits] as char).to_digit(10) {139 out *= 10;140 out += digit as usize;141 digits += 1;142 if digits == bytes.len() {143 return Err(TruncatedFormatCode);144 }145 }146 Ok((Width::Fixed(out), &str[digits..]))147}148149pub fn try_parse_precision(str: &str) -> ParseResult<Option<Width>> {150 if str.is_empty() {151 return Err(TruncatedFormatCode);152 }153 let bytes = str.as_bytes();154 if bytes[0] == b'.' {155 try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))156 } else {157 Ok((None, str))158 }159}160161// Only skips162pub fn try_parse_length_modifier(str: &str) -> ParseResult<()> {163 if str.is_empty() {164 return Err(TruncatedFormatCode);165 }166 let bytes = str.as_bytes();167 let mut idx = 0;168 while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {169 idx += 1;170 if bytes.len() == idx {171 return Err(TruncatedFormatCode);172 }173 }174 Ok(((), &str[idx..]))175}176177#[derive(Debug, PartialEq, Eq)]178pub enum ConvTypeV {179 Decimal,180 Octal,181 Hexadecimal,182 Scientific,183 Float,184 Shorter,185 Char,186 String,187 Percent,188}189pub struct ConvType {190 v: ConvTypeV,191 caps: bool,192}193194pub fn parse_conversion_type(str: &str) -> ParseResult<ConvType> {195 if str.is_empty() {196 return Err(TruncatedFormatCode);197 }198199 let code = str.as_bytes()[0];200 let v: (ConvTypeV, bool) = match code {201 b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),202 b'o' => (ConvTypeV::Octal, false),203 b'x' => (ConvTypeV::Hexadecimal, false),204 b'X' => (ConvTypeV::Hexadecimal, true),205 b'e' => (ConvTypeV::Scientific, false),206 b'E' => (ConvTypeV::Scientific, true),207 b'f' => (ConvTypeV::Float, false),208 b'F' => (ConvTypeV::Float, true),209 b'g' => (ConvTypeV::Shorter, false),210 b'G' => (ConvTypeV::Shorter, true),211 b'c' => (ConvTypeV::Char, false),212 b's' => (ConvTypeV::String, false),213 b'%' => (ConvTypeV::Percent, false),214 c => return Err(UnrecognizedConversionType(c as char)),215 };216217 Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))218}219220#[derive(Debug)]221pub struct Code<'s> {222 mkey: &'s str,223 cflags: CFlags,224 width: Width,225 precision: Option<Width>,226 convtype: ConvTypeV,227 caps: bool,228}229pub fn parse_code(str: &str) -> ParseResult<Code> {230 if str.is_empty() {231 return Err(TruncatedFormatCode);232 }233 let (mkey, str) = try_parse_mapping_key(str)?;234 let (cflags, str) = try_parse_cflags(str)?;235 let (width, str) = try_parse_field_width(str)?;236 let (precision, str) = try_parse_precision(str)?;237 let (_, str) = try_parse_length_modifier(str)?;238 let (convtype, str) = parse_conversion_type(str)?;239240 Ok((241 Code {242 mkey,243 cflags,244 width,245 precision,246 convtype: convtype.v,247 caps: convtype.caps,248 },249 str,250 ))251}252253#[derive(Debug)]254pub enum Element<'s> {255 String(&'s str),256 Code(Code<'s>),257}258pub fn parse_codes(mut str: &str) -> Result<Vec<Element>> {259 let mut bytes = str.as_bytes();260 let mut out = vec![];261 let mut offset = 0;262263 loop {264 while offset != bytes.len() && bytes[offset] != b'%' {265 offset += 1;266 }267 if offset != 0 {268 out.push(Element::String(&str[0..offset]));269 }270 if offset == bytes.len() {271 return Ok(out);272 }273 str = &str[offset + 1..];274 let code;275 (code, str) = parse_code(str)?;276 bytes = str.as_bytes();277 offset = 0;278279 out.push(Element::Code(code));280 }281}282283const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";284285#[inline]286pub fn render_integer(287 out: &mut String,288 iv: f64,289 padding: usize,290 precision: usize,291 blank: bool,292 sign: bool,293 radix: i64,294 prefix: &str,295 caps: bool,296) {297 let radix = radix as f64;298 let iv = iv.floor();299 // Digit char indexes in reverse order, i.e300 // for radix = 16 and n = 12f: [15, 2, 1]301 let digits = if iv == 0.0 {302 vec![0u8]303 } else {304 let mut v = iv.abs();305 let mut nums = Vec::with_capacity(1);306 while v != 0.0 {307 nums.push((v % radix) as u8);308 v = (v / radix).floor();309 }310 nums311 };312 let neg = iv < 0.0;313 #[allow(clippy::bool_to_int_with_if)]314 let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });315 let zp2 = zp316 .max(precision)317 .saturating_sub(prefix.len() + digits.len());318319 if neg {320 out.push('-');321 } else if sign {322 out.push('+');323 } else if blank {324 out.push(' ');325 }326327 out.reserve(zp2);328 for _ in 0..zp2 {329 out.push('0');330 }331 out.push_str(prefix);332333 for digit in digits.into_iter().rev() {334 let ch = NUMBERS[digit as usize] as char;335 out.push(if caps { ch.to_ascii_uppercase() } else { ch });336 }337}338339pub fn render_decimal(340 out: &mut String,341 iv: f64,342 padding: usize,343 precision: usize,344 blank: bool,345 sign: bool,346) {347 render_integer(out, iv, padding, precision, blank, sign, 10, "", false);348}349pub fn render_octal(350 out: &mut String,351 iv: f64,352 padding: usize,353 precision: usize,354 alt: bool,355 blank: bool,356 sign: bool,357) {358 render_integer(359 out,360 iv,361 padding,362 precision,363 blank,364 sign,365 8,366 if alt && iv != 0.0 { "0" } else { "" },367 false,368 );369}370371#[allow(clippy::fn_params_excessive_bools)]372pub fn render_hexadecimal(373 out: &mut String,374 iv: f64,375 padding: usize,376 precision: usize,377 alt: bool,378 blank: bool,379 sign: bool,380 caps: bool,381) {382 render_integer(383 out,384 iv,385 padding,386 precision,387 blank,388 sign,389 16,390 match (alt, caps) {391 (true, true) => "0X",392 (true, false) => "0x",393 (false, _) => "",394 },395 caps,396 );397}398399#[allow(clippy::fn_params_excessive_bools)]400pub fn render_float(401 out: &mut String,402 n: f64,403 mut padding: usize,404 precision: usize,405 blank: bool,406 sign: bool,407 ensure_pt: bool,408 trailing: bool,409) {410 #[allow(clippy::bool_to_int_with_if)]411 let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };412 padding = padding.saturating_sub(dot_size + precision);413 render_decimal(out, n.floor(), padding, 0, blank, sign);414 if precision == 0 {415 if ensure_pt {416 out.push('.');417 }418 return;419 }420 let frac = n421 .fract()422 .mul_add(10.0_f64.powf(precision as f64), 0.5)423 .floor();424 if trailing || frac > 0.0 {425 out.push('.');426 let mut frac_str = String::new();427 render_decimal(&mut frac_str, frac, precision, 0, false, false);428 let mut trim = frac_str.len();429 if !trailing {430 for b in frac_str.as_bytes().iter().rev() {431 if *b == b'0' {432 trim -= 1;433 }434 }435 }436 out.push_str(&frac_str[..trim]);437 } else if ensure_pt {438 out.push('.');439 }440}441442#[allow(clippy::fn_params_excessive_bools)]443pub fn render_float_sci(444 out: &mut String,445 n: f64,446 mut padding: usize,447 precision: usize,448 blank: bool,449 sign: bool,450 ensure_pt: bool,451 trailing: bool,452 caps: bool,453) {454 let exponent = n.log10().floor();455 let mantissa = if exponent as i16 == -324 {456 n * 10.0 / 10.0_f64.powf(exponent + 1.0)457 } else {458 n / 10.0_f64.powf(exponent)459 };460 let mut exponent_str = String::new();461 render_decimal(&mut exponent_str, exponent, 3, 0, false, true);462463 // +1 for e464 padding = padding.saturating_sub(exponent_str.len() + 1);465466 render_float(467 out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,468 );469 out.push(if caps { 'E' } else { 'e' });470 out.push_str(&exponent_str);471}472473#[allow(clippy::too_many_lines)]474pub fn format_code(475 s: State,476 out: &mut String,477 value: &Val,478 code: &Code,479 width: usize,480 precision: Option<usize>,481) -> Result<()> {482 let clfags = &code.cflags;483 let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));484 let padding = if clfags.zero && !clfags.left {485 width486 } else {487 0488 };489490 // TODO: If left padded, can optimize by writing directly to out491 let mut tmp_out = String::new();492493 match code.convtype {494 ConvTypeV::String => tmp_out.push_str(&value.clone().to_string(s)?),495 ConvTypeV::Decimal => {496 let value = f64::from_untyped(value.clone(), s)?;497 render_decimal(498 &mut tmp_out,499 value,500 padding,501 iprec,502 clfags.blank,503 clfags.sign,504 );505 }506 ConvTypeV::Octal => {507 let value = f64::from_untyped(value.clone(), s)?;508 render_octal(509 &mut tmp_out,510 value,511 padding,512 iprec,513 clfags.alt,514 clfags.blank,515 clfags.sign,516 );517 }518 ConvTypeV::Hexadecimal => {519 let value = f64::from_untyped(value.clone(), s)?;520 render_hexadecimal(521 &mut tmp_out,522 value,523 padding,524 iprec,525 clfags.alt,526 clfags.blank,527 clfags.sign,528 code.caps,529 );530 }531 ConvTypeV::Scientific => {532 let value = f64::from_untyped(value.clone(), s)?;533 render_float_sci(534 &mut tmp_out,535 value,536 padding,537 fpprec,538 clfags.blank,539 clfags.sign,540 clfags.alt,541 true,542 code.caps,543 );544 }545 ConvTypeV::Float => {546 let value = f64::from_untyped(value.clone(), s)?;547 render_float(548 &mut tmp_out,549 value,550 padding,551 fpprec,552 clfags.blank,553 clfags.sign,554 clfags.alt,555 true,556 );557 }558 ConvTypeV::Shorter => {559 let value = f64::from_untyped(value.clone(), s)?;560 let exponent = value.log10().floor();561 if exponent < -4.0 || exponent >= fpprec as f64 {562 render_float_sci(563 &mut tmp_out,564 value,565 padding,566 fpprec - 1,567 clfags.blank,568 clfags.sign,569 clfags.alt,570 clfags.alt,571 code.caps,572 );573 } else {574 let digits_before_pt = 1.max(exponent as usize + 1);575 render_float(576 &mut tmp_out,577 value,578 padding,579 fpprec - digits_before_pt,580 clfags.blank,581 clfags.sign,582 clfags.alt,583 clfags.alt,584 );585 }586 }587 ConvTypeV::Char => match value.clone() {588 Val::Num(n) => tmp_out.push(589 std::char::from_u32(n as u32)590 .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,591 ),592 Val::Str(s) => {593 if s.chars().count() != 1 {594 throw!(RuntimeError(595 format!("%c expected 1 char string, got {}", s.chars().count()).into(),596 ));597 }598 tmp_out.push_str(&s);599 }600 _ => {601 throw!(TypeMismatch(602 "%c requires number/string",603 vec![ValType::Num, ValType::Str],604 value.value_type(),605 ));606 }607 },608 ConvTypeV::Percent => tmp_out.push('%'),609 };610611 let padding = width.saturating_sub(tmp_out.len());612613 if !clfags.left {614 for _ in 0..padding {615 out.push(' ');616 }617 }618 out.push_str(&tmp_out);619 if clfags.left {620 for _ in 0..padding {621 out.push(' ');622 }623 }624625 Ok(())626}627628pub fn format_arr(s: State, str: &str, mut values: &[Val]) -> Result<String> {629 let codes = parse_codes(str)?;630 let mut out = String::new();631632 for code in codes {633 match code {634 Element::String(s) => {635 out.push_str(s);636 }637 Element::Code(c) => {638 let width = match c.width {639 Width::Star => {640 if values.is_empty() {641 throw!(NotEnoughValues);642 }643 let value = &values[0];644 values = &values[1..];645 usize::from_untyped(value.clone(), s.clone())?646 }647 Width::Fixed(n) => n,648 };649 let precision = match c.precision {650 Some(Width::Star) => {651 if values.is_empty() {652 throw!(NotEnoughValues);653 }654 let value = &values[0];655 values = &values[1..];656 Some(usize::from_untyped(value.clone(), s.clone())?)657 }658 Some(Width::Fixed(n)) => Some(n),659 None => None,660 };661662 // %% should not consume a value663 let value = if c.convtype == ConvTypeV::Percent {664 &Val::Null665 } else {666 if values.is_empty() {667 throw!(NotEnoughValues);668 }669 let value = &values[0];670 values = &values[1..];671 value672 };673674 format_code(s.clone(), &mut out, value, &c, width, precision)?;675 }676 }677 }678679 Ok(out)680}681682pub fn format_obj(s: State, str: &str, values: &ObjValue) -> Result<String> {683 let codes = parse_codes(str)?;684 let mut out = String::new();685686 for code in codes {687 match code {688 Element::String(s) => {689 out.push_str(s);690 }691 Element::Code(c) => {692 // TODO: Operate on ref693 let f: IStr = c.mkey.into();694 let width = match c.width {695 Width::Star => {696 throw!(CannotUseStarWidthWithObject);697 }698 Width::Fixed(n) => n,699 };700 let precision = match c.precision {701 Some(Width::Star) => {702 throw!(CannotUseStarWidthWithObject);703 }704 Some(Width::Fixed(n)) => Some(n),705 None => None,706 };707708 let value = if c.convtype == ConvTypeV::Percent {709 Val::Null710 } else {711 if f.is_empty() {712 throw!(MappingKeysRequired);713 }714 if let Some(v) = values.get(s.clone(), f.clone())? {715 v716 } else {717 throw!(NoSuchFormatField(f));718 }719 };720721 format_code(s.clone(), &mut out, &value, &c, width, precision)?;722 }723 }724 }725726 Ok(out)727}728729#[cfg(test)]730pub mod test_format {731 use super::*;732733 #[test]734 fn parse() {735 assert_eq!(736 parse_codes(737 "How much error budget is left looking at our %.3f%% availability gurantees?"738 )739 .unwrap()740 .len(),741 4742 );743 }744745 #[test]746 fn octals() {747 let s = State::default();748 assert_eq!(749 format_arr(s.clone(), "%#o", &[Val::Num(8.0)]).unwrap(),750 "010"751 );752 assert_eq!(753 format_arr(s.clone(), "%#4o", &[Val::Num(8.0)]).unwrap(),754 " 010"755 );756 assert_eq!(757 format_arr(s.clone(), "%4o", &[Val::Num(8.0)]).unwrap(),758 " 10"759 );760 assert_eq!(761 format_arr(s.clone(), "%04o", &[Val::Num(8.0)]).unwrap(),762 "0010"763 );764 assert_eq!(765 format_arr(s.clone(), "%+4o", &[Val::Num(8.0)]).unwrap(),766 " +10"767 );768 assert_eq!(769 format_arr(s.clone(), "%+04o", &[Val::Num(8.0)]).unwrap(),770 "+010"771 );772 assert_eq!(773 format_arr(s.clone(), "%-4o", &[Val::Num(8.0)]).unwrap(),774 "10 "775 );776 assert_eq!(777 format_arr(s.clone(), "%+-4o", &[Val::Num(8.0)]).unwrap(),778 "+10 "779 );780 assert_eq!(format_arr(s, "%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");781 }782783 #[test]784 fn percent_doesnt_consumes_values() {785 let s = State::default();786 assert_eq!(787 format_arr(788 s,789 "How much error budget is left looking at our %.3f%% availability gurantees?",790 &[Val::Num(4.0)]791 )792 .unwrap(),793 "How much error budget is left looking at our 4.000% availability gurantees?"794 );795 }796}1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use jrsonnet_gcmodule::Trace;5use jrsonnet_interner::IStr;6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{error::Error::*, throw, typed::Typed, LocError, ObjValue, Result, State, Val};1011#[derive(Debug, Clone, Error, Trace)]12pub enum FormatError {13 #[error("truncated format code")]14 TruncatedFormatCode,15 #[error("unrecognized conversion type: {0}")]16 UnrecognizedConversionType(char),1718 #[error("not enough values")]19 NotEnoughValues,2021 #[error("cannot use * width with object")]22 CannotUseStarWidthWithObject,23 #[error("mapping keys required")]24 MappingKeysRequired,25 #[error("no such format field: {0}")]26 NoSuchFormatField(IStr),27}2829impl From<FormatError> for LocError {30 fn from(e: FormatError) -> Self {31 Self::new(Format(e))32 }33}3435use FormatError::*;3637type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;3839pub fn try_parse_mapping_key(str: &str) -> ParseResult<'_, &str> {40 if str.is_empty() {41 return Err(TruncatedFormatCode);42 }43 let bytes = str.as_bytes();44 if bytes[0] == b'(' {45 let mut i = 1;46 while i < bytes.len() {47 if bytes[i] == b')' {48 return Ok((&str[1..i], &str[i + 1..]));49 }50 i += 1;51 }52 Err(TruncatedFormatCode)53 } else {54 Ok(("", str))55 }56}5758#[cfg(test)]59pub mod tests_key {60 use super::*;6162 #[test]63 fn parse_key() {64 assert_eq!(65 try_parse_mapping_key("(hello ) world").unwrap(),66 ("hello ", " world")67 );68 assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));69 assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));70 assert_eq!(71 try_parse_mapping_key(" () world").unwrap(),72 ("", " () world")73 );74 }7576 #[test]77 #[should_panic]78 fn parse_key_missing_start() {79 try_parse_mapping_key("").unwrap();80 }8182 #[test]83 #[should_panic]84 fn parse_key_missing_end() {85 try_parse_mapping_key("( ").unwrap();86 }87}8889#[allow(clippy::struct_excessive_bools)]90#[derive(Default, Debug)]91pub struct CFlags {92 pub alt: bool,93 pub zero: bool,94 pub left: bool,95 pub blank: bool,96 pub sign: bool,97}9899pub fn try_parse_cflags(str: &str) -> ParseResult<'_, CFlags> {100 if str.is_empty() {101 return Err(TruncatedFormatCode);102 }103 let bytes = str.as_bytes();104 let mut i = 0;105 let mut out = CFlags::default();106 loop {107 if bytes.len() == i {108 return Err(TruncatedFormatCode);109 }110 match bytes[i] {111 b'#' => out.alt = true,112 b'0' => out.zero = true,113 b'-' => out.left = true,114 b' ' => out.blank = true,115 b'+' => out.sign = true,116 _ => break,117 }118 i += 1;119 }120 Ok((out, &str[i..]))121}122123#[derive(Debug, PartialEq, Eq)]124pub enum Width {125 Star,126 Fixed(usize),127}128pub fn try_parse_field_width(str: &str) -> ParseResult<'_, Width> {129 if str.is_empty() {130 return Err(TruncatedFormatCode);131 }132 let bytes = str.as_bytes();133 if bytes[0] == b'*' {134 return Ok((Width::Star, &str[1..]));135 }136 let mut out: usize = 0;137 let mut digits = 0;138 while let Some(digit) = (bytes[digits] as char).to_digit(10) {139 out *= 10;140 out += digit as usize;141 digits += 1;142 if digits == bytes.len() {143 return Err(TruncatedFormatCode);144 }145 }146 Ok((Width::Fixed(out), &str[digits..]))147}148149pub fn try_parse_precision(str: &str) -> ParseResult<'_, Option<Width>> {150 if str.is_empty() {151 return Err(TruncatedFormatCode);152 }153 let bytes = str.as_bytes();154 if bytes[0] == b'.' {155 try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))156 } else {157 Ok((None, str))158 }159}160161// Only skips162pub fn try_parse_length_modifier(str: &str) -> ParseResult<'_, ()> {163 if str.is_empty() {164 return Err(TruncatedFormatCode);165 }166 let bytes = str.as_bytes();167 let mut idx = 0;168 while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {169 idx += 1;170 if bytes.len() == idx {171 return Err(TruncatedFormatCode);172 }173 }174 Ok(((), &str[idx..]))175}176177#[derive(Debug, PartialEq, Eq)]178pub enum ConvTypeV {179 Decimal,180 Octal,181 Hexadecimal,182 Scientific,183 Float,184 Shorter,185 Char,186 String,187 Percent,188}189pub struct ConvType {190 v: ConvTypeV,191 caps: bool,192}193194pub fn parse_conversion_type(str: &str) -> ParseResult<'_, ConvType> {195 if str.is_empty() {196 return Err(TruncatedFormatCode);197 }198199 let code = str.as_bytes()[0];200 let v: (ConvTypeV, bool) = match code {201 b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),202 b'o' => (ConvTypeV::Octal, false),203 b'x' => (ConvTypeV::Hexadecimal, false),204 b'X' => (ConvTypeV::Hexadecimal, true),205 b'e' => (ConvTypeV::Scientific, false),206 b'E' => (ConvTypeV::Scientific, true),207 b'f' => (ConvTypeV::Float, false),208 b'F' => (ConvTypeV::Float, true),209 b'g' => (ConvTypeV::Shorter, false),210 b'G' => (ConvTypeV::Shorter, true),211 b'c' => (ConvTypeV::Char, false),212 b's' => (ConvTypeV::String, false),213 b'%' => (ConvTypeV::Percent, false),214 c => return Err(UnrecognizedConversionType(c as char)),215 };216217 Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))218}219220#[derive(Debug)]221pub struct Code<'s> {222 mkey: &'s str,223 cflags: CFlags,224 width: Width,225 precision: Option<Width>,226 convtype: ConvTypeV,227 caps: bool,228}229pub fn parse_code(str: &str) -> ParseResult<'_, Code<'_>> {230 if str.is_empty() {231 return Err(TruncatedFormatCode);232 }233 let (mkey, str) = try_parse_mapping_key(str)?;234 let (cflags, str) = try_parse_cflags(str)?;235 let (width, str) = try_parse_field_width(str)?;236 let (precision, str) = try_parse_precision(str)?;237 let (_, str) = try_parse_length_modifier(str)?;238 let (convtype, str) = parse_conversion_type(str)?;239240 Ok((241 Code {242 mkey,243 cflags,244 width,245 precision,246 convtype: convtype.v,247 caps: convtype.caps,248 },249 str,250 ))251}252253#[derive(Debug)]254pub enum Element<'s> {255 String(&'s str),256 Code(Code<'s>),257}258pub fn parse_codes(mut str: &str) -> Result<Vec<Element<'_>>> {259 let mut bytes = str.as_bytes();260 let mut out = vec![];261 let mut offset = 0;262263 loop {264 while offset != bytes.len() && bytes[offset] != b'%' {265 offset += 1;266 }267 if offset != 0 {268 out.push(Element::String(&str[0..offset]));269 }270 if offset == bytes.len() {271 return Ok(out);272 }273 str = &str[offset + 1..];274 let code;275 (code, str) = parse_code(str)?;276 bytes = str.as_bytes();277 offset = 0;278279 out.push(Element::Code(code));280 }281}282283const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";284285#[inline]286pub fn render_integer(287 out: &mut String,288 iv: f64,289 padding: usize,290 precision: usize,291 blank: bool,292 sign: bool,293 radix: i64,294 prefix: &str,295 caps: bool,296) {297 let radix = radix as f64;298 let iv = iv.floor();299 // Digit char indexes in reverse order, i.e300 // for radix = 16 and n = 12f: [15, 2, 1]301 let digits = if iv == 0.0 {302 vec![0u8]303 } else {304 let mut v = iv.abs();305 let mut nums = Vec::with_capacity(1);306 while v != 0.0 {307 nums.push((v % radix) as u8);308 v = (v / radix).floor();309 }310 nums311 };312 let neg = iv < 0.0;313 #[allow(clippy::bool_to_int_with_if)]314 let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });315 let zp2 = zp316 .max(precision)317 .saturating_sub(prefix.len() + digits.len());318319 if neg {320 out.push('-');321 } else if sign {322 out.push('+');323 } else if blank {324 out.push(' ');325 }326327 out.reserve(zp2);328 for _ in 0..zp2 {329 out.push('0');330 }331 out.push_str(prefix);332333 for digit in digits.into_iter().rev() {334 let ch = NUMBERS[digit as usize] as char;335 out.push(if caps { ch.to_ascii_uppercase() } else { ch });336 }337}338339pub fn render_decimal(340 out: &mut String,341 iv: f64,342 padding: usize,343 precision: usize,344 blank: bool,345 sign: bool,346) {347 render_integer(out, iv, padding, precision, blank, sign, 10, "", false);348}349pub fn render_octal(350 out: &mut String,351 iv: f64,352 padding: usize,353 precision: usize,354 alt: bool,355 blank: bool,356 sign: bool,357) {358 render_integer(359 out,360 iv,361 padding,362 precision,363 blank,364 sign,365 8,366 if alt && iv != 0.0 { "0" } else { "" },367 false,368 );369}370371#[allow(clippy::fn_params_excessive_bools)]372pub fn render_hexadecimal(373 out: &mut String,374 iv: f64,375 padding: usize,376 precision: usize,377 alt: bool,378 blank: bool,379 sign: bool,380 caps: bool,381) {382 render_integer(383 out,384 iv,385 padding,386 precision,387 blank,388 sign,389 16,390 match (alt, caps) {391 (true, true) => "0X",392 (true, false) => "0x",393 (false, _) => "",394 },395 caps,396 );397}398399#[allow(clippy::fn_params_excessive_bools)]400pub fn render_float(401 out: &mut String,402 n: f64,403 mut padding: usize,404 precision: usize,405 blank: bool,406 sign: bool,407 ensure_pt: bool,408 trailing: bool,409) {410 #[allow(clippy::bool_to_int_with_if)]411 let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };412 padding = padding.saturating_sub(dot_size + precision);413 render_decimal(out, n.floor(), padding, 0, blank, sign);414 if precision == 0 {415 if ensure_pt {416 out.push('.');417 }418 return;419 }420 let frac = n421 .fract()422 .mul_add(10.0_f64.powf(precision as f64), 0.5)423 .floor();424 if trailing || frac > 0.0 {425 out.push('.');426 let mut frac_str = String::new();427 render_decimal(&mut frac_str, frac, precision, 0, false, false);428 let mut trim = frac_str.len();429 if !trailing {430 for b in frac_str.as_bytes().iter().rev() {431 if *b == b'0' {432 trim -= 1;433 }434 }435 }436 out.push_str(&frac_str[..trim]);437 } else if ensure_pt {438 out.push('.');439 }440}441442#[allow(clippy::fn_params_excessive_bools)]443pub fn render_float_sci(444 out: &mut String,445 n: f64,446 mut padding: usize,447 precision: usize,448 blank: bool,449 sign: bool,450 ensure_pt: bool,451 trailing: bool,452 caps: bool,453) {454 let exponent = n.log10().floor();455 let mantissa = if exponent as i16 == -324 {456 n * 10.0 / 10.0_f64.powf(exponent + 1.0)457 } else {458 n / 10.0_f64.powf(exponent)459 };460 let mut exponent_str = String::new();461 render_decimal(&mut exponent_str, exponent, 3, 0, false, true);462463 // +1 for e464 padding = padding.saturating_sub(exponent_str.len() + 1);465466 render_float(467 out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,468 );469 out.push(if caps { 'E' } else { 'e' });470 out.push_str(&exponent_str);471}472473#[allow(clippy::too_many_lines)]474pub fn format_code(475 s: State,476 out: &mut String,477 value: &Val,478 code: &Code<'_>,479 width: usize,480 precision: Option<usize>,481) -> Result<()> {482 let clfags = &code.cflags;483 let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));484 let padding = if clfags.zero && !clfags.left {485 width486 } else {487 0488 };489490 // TODO: If left padded, can optimize by writing directly to out491 let mut tmp_out = String::new();492493 match code.convtype {494 ConvTypeV::String => tmp_out.push_str(&value.clone().to_string(s)?),495 ConvTypeV::Decimal => {496 let value = f64::from_untyped(value.clone(), s)?;497 render_decimal(498 &mut tmp_out,499 value,500 padding,501 iprec,502 clfags.blank,503 clfags.sign,504 );505 }506 ConvTypeV::Octal => {507 let value = f64::from_untyped(value.clone(), s)?;508 render_octal(509 &mut tmp_out,510 value,511 padding,512 iprec,513 clfags.alt,514 clfags.blank,515 clfags.sign,516 );517 }518 ConvTypeV::Hexadecimal => {519 let value = f64::from_untyped(value.clone(), s)?;520 render_hexadecimal(521 &mut tmp_out,522 value,523 padding,524 iprec,525 clfags.alt,526 clfags.blank,527 clfags.sign,528 code.caps,529 );530 }531 ConvTypeV::Scientific => {532 let value = f64::from_untyped(value.clone(), s)?;533 render_float_sci(534 &mut tmp_out,535 value,536 padding,537 fpprec,538 clfags.blank,539 clfags.sign,540 clfags.alt,541 true,542 code.caps,543 );544 }545 ConvTypeV::Float => {546 let value = f64::from_untyped(value.clone(), s)?;547 render_float(548 &mut tmp_out,549 value,550 padding,551 fpprec,552 clfags.blank,553 clfags.sign,554 clfags.alt,555 true,556 );557 }558 ConvTypeV::Shorter => {559 let value = f64::from_untyped(value.clone(), s)?;560 let exponent = value.log10().floor();561 if exponent < -4.0 || exponent >= fpprec as f64 {562 render_float_sci(563 &mut tmp_out,564 value,565 padding,566 fpprec - 1,567 clfags.blank,568 clfags.sign,569 clfags.alt,570 clfags.alt,571 code.caps,572 );573 } else {574 let digits_before_pt = 1.max(exponent as usize + 1);575 render_float(576 &mut tmp_out,577 value,578 padding,579 fpprec - digits_before_pt,580 clfags.blank,581 clfags.sign,582 clfags.alt,583 clfags.alt,584 );585 }586 }587 ConvTypeV::Char => match value.clone() {588 Val::Num(n) => tmp_out.push(589 std::char::from_u32(n as u32)590 .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,591 ),592 Val::Str(s) => {593 if s.chars().count() != 1 {594 throw!(RuntimeError(595 format!("%c expected 1 char string, got {}", s.chars().count()).into(),596 ));597 }598 tmp_out.push_str(&s);599 }600 _ => {601 throw!(TypeMismatch(602 "%c requires number/string",603 vec![ValType::Num, ValType::Str],604 value.value_type(),605 ));606 }607 },608 ConvTypeV::Percent => tmp_out.push('%'),609 };610611 let padding = width.saturating_sub(tmp_out.len());612613 if !clfags.left {614 for _ in 0..padding {615 out.push(' ');616 }617 }618 out.push_str(&tmp_out);619 if clfags.left {620 for _ in 0..padding {621 out.push(' ');622 }623 }624625 Ok(())626}627628pub fn format_arr(s: State, str: &str, mut values: &[Val]) -> Result<String> {629 let codes = parse_codes(str)?;630 let mut out = String::new();631632 for code in codes {633 match code {634 Element::String(s) => {635 out.push_str(s);636 }637 Element::Code(c) => {638 let width = match c.width {639 Width::Star => {640 if values.is_empty() {641 throw!(NotEnoughValues);642 }643 let value = &values[0];644 values = &values[1..];645 usize::from_untyped(value.clone(), s.clone())?646 }647 Width::Fixed(n) => n,648 };649 let precision = match c.precision {650 Some(Width::Star) => {651 if values.is_empty() {652 throw!(NotEnoughValues);653 }654 let value = &values[0];655 values = &values[1..];656 Some(usize::from_untyped(value.clone(), s.clone())?)657 }658 Some(Width::Fixed(n)) => Some(n),659 None => None,660 };661662 // %% should not consume a value663 let value = if c.convtype == ConvTypeV::Percent {664 &Val::Null665 } else {666 if values.is_empty() {667 throw!(NotEnoughValues);668 }669 let value = &values[0];670 values = &values[1..];671 value672 };673674 format_code(s.clone(), &mut out, value, &c, width, precision)?;675 }676 }677 }678679 Ok(out)680}681682pub fn format_obj(s: State, str: &str, values: &ObjValue) -> Result<String> {683 let codes = parse_codes(str)?;684 let mut out = String::new();685686 for code in codes {687 match code {688 Element::String(s) => {689 out.push_str(s);690 }691 Element::Code(c) => {692 // TODO: Operate on ref693 let f: IStr = c.mkey.into();694 let width = match c.width {695 Width::Star => {696 throw!(CannotUseStarWidthWithObject);697 }698 Width::Fixed(n) => n,699 };700 let precision = match c.precision {701 Some(Width::Star) => {702 throw!(CannotUseStarWidthWithObject);703 }704 Some(Width::Fixed(n)) => Some(n),705 None => None,706 };707708 let value = if c.convtype == ConvTypeV::Percent {709 Val::Null710 } else {711 if f.is_empty() {712 throw!(MappingKeysRequired);713 }714 if let Some(v) = values.get(s.clone(), f.clone())? {715 v716 } else {717 throw!(NoSuchFormatField(f));718 }719 };720721 format_code(s.clone(), &mut out, &value, &c, width, precision)?;722 }723 }724 }725726 Ok(out)727}728729#[cfg(test)]730pub mod test_format {731 use super::*;732733 #[test]734 fn parse() {735 assert_eq!(736 parse_codes(737 "How much error budget is left looking at our %.3f%% availability gurantees?"738 )739 .unwrap()740 .len(),741 4742 );743 }744745 #[test]746 fn octals() {747 let s = State::default();748 assert_eq!(749 format_arr(s.clone(), "%#o", &[Val::Num(8.0)]).unwrap(),750 "010"751 );752 assert_eq!(753 format_arr(s.clone(), "%#4o", &[Val::Num(8.0)]).unwrap(),754 " 010"755 );756 assert_eq!(757 format_arr(s.clone(), "%4o", &[Val::Num(8.0)]).unwrap(),758 " 10"759 );760 assert_eq!(761 format_arr(s.clone(), "%04o", &[Val::Num(8.0)]).unwrap(),762 "0010"763 );764 assert_eq!(765 format_arr(s.clone(), "%+4o", &[Val::Num(8.0)]).unwrap(),766 " +10"767 );768 assert_eq!(769 format_arr(s.clone(), "%+04o", &[Val::Num(8.0)]).unwrap(),770 "+010"771 );772 assert_eq!(773 format_arr(s.clone(), "%-4o", &[Val::Num(8.0)]).unwrap(),774 "10 "775 );776 assert_eq!(777 format_arr(s.clone(), "%+-4o", &[Val::Num(8.0)]).unwrap(),778 "+10 "779 );780 assert_eq!(format_arr(s, "%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");781 }782783 #[test]784 fn percent_doesnt_consumes_values() {785 let s = State::default();786 assert_eq!(787 format_arr(788 s,789 "How much error budget is left looking at our %.3f%% availability gurantees?",790 &[Val::Num(4.0)]791 )792 .unwrap(),793 "How much error budget is left looking at our 4.000% availability gurantees?"794 );795 }796}crates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -116,7 +116,7 @@
|| {
let value = obj.get(s.clone(), field.clone())?.unwrap();
manifest_json_ex_buf(s.clone(), &value, buf, cur_padding, options)?;
- Ok(Val::Null)
+ Ok(())
},
)?;
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -186,16 +186,26 @@
}
}
+/// Represents a Jsonnet array value.
#[derive(Debug, Clone, Trace)]
// may contrain other ArrValue
#[trace(tracking(force))]
pub enum ArrValue {
+ /// Layout optimized byte array.
Bytes(#[trace(skip)] IBytes),
+ /// Every element is lazy evaluated.
Lazy(Cc<Vec<Thunk<Val>>>),
+ /// Every field is already evaluated.
Eager(Cc<Vec<Val>>),
+ /// Concatenation of two arrays of any kind.
Extended(Box<(Self, Self)>),
+ /// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.
+ /// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.
Range(i32, i32),
+ /// Sliced array view.
Slice(Box<Slice>),
+ /// Reversed array view.
+ /// Returned by `std.reverse(other)` call
Reversed(Box<Self>),
}
@@ -237,6 +247,7 @@
}))
}
+ /// Array length.
pub fn len(&self) -> usize {
match self {
Self::Bytes(i) => i.len(),
@@ -249,10 +260,14 @@
}
}
+ /// Is array contains no elements?
pub fn is_empty(&self) -> bool {
self.len() == 0
}
+ /// Get array element by index, evaluating it, if it is lazy.
+ ///
+ /// Returns `None` on out-of-bounds condition.
pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {
match self {
Self::Bytes(i) => i
@@ -297,6 +312,9 @@
}
}
+ /// Get array element by index, without evaluation.
+ ///
+ /// Returns `None` on out-of-bounds condition.
pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
match self {
Self::Bytes(i) => i
@@ -337,6 +355,7 @@
}
}
+ /// Evaluate all array elements, returning new array.
pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {
Ok(match self {
Self::Bytes(i) => {
@@ -389,6 +408,7 @@
})
}
+ /// Iterate over elements, evaluating them.
pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {
(0..self.len()).map(move |idx| match self {
Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),
@@ -400,6 +420,7 @@
})
}
+ /// Iterate over elements, returning lazy values.
pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {
(0..self.len()).map(move |idx| match self {
Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),
@@ -411,11 +432,13 @@
})
}
+ /// Return a reversed view on current array.
#[must_use]
pub fn reversed(self) -> Self {
Self::Reversed(Box::new(self))
}
+ /// Return a new array, produced by passing every element of current array to specified callback function.
pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {
let mut out = Vec::with_capacity(self.len());
@@ -426,6 +449,7 @@
Ok(Self::Eager(Cc::new(out)))
}
+ /// Return a new array, produced from current array by removing every value, for which specified callback function returns false.
pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
let mut out = Vec::with_capacity(self.len());
@@ -460,12 +484,22 @@
}
}
+/// Represents a Jsonnet value, which can be spliced or indexed (string or array).
#[allow(clippy::module_name_repetitions)]
pub enum IndexableVal {
+ /// String.
Str(IStr),
+ /// Array.
Arr(ArrValue),
}
impl IndexableVal {
+ /// Slice the value.
+ ///
+ /// # Implementation
+ ///
+ /// For strings, will create a copy of specified interval.
+ ///
+ /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.
pub fn slice(
self,
index: Option<BoundedUsize<0, { i32::MAX as usize }>>,
@@ -511,14 +545,24 @@
}
}
+/// Represents any valid Jsonnet value.
#[derive(Debug, Clone, Trace)]
pub enum Val {
+ /// Represents a Jsonnet boolean.
Bool(bool),
+ /// Represents a Jsonnet null value.
Null,
+ /// Represents a Jsonnet string.
Str(IStr),
+ /// Represents a Jsonnet number.
+ /// Should be finite, and not NaN
+ /// This restriction isn't enforced by enum, as enum field can't be marked as private
Num(f64),
+ /// Represents a Jsonnet array.
Arr(ArrValue),
+ /// Represents a Jsonnet object.
Obj(ObjValue),
+ /// Represents a Jsonnet function.
Func(FuncVal),
}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -52,91 +52,88 @@
builder.with_super(eval);
for (name, builtin) in [
- ("length".into(), builtin_length::INST),
+ ("length", builtin_length::INST),
// Types
- ("type".into(), builtin_type::INST),
- ("isString".into(), builtin_is_string::INST),
- ("isNumber".into(), builtin_is_number::INST),
- ("isBoolean".into(), builtin_is_boolean::INST),
- ("isObject".into(), builtin_is_object::INST),
- ("isArray".into(), builtin_is_array::INST),
- ("isFunction".into(), builtin_is_function::INST),
+ ("type", builtin_type::INST),
+ ("isString", builtin_is_string::INST),
+ ("isNumber", builtin_is_number::INST),
+ ("isBoolean", builtin_is_boolean::INST),
+ ("isObject", builtin_is_object::INST),
+ ("isArray", builtin_is_array::INST),
+ ("isFunction", builtin_is_function::INST),
// Arrays
- ("makeArray".into(), builtin_make_array::INST),
- ("slice".into(), builtin_slice::INST),
- ("map".into(), builtin_map::INST),
- ("flatMap".into(), builtin_flatmap::INST),
- ("filter".into(), builtin_filter::INST),
- ("foldl".into(), builtin_foldl::INST),
- ("foldr".into(), builtin_foldr::INST),
- ("range".into(), builtin_range::INST),
- ("join".into(), builtin_join::INST),
- ("reverse".into(), builtin_reverse::INST),
- ("any".into(), builtin_any::INST),
- ("all".into(), builtin_all::INST),
- ("member".into(), builtin_member::INST),
- ("count".into(), builtin_count::INST),
+ ("makeArray", builtin_make_array::INST),
+ ("slice", builtin_slice::INST),
+ ("map", builtin_map::INST),
+ ("flatMap", builtin_flatmap::INST),
+ ("filter", builtin_filter::INST),
+ ("foldl", builtin_foldl::INST),
+ ("foldr", builtin_foldr::INST),
+ ("range", builtin_range::INST),
+ ("join", builtin_join::INST),
+ ("reverse", builtin_reverse::INST),
+ ("any", builtin_any::INST),
+ ("all", builtin_all::INST),
+ ("member", builtin_member::INST),
+ ("count", builtin_count::INST),
// Math
- ("modulo".into(), builtin_modulo::INST),
- ("floor".into(), builtin_floor::INST),
- ("ceil".into(), builtin_ceil::INST),
- ("log".into(), builtin_log::INST),
- ("pow".into(), builtin_pow::INST),
- ("sqrt".into(), builtin_sqrt::INST),
- ("sin".into(), builtin_sin::INST),
- ("cos".into(), builtin_cos::INST),
- ("tan".into(), builtin_tan::INST),
- ("asin".into(), builtin_asin::INST),
- ("acos".into(), builtin_acos::INST),
- ("atan".into(), builtin_atan::INST),
- ("exp".into(), builtin_exp::INST),
- ("mantissa".into(), builtin_mantissa::INST),
- ("exponent".into(), builtin_exponent::INST),
+ ("modulo", builtin_modulo::INST),
+ ("floor", builtin_floor::INST),
+ ("ceil", builtin_ceil::INST),
+ ("log", builtin_log::INST),
+ ("pow", builtin_pow::INST),
+ ("sqrt", builtin_sqrt::INST),
+ ("sin", builtin_sin::INST),
+ ("cos", builtin_cos::INST),
+ ("tan", builtin_tan::INST),
+ ("asin", builtin_asin::INST),
+ ("acos", builtin_acos::INST),
+ ("atan", builtin_atan::INST),
+ ("exp", builtin_exp::INST),
+ ("mantissa", builtin_mantissa::INST),
+ ("exponent", builtin_exponent::INST),
// Operator
- ("mod".into(), builtin_mod::INST),
- ("primitiveEquals".into(), builtin_primitive_equals::INST),
- ("equals".into(), builtin_equals::INST),
- ("format".into(), builtin_format::INST),
+ ("mod", builtin_mod::INST),
+ ("primitiveEquals", builtin_primitive_equals::INST),
+ ("equals", builtin_equals::INST),
+ ("format", builtin_format::INST),
// Sort
- ("sort".into(), builtin_sort::INST),
+ ("sort", builtin_sort::INST),
// Hash
- ("md5".into(), builtin_md5::INST),
+ ("md5", builtin_md5::INST),
// Encoding
- ("encodeUTF8".into(), builtin_encode_utf8::INST),
- ("decodeUTF8".into(), builtin_decode_utf8::INST),
- ("base64".into(), builtin_base64::INST),
- ("base64Decode".into(), builtin_base64_decode::INST),
- (
- "base64DecodeBytes".into(),
- builtin_base64_decode_bytes::INST,
- ),
+ ("encodeUTF8", builtin_encode_utf8::INST),
+ ("decodeUTF8", builtin_decode_utf8::INST),
+ ("base64", builtin_base64::INST),
+ ("base64Decode", builtin_base64_decode::INST),
+ ("base64DecodeBytes", builtin_base64_decode_bytes::INST),
// Objects
- ("objectFieldsEx".into(), builtin_object_fields_ex::INST),
- ("objectHasEx".into(), builtin_object_has_ex::INST),
+ ("objectFieldsEx", builtin_object_fields_ex::INST),
+ ("objectHasEx", builtin_object_has_ex::INST),
// Manifest
- ("escapeStringJson".into(), builtin_escape_string_json::INST),
- ("manifestJsonEx".into(), builtin_manifest_json_ex::INST),
- ("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),
+ ("escapeStringJson", builtin_escape_string_json::INST),
+ ("manifestJsonEx", builtin_manifest_json_ex::INST),
+ ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),
// Parsing
- ("parseJson".into(), builtin_parse_json::INST),
- ("parseYaml".into(), builtin_parse_yaml::INST),
+ ("parseJson", builtin_parse_json::INST),
+ ("parseYaml", builtin_parse_yaml::INST),
// Misc
- ("codepoint".into(), builtin_codepoint::INST),
- ("substr".into(), builtin_substr::INST),
- ("char".into(), builtin_char::INST),
- ("strReplace".into(), builtin_str_replace::INST),
- ("splitLimit".into(), builtin_splitlimit::INST),
- ("asciiUpper".into(), builtin_ascii_upper::INST),
- ("asciiLower".into(), builtin_ascii_lower::INST),
- ("findSubstr".into(), builtin_find_substr::INST),
- ("startsWith".into(), builtin_starts_with::INST),
- ("endsWith".into(), builtin_ends_with::INST),
+ ("codepoint", builtin_codepoint::INST),
+ ("substr", builtin_substr::INST),
+ ("char", builtin_char::INST),
+ ("strReplace", builtin_str_replace::INST),
+ ("splitLimit", builtin_splitlimit::INST),
+ ("asciiUpper", builtin_ascii_upper::INST),
+ ("asciiLower", builtin_ascii_lower::INST),
+ ("findSubstr", builtin_find_substr::INST),
+ ("startsWith", builtin_starts_with::INST),
+ ("endsWith", builtin_ends_with::INST),
]
.iter()
.cloned()
{
builder
- .member(name)
+ .member(name.into())
.hide()
.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))
.expect("no conflict");
tests/src/lib.rsdiffbeforeafterboth--- a/tests/src/lib.rs
+++ b/tests/src/lib.rs
@@ -1 +1 @@
-
+//! See tests/, suite/ and golden/ directories for tests