difftreelog
style fix formatting
in: master
31 files changed
crates/jrsonnet-evaluator/src/analyze.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/analyze.rs
+++ b/crates/jrsonnet-evaluator/src/analyze.rs
@@ -21,10 +21,10 @@
use jrsonnet_gcmodule::Acyclic;
use jrsonnet_interner::IStr;
use jrsonnet_ir::{
- function::FunctionSignature, ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType,
- BindSpec, CompSpec, Destruct, Expr, ExprParams, FieldName, ForSpecData, IfElse, IfSpecData,
- ImportKind, LiteralType, NumValue, ObjBody, ObjComp, ObjMembers, Slice, SliceDesc, Span,
- Spanned, UnaryOpType, Visibility,
+ ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec, Destruct, Expr,
+ ExprParams, FieldName, ForSpecData, IfElse, IfSpecData, ImportKind, LiteralType, NumValue,
+ ObjBody, ObjComp, ObjMembers, Slice, SliceDesc, Span, Spanned, UnaryOpType, Visibility,
+ function::FunctionSignature,
};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -5,9 +5,9 @@
rc::Rc,
};
-use jrsonnet_gcmodule::{cc_dyn, Cc};
+use jrsonnet_gcmodule::{Cc, cc_dyn};
-use crate::{analyze::LExpr, function::NativeFn, typed::IntoUntyped, Context, Result, Thunk, Val};
+use crate::{Context, Result, Thunk, Val, analyze::LExpr, function::NativeFn, typed::IntoUntyped};
mod spec;
pub use spec::{ArrayLike, *};
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -11,13 +11,13 @@
use super::ArrValue;
use crate::{
+ Context, Error, ObjValue, Result, Thunk, Val,
analyze::LExpr,
error::ErrorKind::InfiniteRecursionDetected,
evaluate::evaluate,
function::NativeFn,
typed::{IntoUntyped, Typed},
val::ThunkValue,
- Context, Error, ObjValue, Result, Thunk, Val,
};
pub trait ArrayLike: Any + Trace + Debug {
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -4,7 +4,7 @@
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
-use crate::{analyze::LocalId, error, error::ErrorKind::*, Pending, Result, SupThis, Thunk, Val};
+use crate::{Pending, Result, SupThis, Thunk, Val, analyze::LocalId, error, error::ErrorKind::*};
#[derive(Debug, Trace, Clone, Educe)]
#[educe(PartialEq)]
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -9,10 +9,10 @@
use thiserror::Error;
use crate::{
+ ObjValue, ResolvePathOwned,
function::{CallLocation, FunctionSignature, ParamName},
stdlib::format::FormatError,
typed::TypeLocError,
- ObjValue, ResolvePathOwned,
};
#[derive(Debug, Clone, Acyclic)]
@@ -286,11 +286,11 @@
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- writeln!(f, "{}", self.0 .0)?;
- for el in &self.0 .1 .0 {
+ writeln!(f, "{}", self.0.0)?;
+ for el in &self.0.1.0 {
write!(f, "\t{}", el.desc)?;
if let Some(loc) = &el.location {
- write!(f, "at {}", loc.0 .0 .0)?;
+ write!(f, "at {}", loc.0.0.0)?;
loc.0.map_source_locations(&[loc.1, loc.2]);
}
writeln!(f)?;
crates/jrsonnet-evaluator/src/evaluate/compspec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/compspec.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/compspec.rs
@@ -7,12 +7,12 @@
evaluate_field_member_static, evaluate_field_member_unbound,
};
use crate::{
+ Context, ContextBuilder, ObjValue, ObjValueBuilder, Pending, Result, Thunk, Val,
analyze::{LArrComp, LBind, LCompSpec, LDestruct, LExpr, LFieldMember, LObjComp, LocalId},
arr::ArrValue,
bail,
error::ErrorKind::*,
evaluate::evaluate,
- Context, ContextBuilder, ObjValue, ObjValueBuilder, Pending, Result, Thunk, Val,
};
trait CompCollector {
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -3,10 +3,10 @@
use jrsonnet_gcmodule::Trace;
use crate::{
+ Context, ContextBuilder, Pending, Result, SupThis, Thunk, Unbound, Val,
analyze::{LBind, LDestruct, LDestructField, LDestructRest, LExpr, LocalId},
bail,
evaluate::evaluate,
- Context, ContextBuilder, Pending, Result, SupThis, Thunk, Unbound, Val,
};
#[allow(dead_code, reason = "not dead in exp-destruct")]
@@ -97,7 +97,7 @@
use jrsonnet_interner::IStr;
use rustc_hash::FxHashSet;
- use crate::{bail, ObjValueBuilder};
+ use crate::{ObjValueBuilder, bail};
let captured_fields: FxHashSet<IStr> = fields.iter().map(|f| f.name.clone()).collect();
let field_names: Vec<(IStr, bool)> = fields
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,19 +11,20 @@
operator::evaluate_binary_op_special,
};
use crate::{
+ Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Result, ResultExt as _, SupThis,
+ Unbound, Val,
analyze::{
LArgsDesc, LAssertStmt, LExpr, LFieldMember, LFieldName, LFunction, LIndexPart, LObjBody,
LObjMembers,
},
bail,
- error::{suggest_object_fields, ErrorKind::*},
+ error::{ErrorKind::*, suggest_object_fields},
evaluate::operator::evaluate_unary_op,
- function::{prepared::PreparedFuncVal, CallLocation, FuncDesc, FuncVal},
+ function::{CallLocation, FuncDesc, FuncVal, prepared::PreparedFuncVal},
in_frame, runtime_error,
typed::FromUntyped as _,
val::{CachedUnbound, Thunk},
- with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Result, ResultExt as _,
- SupThis, Unbound, Val,
+ with_state,
};
pub mod compspec;
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -3,6 +3,7 @@
use jrsonnet_ir::{BinaryOpType, UnaryOpType};
use crate::{
+ Context, Result, Val,
analyze::LExpr,
arr::ArrValue,
bail, error,
@@ -10,8 +11,7 @@
evaluate::evaluate,
stdlib::std_format,
typed::IntoUntyped as _,
- val::{equals, StrValue},
- Context, Result, Val,
+ val::{StrValue, equals},
};
pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -8,13 +8,13 @@
use self::{
builtin::Builtin,
- prepared::{parse_prepared_builtin_call, PreparedCall},
+ prepared::{PreparedCall, parse_prepared_builtin_call},
};
use crate::{
+ Context, ContextBuilder, Result, Thunk, Val,
analyze::{LDestruct, LExpr, LFunction},
evaluate::{destructure::destruct, ensure_sufficient_stack, evaluate, evaluate_trivial},
function::builtin::BuiltinFunc,
- Context, ContextBuilder, Result, Thunk, Val,
};
pub mod builtin;
@@ -210,8 +210,7 @@
return false;
}
#[allow(irrefutable_let_patterns, reason = "refutable with exp-destruct")]
- let LDestruct::Full(id) = ¶m.destruct
- else {
+ let LDestruct::Full(id) = ¶m.destruct else {
return false;
};
matches!(&*desc.func.body, LExpr::Local(v) if v == id)
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,9 +1,9 @@
use std::rc::Rc;
use crate::{
+ Context, ContextBuilder, Result, Thunk,
analyze::LFunction,
evaluate::{destructure::destruct, evaluate},
- Context, ContextBuilder, Result, Thunk,
};
/// Creates Context with all argument default values applied
crates/jrsonnet-evaluator/src/function/prepared.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/prepared.rs
+++ b/crates/jrsonnet-evaluator/src/function/prepared.rs
@@ -5,10 +5,7 @@
use rustc_hash::FxHashSet;
use super::{CallLocation, FuncVal};
-use crate::{
- Result, Thunk, Val, bail,
- error::ErrorKind::*,
-};
+use crate::{Result, Thunk, Val, bail, error::ErrorKind::*};
#[derive(Debug, Trace, Clone)]
pub struct PreparedFuncVal {
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -3,16 +3,16 @@
use jrsonnet_interner::{IBytes, IStr};
use jrsonnet_ir::NumValue;
use serde::{
+ Deserialize, Serialize, Serializer,
de::{self, Visitor},
ser::{
Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
SerializeTupleStruct, SerializeTupleVariant,
},
- Deserialize, Serialize, Serializer,
};
use crate::{
- in_description_frame, runtime_error, Error as JrError, ObjValue, ObjValueBuilder, Result, Val,
+ Error as JrError, ObjValue, ObjValueBuilder, Result, Val, in_description_frame, runtime_error,
};
impl<'de> Deserialize<'de> for Val {
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -39,7 +39,7 @@
pub use evaluate::ensure_sufficient_stack;
use function::CallLocation;
pub use import::*;
-use jrsonnet_gcmodule::{cc_dyn, Cc, Trace};
+use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};
pub use jrsonnet_interner::{IBytes, IStr};
use jrsonnet_ir::Expr;
pub use jrsonnet_ir::{NumValue, Source, SourcePath, Span};
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,8 +1,7 @@
use std::{borrow::Cow, fmt::Write, hint::black_box, ptr};
use crate::{
- bail, evaluate::ensure_sufficient_stack, in_description_frame, Error,
- Result, ResultExt, Val,
+ Error, Result, ResultExt, Val, bail, evaluate::ensure_sufficient_stack, in_description_frame,
};
pub trait ManifestFormat {
crates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj/mod.rs
+++ b/crates/jrsonnet-evaluator/src/obj/mod.rs
@@ -11,8 +11,8 @@
};
use educe::Educe;
-use im_rc::{vector, Vector};
-use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};
+use im_rc::{Vector, vector};
+use jrsonnet_gcmodule::{Acyclic, Cc, Trace, Weak, cc_dyn};
use jrsonnet_interner::IStr;
use jrsonnet_ir::Span;
use rustc_hash::{FxHashMap, FxHashSet};
@@ -23,13 +23,13 @@
pub use oop::ObjValueBuilder;
use crate::{
+ CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
arr::{PickObjectKeyValues, PickObjectValues},
bail,
- error::{suggest_object_fields, ErrorKind::*},
+ error::{ErrorKind::*, suggest_object_fields},
evaluate::operator::evaluate_add_op,
identity_hash,
val::{ArrValue, ThunkValue},
- CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
};
#[cfg(not(feature = "exp-preserve-order"))]
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -10,7 +10,7 @@
#[cfg(feature = "explaining-traces")]
use jrsonnet_ir::Span;
-use crate::{error::ErrorKind, Error};
+use crate::{Error, error::ErrorKind};
/// The way paths should be displayed
#[derive(Clone, Trace)]
@@ -259,7 +259,7 @@
struct ResetData {
loc: Span,
}
- use hi_doc::{source_to_ansi, Formatting, SnippetBuilder, Text};
+ use hi_doc::{Formatting, SnippetBuilder, Text, source_to_ansi};
write!(out, "{}", error.error())?;
if let ErrorKind::ImportSyntaxError { path, error } = error.error() {
@@ -277,14 +277,15 @@
use crate::analyze::DiagLevel;
let mut builder: Option<SnippetBuilder> = None;
let mut current_src: Option<&str> = None;
- let flush =
- |builder: Option<SnippetBuilder>, out: &mut dyn std::fmt::Write| -> Result<(), std::fmt::Error> {
- if let Some(b) = builder {
- let ansi = source_to_ansi(&b.build());
- write!(out, "\n{}", ansi.trim_end())?;
- }
- Ok(())
- };
+ let flush = |builder: Option<SnippetBuilder>,
+ out: &mut dyn std::fmt::Write|
+ -> Result<(), std::fmt::Error> {
+ if let Some(b) = builder {
+ let ansi = source_to_ansi(&b.build());
+ write!(out, "\n{}", ansi.trim_end())?;
+ }
+ Ok(())
+ };
for diag in diagnostics {
if let Some(span) = &diag.span {
let src = span.0.code();
@@ -295,14 +296,12 @@
}
let b = builder.as_mut().unwrap();
let ab = match diag.level {
- DiagLevel::Error => b.error(Text::fragment(
- diag.message.clone(),
- Formatting::default(),
- )),
- DiagLevel::Warning => b.warning(Text::fragment(
- diag.message.clone(),
- Formatting::default(),
- )),
+ DiagLevel::Error => {
+ b.error(Text::fragment(diag.message.clone(), Formatting::default()))
+ }
+ DiagLevel::Warning => {
+ b.warning(Text::fragment(diag.message.clone(), Formatting::default()))
+ }
};
ab.range(span.range()).build();
} else {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -17,7 +17,13 @@
pub use crate::arr::{ArrValue, ArrayLike};
use crate::{
- NumValue, ObjValue, Result, SupThis, Unbound, WeakSupThis, bail, error::{Error, ErrorKind::*}, evaluate::operator::{evaluate_compare_op, evaluate_mod_op}, function::FuncVal, gc::WithCapacityExt as _, manifest::{ManifestFormat, ToStringFormat}, typed::BoundedUsize
+ NumValue, ObjValue, Result, SupThis, Unbound, WeakSupThis, bail,
+ error::{Error, ErrorKind::*},
+ evaluate::operator::{evaluate_compare_op, evaluate_mod_op},
+ function::FuncVal,
+ gc::WithCapacityExt as _,
+ manifest::{ManifestFormat, ToStringFormat},
+ typed::BoundedUsize,
};
pub trait ThunkValue: Trace {
crates/jrsonnet-ir-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir-parser/src/lib.rs
+++ b/crates/jrsonnet-ir-parser/src/lib.rs
@@ -1,11 +1,11 @@
use jrsonnet_gcmodule::Acyclic;
use jrsonnet_ir::{
- unescape, ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec,
- Destruct, Expr, ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse,
- IfSpecData, ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers,
- Slice, SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility,
+ ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec, Destruct, Expr,
+ ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData,
+ ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers, Slice,
+ SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility, unescape,
};
-use jrsonnet_lexer::{collect_lexed_str_block, Lexeme, Lexer, Span as LexSpan, SyntaxKind, T};
+use jrsonnet_lexer::{Lexeme, Lexer, Span as LexSpan, SyntaxKind, T, collect_lexed_str_block};
pub struct ParserSettings {
pub source: Source,
crates/jrsonnet-ir/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir/src/expr.rs
+++ b/crates/jrsonnet-ir/src/expr.rs
@@ -7,9 +7,9 @@
use jrsonnet_interner::IStr;
use crate::{
+ NumValue,
function::{FunctionSignature, ParamDefault, ParamName, ParamParse},
source::Source,
- NumValue,
};
#[derive(Debug, PartialEq, Acyclic)]
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth1use std::string::String;23use proc_macro2::TokenStream;4use quote::{quote, quote_spanned};5use syn::{6 parenthesized,7 parse::{Parse, ParseStream},8 parse_macro_input,9 punctuated::Punctuated,10 spanned::Spanned,11 token::Comma,12 Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,13 LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,14};1516use self::typed::{derive_from_untyped_inner, derive_into_untyped_inner, derive_typed_inner};1718mod names;19mod typed;2021fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>22where23 Ident: PartialEq<I>,24{25 let attrs = attrs26 .iter()27 .filter(|a| a.path().is_ident(&ident))28 .collect::<Vec<_>>();29 if attrs.len() > 1 {30 return Err(Error::new(31 attrs[1].span(),32 "this attribute may be specified only once",33 ));34 } else if attrs.is_empty() {35 return Ok(false);36 }37 let attr = attrs[0];3839 match attr.meta {40 Meta::Path(_) => Ok(true),41 _ => Ok(false),42 }43}44fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>45where46 Ident: PartialEq<I>,47{48 let attrs = attrs49 .iter()50 .filter(|a| a.path().is_ident(&ident))51 .collect::<Vec<_>>();52 if attrs.len() > 1 {53 return Err(Error::new(54 attrs[1].span(),55 "this attribute may be specified only once",56 ));57 } else if attrs.is_empty() {58 return Ok(None);59 }60 let attr = attrs[0];61 let attr = attr.parse_args::<A>()?;6263 Ok(Some(attr))64}65fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)66where67 Ident: PartialEq<I>,68{69 attrs.retain(|a| !a.path().is_ident(&ident));70}7172fn path_is(path: &Path, needed: &str) -> bool {73 path.leading_colon.is_none()74 && !path.segments.is_empty()75 && path.segments.iter().last().unwrap().ident == needed76}7778fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {79 match ty {80 Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {81 let args = &path.path.segments.iter().last().unwrap().arguments;82 Some(args)83 }84 _ => None,85 }86}8788fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {89 let Some(args) = type_is_path(ty, "Option") else {90 return Ok(None);91 };92 // It should have only on angle-bracketed param ("<String>"):93 let PathArguments::AngleBracketed(params) = args else {94 return Err(Error::new(args.span(), "missing option generic"));95 };96 let generic_arg = params.args.iter().next().unwrap();97 // This argument must be a type:98 let GenericArgument::Type(ty) = generic_arg else {99 return Err(Error::new(100 generic_arg.span(),101 "option generic should be a type",102 ));103 };104 Ok(Some(ty))105}106107struct Field {108 attrs: Vec<Attribute>,109 name: Ident,110 _colon: Token![:],111 ty: Type,112}113impl Parse for Field {114 fn parse(input: ParseStream) -> syn::Result<Self> {115 Ok(Self {116 attrs: input.call(Attribute::parse_outer)?,117 name: input.parse()?,118 _colon: input.parse()?,119 ty: input.parse()?,120 })121 }122}123124mod kw {125 syn::custom_keyword!(fields);126 syn::custom_keyword!(rename);127 syn::custom_keyword!(alias);128 syn::custom_keyword!(flatten);129 syn::custom_keyword!(add);130 syn::custom_keyword!(hide);131 syn::custom_keyword!(method);132 syn::custom_keyword!(ok);133}134135struct BuiltinAttrs {136 fields: Vec<Field>,137}138impl Parse for BuiltinAttrs {139 fn parse(input: ParseStream) -> syn::Result<Self> {140 if input.is_empty() {141 return Ok(Self { fields: Vec::new() });142 }143 input.parse::<kw::fields>()?;144 let fields;145 parenthesized!(fields in input);146 let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;147 Ok(Self {148 fields: p.into_iter().collect(),149 })150 }151}152153enum Optionality {154 Required,155 Optional,156 Default(Expr),157 TypeDefault,158}159160#[allow(161 clippy::large_enum_variant,162 reason = "this macro is not that hot for it to matter"163)]164enum ArgInfo {165 Normal {166 ty: Box<Type>,167 optionality: Optionality,168 name: Option<String>,169 cfg_attrs: Vec<Attribute>,170 },171 Lazy {172 is_option: bool,173 name: Option<String>,174 },175 Context,176 Location,177 This,178}179180impl ArgInfo {181 fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {182 let FnArg::Typed(arg) = arg else {183 unreachable!()184 };185 let ident = match &arg.pat as &Pat {186 Pat::Ident(i) => Some(i.ident.clone()),187 _ => None,188 };189 let ty = &arg.ty;190 if type_is_path(ty, "Context").is_some() {191 return Ok(Self::Context);192 } else if type_is_path(ty, "CallLocation").is_some() {193 return Ok(Self::Location);194 } else if type_is_path(ty, "Thunk").is_some() {195 return Ok(Self::Lazy {196 is_option: false,197 name: ident.map(|v| v.to_string()),198 });199 }200201 match ty as &Type {202 Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),203 _ => {}204 }205206 let (optionality, ty) = if try_parse_attr_noargs(&arg.attrs, "default")? {207 remove_attr(&mut arg.attrs, "default");208 (Optionality::TypeDefault, ty.clone())209 } else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {210 remove_attr(&mut arg.attrs, "default");211 (Optionality::Default(default), ty.clone())212 } else if let Some(ty) = extract_type_from_option(ty)? {213 if type_is_path(ty, "Thunk").is_some() {214 return Ok(Self::Lazy {215 is_option: true,216 name: ident.map(|v| v.to_string()),217 });218 }219220 (Optionality::Optional, Box::new(ty.clone()))221 } else {222 (Optionality::Required, ty.clone())223 };224225 let cfg_attrs = arg226 .attrs227 .iter()228 .filter(|a| a.path().is_ident("cfg"))229 .cloned()230 .collect();231232 Ok(Self::Normal {233 ty,234 optionality,235 name: ident.map(|v| v.to_string()),236 cfg_attrs,237 })238 }239}240241#[proc_macro_attribute]242pub fn builtin(243 attr: proc_macro::TokenStream,244 item: proc_macro::TokenStream,245) -> proc_macro::TokenStream {246 let attr = parse_macro_input!(attr as BuiltinAttrs);247 let item_fn = parse_macro_input!(item as ItemFn);248249 match builtin_inner(attr, item_fn) {250 Ok(v) => v.into(),251 Err(e) => e.into_compile_error().into(),252 }253}254255#[allow(clippy::too_many_lines)]256fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {257 let ReturnType::Type(_, result) = &fun.sig.output else {258 return Err(Error::new(259 fun.sig.span(),260 "builtin should return something",261 ));262 };263264 let name = fun.sig.ident.to_string();265 let args = fun266 .sig267 .inputs268 .iter_mut()269 .map(|arg| ArgInfo::parse(&name, arg))270 .collect::<Result<Vec<_>>>()?;271272 let params_desc = args.iter().filter_map(|a| match a {273 ArgInfo::Normal {274 optionality,275 name,276 cfg_attrs,277 ..278 } => {279 let name = name280 .as_ref()281 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});282 let default = match optionality {283 Optionality::Required => quote!(ParamDefault::None),284 Optionality::Optional | Optionality::TypeDefault => quote!(ParamDefault::Exists),285 Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),286 };287 Some(quote! {288 #(#cfg_attrs)*289 [#name => #default],290 })291 }292 ArgInfo::Lazy { is_option, name } => {293 let name = name294 .as_ref()295 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});296 Some(quote! {297 [#name => ParamDefault::exists(#is_option)],298 })299 }300 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,301 });302303 let mut id = 0usize;304 let pass = args305 .iter()306 .map(|a| match a {307 ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {308 let cid = id;309 id += 1;310 (quote! {#cid}, a)311 }312 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {313 (quote! {compile_error!("should not use id")}, a)314 }315 })316 .map(|(id, a)| match a {317 ArgInfo::Normal {318 ty,319 optionality,320 name,321 cfg_attrs,322 } => {323 let name = name.as_ref().map_or("<unnamed>", String::as_str);324 let eval = quote! {jrsonnet_evaluator::in_description_frame(325 || format!("argument <{}> evaluation", #name),326 || <#ty as FromUntyped>::from_untyped(value.evaluate()?),327 )?};328 let value = match optionality {329 Optionality::Required => quote! {{330 let value = parsed[#id].as_ref().expect("args shape is checked");331 #eval332 },},333 Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {334 Some(#eval)335 } else {336 None337 },},338 Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {339 #eval340 } else {341 let v: #ty = #expr;342 v343 },},344 Optionality::TypeDefault => quote! {if let Some(value) = &parsed[#id] {345 #eval346 } else {347 let v: #ty = Default::default();348 v349 },},350 };351 quote! {352 #(#cfg_attrs)*353 #value354 }355 }356 ArgInfo::Lazy { is_option, .. } => {357 if *is_option {358 quote! {if let Some(value) = &parsed[#id] {359 Some(value.clone())360 } else {361 None362 },}363 } else {364 quote! {365 parsed[#id].as_ref().expect("args shape is correct").clone(),366 }367 }368 }369 ArgInfo::Context => quote! {ctx.clone(),},370 ArgInfo::Location => quote! {location,},371 ArgInfo::This => quote! {self,},372 });373374 let fields = attr.fields.iter().map(|field| {375 let attrs = &field.attrs;376 let name = &field.name;377 let ty = &field.ty;378 quote! {379 #(#attrs)*380 pub #name: #ty,381 }382 });383384 let name = &fun.sig.ident;385 let vis = &fun.vis;386 let static_derive_copy = if attr.fields.is_empty() {387 quote! {, Copy, Default}388 } else {389 quote! {}390 };391392 Ok(quote! {393 #fun394395 #[doc(hidden)]396 #[allow(non_camel_case_types)]397 #[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]398 #vis struct #name {399 #(#fields)*400 }401 const _: () = {402 use ::jrsonnet_evaluator::{403 State, Val,404 function::{builtin::Builtin, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},405 Result, Context, typed::{Typed, FromUntyped, IntoUntypedResult},406 Span, params, Thunk,407 };408 params!(409 #(#params_desc)*410 );411412 impl Builtin for #name413 where414 Self: 'static415 {416 fn name(&self) -> &str {417 stringify!(#name)418 }419 fn params(&self) -> FunctionSignature {420 PARAMS.with(|p| p.clone())421 }422 #[allow(unused_variables)]423 fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {424 let result: #result = #name(#(#pass)*);425 <_ as IntoUntypedResult>::into_untyped_result(result)426 }427 fn as_any(&self) -> &dyn ::std::any::Any {428 self429 }430 }431 };432 })433}434435#[proc_macro_derive(Typed, attributes(typed))]436pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {437 let input = parse_macro_input!(item as DeriveInput);438439 match derive_typed_inner(input) {440 Ok(v) => v.into(),441 Err(e) => e.to_compile_error().into(),442 }443}444#[proc_macro_derive(IntoUntyped, attributes(typed))]445pub fn derive_into_untyped(item: proc_macro::TokenStream) -> proc_macro::TokenStream {446 let input = parse_macro_input!(item as DeriveInput);447448 match derive_into_untyped_inner(input) {449 Ok(v) => v.into(),450 Err(e) => e.to_compile_error().into(),451 }452}453#[proc_macro_derive(FromUntyped, attributes(typed))]454pub fn derive_from_untyped(item: proc_macro::TokenStream) -> proc_macro::TokenStream {455 let input = parse_macro_input!(item as DeriveInput);456457 match derive_from_untyped_inner(input) {458 Ok(v) => v.into(),459 Err(e) => e.to_compile_error().into(),460 }461}462463struct FormatInput {464 formatting: LitStr,465 arguments: Vec<Expr>,466}467impl Parse for FormatInput {468 fn parse(input: ParseStream) -> Result<Self> {469 let formatting = input.parse()?;470 let mut arguments = Vec::new();471472 while input.peek(Token![,]) {473 input.parse::<Token![,]>()?;474 if input.is_empty() {475 // Trailing comma476 break;477 }478 let expr = input.parse()?;479 arguments.push(expr);480 }481482 if !input.is_empty() {483 return Err(syn::Error::new(input.span(), "unexpected trailing input"));484 }485486 Ok(Self {487 formatting,488 arguments,489 })490 }491}492fn is_format_str(i: &str) -> bool {493 let mut is_plain = true;494 // -1 = {495 // +1 = }496 let mut is_bracket = 0i8;497 for ele in i.chars() {498 match ele {499 '{' if is_bracket == -1 => {500 is_bracket = 0;501 }502 '}' if is_bracket == -1 => {503 is_plain = false;504 break;505 }506 '}' if is_bracket == 1 => {507 is_bracket = 0;508 }509 '{' if is_bracket == 1 => {510 is_plain = false;511 break;512 }513 '{' => {514 is_bracket = -1;515 }516 '}' => {517 is_bracket = 1;518 }519 _ if is_bracket != 0 => {520 is_plain = false;521 break;522 }523 _ => {}524 }525 }526 !is_plain || is_bracket != 0527}528impl FormatInput {529 fn expand(self) -> TokenStream {530 let format = self.formatting;531 if is_format_str(&format.value()) {532 let args = self.arguments;533 quote! {534 ::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))535 }536 } else {537 if let Some(first) = self.arguments.first() {538 return syn::Error::new(539 first.span(),540 "string has no formatting codes, it should not have the arguments",541 )542 .into_compile_error();543 }544 quote! {545 ::jrsonnet_evaluator::IStr::from(#format)546 }547 }548 }549}550551/// `IStr` formatting helper552///553/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`554/// This macro looks for formatting codes in the input string, and uses555/// `format!()` only when necessary556#[proc_macro]557pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {558 let input = parse_macro_input!(input as FormatInput);559 input.expand().into()560}561562/// Create Thunk using closure syntax563#[proc_macro]564#[allow(non_snake_case)]565pub fn Thunk(input: proc_macro::TokenStream) -> proc_macro::TokenStream {566 let input = parse_macro_input!(input as ExprClosure);567568 let span = input.inputs.span();569 let move_check = input.capture.is_none().then(|| {570 quote_spanned! {span => {571 compile_error!("Thunk! needs to be called with move closure");572 }}573 });574575 let (env, closure, args) = syn_dissect_closure::split_env(input);576577 let trace_check = args.iter().map(|el| {578 let span = el.span();579 quote_spanned! {span => ::jrsonnet_evaluator::gc::assert_trace(&#el);}580 });581582 quote! {{583 #move_check584 #(#trace_check)*585 ::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))586 }}.into()587}1use std::string::String;23use proc_macro2::TokenStream;4use quote::{quote, quote_spanned};5use syn::{6 Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,7 LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type, parenthesized,8 parse::{Parse, ParseStream},9 parse_macro_input,10 punctuated::Punctuated,11 spanned::Spanned,12 token::Comma,13};1415use self::typed::{derive_from_untyped_inner, derive_into_untyped_inner, derive_typed_inner};1617mod names;18mod typed;1920fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>21where22 Ident: PartialEq<I>,23{24 let attrs = attrs25 .iter()26 .filter(|a| a.path().is_ident(&ident))27 .collect::<Vec<_>>();28 if attrs.len() > 1 {29 return Err(Error::new(30 attrs[1].span(),31 "this attribute may be specified only once",32 ));33 } else if attrs.is_empty() {34 return Ok(false);35 }36 let attr = attrs[0];3738 match attr.meta {39 Meta::Path(_) => Ok(true),40 _ => Ok(false),41 }42}43fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>44where45 Ident: PartialEq<I>,46{47 let attrs = attrs48 .iter()49 .filter(|a| a.path().is_ident(&ident))50 .collect::<Vec<_>>();51 if attrs.len() > 1 {52 return Err(Error::new(53 attrs[1].span(),54 "this attribute may be specified only once",55 ));56 } else if attrs.is_empty() {57 return Ok(None);58 }59 let attr = attrs[0];60 let attr = attr.parse_args::<A>()?;6162 Ok(Some(attr))63}64fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)65where66 Ident: PartialEq<I>,67{68 attrs.retain(|a| !a.path().is_ident(&ident));69}7071fn path_is(path: &Path, needed: &str) -> bool {72 path.leading_colon.is_none()73 && !path.segments.is_empty()74 && path.segments.iter().last().unwrap().ident == needed75}7677fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {78 match ty {79 Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {80 let args = &path.path.segments.iter().last().unwrap().arguments;81 Some(args)82 }83 _ => None,84 }85}8687fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {88 let Some(args) = type_is_path(ty, "Option") else {89 return Ok(None);90 };91 // It should have only on angle-bracketed param ("<String>"):92 let PathArguments::AngleBracketed(params) = args else {93 return Err(Error::new(args.span(), "missing option generic"));94 };95 let generic_arg = params.args.iter().next().unwrap();96 // This argument must be a type:97 let GenericArgument::Type(ty) = generic_arg else {98 return Err(Error::new(99 generic_arg.span(),100 "option generic should be a type",101 ));102 };103 Ok(Some(ty))104}105106struct Field {107 attrs: Vec<Attribute>,108 name: Ident,109 _colon: Token![:],110 ty: Type,111}112impl Parse for Field {113 fn parse(input: ParseStream) -> syn::Result<Self> {114 Ok(Self {115 attrs: input.call(Attribute::parse_outer)?,116 name: input.parse()?,117 _colon: input.parse()?,118 ty: input.parse()?,119 })120 }121}122123mod kw {124 syn::custom_keyword!(fields);125 syn::custom_keyword!(rename);126 syn::custom_keyword!(alias);127 syn::custom_keyword!(flatten);128 syn::custom_keyword!(add);129 syn::custom_keyword!(hide);130 syn::custom_keyword!(method);131 syn::custom_keyword!(ok);132}133134struct BuiltinAttrs {135 fields: Vec<Field>,136}137impl Parse for BuiltinAttrs {138 fn parse(input: ParseStream) -> syn::Result<Self> {139 if input.is_empty() {140 return Ok(Self { fields: Vec::new() });141 }142 input.parse::<kw::fields>()?;143 let fields;144 parenthesized!(fields in input);145 let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;146 Ok(Self {147 fields: p.into_iter().collect(),148 })149 }150}151152enum Optionality {153 Required,154 Optional,155 Default(Expr),156 TypeDefault,157}158159#[allow(160 clippy::large_enum_variant,161 reason = "this macro is not that hot for it to matter"162)]163enum ArgInfo {164 Normal {165 ty: Box<Type>,166 optionality: Optionality,167 name: Option<String>,168 cfg_attrs: Vec<Attribute>,169 },170 Lazy {171 is_option: bool,172 name: Option<String>,173 },174 Context,175 Location,176 This,177}178179impl ArgInfo {180 fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {181 let FnArg::Typed(arg) = arg else {182 unreachable!()183 };184 let ident = match &arg.pat as &Pat {185 Pat::Ident(i) => Some(i.ident.clone()),186 _ => None,187 };188 let ty = &arg.ty;189 if type_is_path(ty, "Context").is_some() {190 return Ok(Self::Context);191 } else if type_is_path(ty, "CallLocation").is_some() {192 return Ok(Self::Location);193 } else if type_is_path(ty, "Thunk").is_some() {194 return Ok(Self::Lazy {195 is_option: false,196 name: ident.map(|v| v.to_string()),197 });198 }199200 match ty as &Type {201 Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),202 _ => {}203 }204205 let (optionality, ty) = if try_parse_attr_noargs(&arg.attrs, "default")? {206 remove_attr(&mut arg.attrs, "default");207 (Optionality::TypeDefault, ty.clone())208 } else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {209 remove_attr(&mut arg.attrs, "default");210 (Optionality::Default(default), ty.clone())211 } else if let Some(ty) = extract_type_from_option(ty)? {212 if type_is_path(ty, "Thunk").is_some() {213 return Ok(Self::Lazy {214 is_option: true,215 name: ident.map(|v| v.to_string()),216 });217 }218219 (Optionality::Optional, Box::new(ty.clone()))220 } else {221 (Optionality::Required, ty.clone())222 };223224 let cfg_attrs = arg225 .attrs226 .iter()227 .filter(|a| a.path().is_ident("cfg"))228 .cloned()229 .collect();230231 Ok(Self::Normal {232 ty,233 optionality,234 name: ident.map(|v| v.to_string()),235 cfg_attrs,236 })237 }238}239240#[proc_macro_attribute]241pub fn builtin(242 attr: proc_macro::TokenStream,243 item: proc_macro::TokenStream,244) -> proc_macro::TokenStream {245 let attr = parse_macro_input!(attr as BuiltinAttrs);246 let item_fn = parse_macro_input!(item as ItemFn);247248 match builtin_inner(attr, item_fn) {249 Ok(v) => v.into(),250 Err(e) => e.into_compile_error().into(),251 }252}253254#[allow(clippy::too_many_lines)]255fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {256 let ReturnType::Type(_, result) = &fun.sig.output else {257 return Err(Error::new(258 fun.sig.span(),259 "builtin should return something",260 ));261 };262263 let name = fun.sig.ident.to_string();264 let args = fun265 .sig266 .inputs267 .iter_mut()268 .map(|arg| ArgInfo::parse(&name, arg))269 .collect::<Result<Vec<_>>>()?;270271 let params_desc = args.iter().filter_map(|a| match a {272 ArgInfo::Normal {273 optionality,274 name,275 cfg_attrs,276 ..277 } => {278 let name = name279 .as_ref()280 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});281 let default = match optionality {282 Optionality::Required => quote!(ParamDefault::None),283 Optionality::Optional | Optionality::TypeDefault => quote!(ParamDefault::Exists),284 Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),285 };286 Some(quote! {287 #(#cfg_attrs)*288 [#name => #default],289 })290 }291 ArgInfo::Lazy { is_option, name } => {292 let name = name293 .as_ref()294 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});295 Some(quote! {296 [#name => ParamDefault::exists(#is_option)],297 })298 }299 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,300 });301302 let mut id = 0usize;303 let pass = args304 .iter()305 .map(|a| match a {306 ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {307 let cid = id;308 id += 1;309 (quote! {#cid}, a)310 }311 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {312 (quote! {compile_error!("should not use id")}, a)313 }314 })315 .map(|(id, a)| match a {316 ArgInfo::Normal {317 ty,318 optionality,319 name,320 cfg_attrs,321 } => {322 let name = name.as_ref().map_or("<unnamed>", String::as_str);323 let eval = quote! {jrsonnet_evaluator::in_description_frame(324 || format!("argument <{}> evaluation", #name),325 || <#ty as FromUntyped>::from_untyped(value.evaluate()?),326 )?};327 let value = match optionality {328 Optionality::Required => quote! {{329 let value = parsed[#id].as_ref().expect("args shape is checked");330 #eval331 },},332 Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {333 Some(#eval)334 } else {335 None336 },},337 Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {338 #eval339 } else {340 let v: #ty = #expr;341 v342 },},343 Optionality::TypeDefault => quote! {if let Some(value) = &parsed[#id] {344 #eval345 } else {346 let v: #ty = Default::default();347 v348 },},349 };350 quote! {351 #(#cfg_attrs)*352 #value353 }354 }355 ArgInfo::Lazy { is_option, .. } => {356 if *is_option {357 quote! {if let Some(value) = &parsed[#id] {358 Some(value.clone())359 } else {360 None361 },}362 } else {363 quote! {364 parsed[#id].as_ref().expect("args shape is correct").clone(),365 }366 }367 }368 ArgInfo::Context => quote! {ctx.clone(),},369 ArgInfo::Location => quote! {location,},370 ArgInfo::This => quote! {self,},371 });372373 let fields = attr.fields.iter().map(|field| {374 let attrs = &field.attrs;375 let name = &field.name;376 let ty = &field.ty;377 quote! {378 #(#attrs)*379 pub #name: #ty,380 }381 });382383 let name = &fun.sig.ident;384 let vis = &fun.vis;385 let static_derive_copy = if attr.fields.is_empty() {386 quote! {, Copy, Default}387 } else {388 quote! {}389 };390391 Ok(quote! {392 #fun393394 #[doc(hidden)]395 #[allow(non_camel_case_types)]396 #[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]397 #vis struct #name {398 #(#fields)*399 }400 const _: () = {401 use ::jrsonnet_evaluator::{402 State, Val,403 function::{builtin::Builtin, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},404 Result, Context, typed::{Typed, FromUntyped, IntoUntypedResult},405 Span, params, Thunk,406 };407 params!(408 #(#params_desc)*409 );410411 impl Builtin for #name412 where413 Self: 'static414 {415 fn name(&self) -> &str {416 stringify!(#name)417 }418 fn params(&self) -> FunctionSignature {419 PARAMS.with(|p| p.clone())420 }421 #[allow(unused_variables)]422 fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {423 let result: #result = #name(#(#pass)*);424 <_ as IntoUntypedResult>::into_untyped_result(result)425 }426 fn as_any(&self) -> &dyn ::std::any::Any {427 self428 }429 }430 };431 })432}433434#[proc_macro_derive(Typed, attributes(typed))]435pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {436 let input = parse_macro_input!(item as DeriveInput);437438 match derive_typed_inner(input) {439 Ok(v) => v.into(),440 Err(e) => e.to_compile_error().into(),441 }442}443#[proc_macro_derive(IntoUntyped, attributes(typed))]444pub fn derive_into_untyped(item: proc_macro::TokenStream) -> proc_macro::TokenStream {445 let input = parse_macro_input!(item as DeriveInput);446447 match derive_into_untyped_inner(input) {448 Ok(v) => v.into(),449 Err(e) => e.to_compile_error().into(),450 }451}452#[proc_macro_derive(FromUntyped, attributes(typed))]453pub fn derive_from_untyped(item: proc_macro::TokenStream) -> proc_macro::TokenStream {454 let input = parse_macro_input!(item as DeriveInput);455456 match derive_from_untyped_inner(input) {457 Ok(v) => v.into(),458 Err(e) => e.to_compile_error().into(),459 }460}461462struct FormatInput {463 formatting: LitStr,464 arguments: Vec<Expr>,465}466impl Parse for FormatInput {467 fn parse(input: ParseStream) -> Result<Self> {468 let formatting = input.parse()?;469 let mut arguments = Vec::new();470471 while input.peek(Token![,]) {472 input.parse::<Token![,]>()?;473 if input.is_empty() {474 // Trailing comma475 break;476 }477 let expr = input.parse()?;478 arguments.push(expr);479 }480481 if !input.is_empty() {482 return Err(syn::Error::new(input.span(), "unexpected trailing input"));483 }484485 Ok(Self {486 formatting,487 arguments,488 })489 }490}491fn is_format_str(i: &str) -> bool {492 let mut is_plain = true;493 // -1 = {494 // +1 = }495 let mut is_bracket = 0i8;496 for ele in i.chars() {497 match ele {498 '{' if is_bracket == -1 => {499 is_bracket = 0;500 }501 '}' if is_bracket == -1 => {502 is_plain = false;503 break;504 }505 '}' if is_bracket == 1 => {506 is_bracket = 0;507 }508 '{' if is_bracket == 1 => {509 is_plain = false;510 break;511 }512 '{' => {513 is_bracket = -1;514 }515 '}' => {516 is_bracket = 1;517 }518 _ if is_bracket != 0 => {519 is_plain = false;520 break;521 }522 _ => {}523 }524 }525 !is_plain || is_bracket != 0526}527impl FormatInput {528 fn expand(self) -> TokenStream {529 let format = self.formatting;530 if is_format_str(&format.value()) {531 let args = self.arguments;532 quote! {533 ::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))534 }535 } else {536 if let Some(first) = self.arguments.first() {537 return syn::Error::new(538 first.span(),539 "string has no formatting codes, it should not have the arguments",540 )541 .into_compile_error();542 }543 quote! {544 ::jrsonnet_evaluator::IStr::from(#format)545 }546 }547 }548}549550/// `IStr` formatting helper551///552/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`553/// This macro looks for formatting codes in the input string, and uses554/// `format!()` only when necessary555#[proc_macro]556pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {557 let input = parse_macro_input!(input as FormatInput);558 input.expand().into()559}560561/// Create Thunk using closure syntax562#[proc_macro]563#[allow(non_snake_case)]564pub fn Thunk(input: proc_macro::TokenStream) -> proc_macro::TokenStream {565 let input = parse_macro_input!(input as ExprClosure);566567 let span = input.inputs.span();568 let move_check = input.capture.is_none().then(|| {569 quote_spanned! {span => {570 compile_error!("Thunk! needs to be called with move closure");571 }}572 });573574 let (env, closure, args) = syn_dissect_closure::split_env(input);575576 let trace_check = args.iter().map(|el| {577 let span = el.span();578 quote_spanned! {span => ::jrsonnet_evaluator::gc::assert_trace(&#el);}579 });580581 quote! {{582 #move_check583 #(#trace_check)*584 ::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))585 }}.into()586}crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -1,12 +1,11 @@
#![allow(non_snake_case)]
use jrsonnet_evaluator::{
- bail, error,
- function::{builtin, NativeFn},
+ Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val, bail, error,
+ function::{NativeFn, builtin},
runtime_error,
typed::{BoundedUsize, Either2, FromUntyped},
- val::{equals, ArrValue, IndexableVal},
- Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
+ val::{ArrValue, IndexableVal, equals},
};
pub fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
crates/jrsonnet-stdlib/src/compat.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/compat.rs
+++ b/crates/jrsonnet-stdlib/src/compat.rs
@@ -1,6 +1,6 @@
use std::cmp::Ordering;
-use jrsonnet_evaluator::{function::builtin, val::ArrValue, Result, Val};
+use jrsonnet_evaluator::{Result, Val, function::builtin, val::ArrValue};
#[builtin]
#[allow(non_snake_case)]
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -12,7 +12,12 @@
pub use encoding::*;
pub use hash::*;
use jrsonnet_evaluator::{
- IStr, InitialContextBuilder, NumValue, ObjValue, ObjValueBuilder, Source, Thunk, Val, error::Result, function::{CallLocation, FuncVal, builtin_id}, tla::TlaArg, trace::PathResolver, typed::SerializeTypedObj as _
+ IStr, InitialContextBuilder, NumValue, ObjValue, ObjValueBuilder, Source, Thunk, Val,
+ error::Result,
+ function::{CallLocation, FuncVal, builtin_id},
+ tla::TlaArg,
+ trace::PathResolver,
+ typed::SerializeTypedObj as _,
};
use jrsonnet_gcmodule::{Acyclic, Cc, Trace};
use jrsonnet_macros::{IntoUntyped, Typed};
crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -1,7 +1,10 @@
use std::borrow::Cow;
use jrsonnet_evaluator::{
- Error, IStr, ObjValue, Result, ResultExt, Val, bail, ensure_sufficient_stack, in_description_frame, manifest::{ManifestFormat, escape_string_json_buf}, val::ArrValue
+ Error, IStr, ObjValue, Result, ResultExt, Val, bail, ensure_sufficient_stack,
+ in_description_frame,
+ manifest::{ManifestFormat, escape_string_json_buf},
+ val::ArrValue,
};
pub struct TomlFormat<'s> {
@@ -218,14 +221,16 @@
}
first = false;
path.push(k.clone());
- ensure_sufficient_stack(|| in_description_frame(
- || format!("section <{k}> manifestification"),
- || match v {
- Val::Obj(obj) => manifest_table(&obj, path, buf, cur_padding, options),
- Val::Arr(arr) => manifest_table_array(&arr, path, buf, cur_padding, options),
- _ => unreachable!("iterating over sections"),
- },
- ))?;
+ ensure_sufficient_stack(|| {
+ in_description_frame(
+ || format!("section <{k}> manifestification"),
+ || match v {
+ Val::Obj(obj) => manifest_table(&obj, path, buf, cur_padding, options),
+ Val::Arr(arr) => manifest_table_array(&arr, path, buf, cur_padding, options),
+ _ => unreachable!("iterating over sections"),
+ },
+ )
+ })?;
path.pop();
}
Ok(())
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -1,13 +1,12 @@
use std::{cell::RefCell, collections::BTreeSet};
use jrsonnet_evaluator::{
- bail,
+ Either, IStr, ObjValue, ObjValueBuilder, ResultExt, Thunk, Val, bail,
error::{ErrorKind::*, Result},
- function::{builtin, CallLocation, FuncVal},
+ function::{CallLocation, FuncVal, builtin},
manifest::JsonFormat,
typed::{Either2, Either4},
- val::{equals, ArrValue},
- Either, IStr, ObjValue, ObjValueBuilder, ResultExt, Thunk, Val,
+ val::{ArrValue, equals},
};
use jrsonnet_gcmodule::Cc;
crates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -2,11 +2,11 @@
//! However, in our case we instead implement them in native, and implement native functions on top of core for backwards compatibility
use jrsonnet_evaluator::{
+ IStr, NumValue, Result, Val,
function::builtin,
stdlib::std_format,
typed::{Either, Either2},
val::{equals, primitive_equals},
- IStr, NumValue, Result, Val,
};
#[builtin]
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -1,6 +1,6 @@
use std::cmp::Ordering;
-use jrsonnet_evaluator::{function::builtin, val::ArrValue, Result, Thunk, Val};
+use jrsonnet_evaluator::{Result, Thunk, Val, function::builtin, val::ArrValue};
use crate::keyf::KeyF;
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -3,10 +3,9 @@
use std::cmp::Ordering;
use jrsonnet_evaluator::{
- bail,
+ Result, Thunk, Val, bail,
function::builtin,
- val::{equals, ArrValue},
- Result, Thunk, Val,
+ val::{ArrValue, equals},
};
use crate::{eval_on_empty, keyf::KeyF};
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -1,7 +1,11 @@
mod common;
use jrsonnet_evaluator::{
- ContextInitializer, FileImportResolver, InitialContextBuilder, Result, Source, State, Thunk, Val, function::{CallLocation, FuncVal, builtin, builtin::{Builtin}}, trace::PathResolver, typed::FromUntyped
+ ContextInitializer, FileImportResolver, InitialContextBuilder, Result, Source, State, Thunk,
+ Val,
+ function::{CallLocation, FuncVal, builtin, builtin::Builtin},
+ trace::PathResolver,
+ typed::FromUntyped,
};
use jrsonnet_gcmodule::Trace;
use jrsonnet_stdlib::ContextInitializer as StdContextInitializer;
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,5 +1,7 @@
use jrsonnet_evaluator::{
- ContextBuilder, ContextInitializer as ContextInitializerT, InitialContextBuilder, ObjValueBuilder, Result, Thunk, Val, bail, function::{FuncVal, builtin}, Source
+ ContextBuilder, ContextInitializer as ContextInitializerT, InitialContextBuilder,
+ ObjValueBuilder, Result, Source, Thunk, Val, bail,
+ function::{FuncVal, builtin},
};
use jrsonnet_gcmodule::Trace;