difftreelog
perf lesser and cheaper clones
in: master
11 files changed
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -5,7 +5,7 @@
use jsonnet_parser::{el, Arg, ArgsDesc, Expr, LocExpr, ParserSettings};
use location::{offset_to_location, CodeLocation};
use std::env::current_dir;
-use std::{collections::HashMap, path::PathBuf, str::FromStr};
+use std::{collections::HashMap, path::PathBuf, str::FromStr, rc::Rc};
enum Format {
None,
@@ -128,10 +128,10 @@
evaluator.with_stdlib();
}
for ExtStr { name, value } in opts.ext_str.iter().cloned() {
- evaluator.add_ext_var(name, Val::Str(value));
+ evaluator.add_ext_var(name.into(), Val::Str(value.into()));
}
for ExtStr { name, value } in opts.ext_code.iter().cloned() {
- evaluator.add_ext_var(name, evaluator.parse_evaluate_raw(&value).unwrap());
+ evaluator.add_ext_var(name.into(), evaluator.parse_evaluate_raw(&value).unwrap());
}
let mut input = current_dir().unwrap();
input.push(opts.input.clone());
@@ -147,7 +147,7 @@
Val::Func(f) => {
let mut desc_map = HashMap::new();
for ExtStr { name, value } in opts.tla_str.iter().cloned() {
- desc_map.insert(name, el!(Expr::Str(value)));
+ desc_map.insert(name, el!(Expr::Str(value.into())));
}
for ExtStr { name, value } in opts.tla_code.iter().cloned() {
desc_map.insert(
@@ -155,17 +155,17 @@
jsonnet_parser::parse(
&value,
&ParserSettings {
- file_name: PathBuf::new(),
+ file_name: Rc::new(PathBuf::new()),
loc_data: false,
},
)
.unwrap(),
);
}
- evaluator.add_global("__tmp__tlf__".to_owned(), Val::Func(f));
+ evaluator.add_global("__tmp__tlf__".into(), Val::Func(f));
evaluator
.evaluate_raw(el!(Expr::Apply(
- el!(Expr::Var("__tmp__tlf__".to_owned())),
+ el!(Expr::Var("__tmp__tlf__".into())),
ArgsDesc(desc_map.into_iter().map(|(k, v)| Arg(Some(k), v)).collect()),
false,
)))
@@ -178,7 +178,7 @@
if opts.no_stdlib {
evaluator.with_stdlib();
}
- evaluator.add_global("__tmp__to_json__".to_owned(), v);
+ evaluator.add_global("__tmp__to_json__".into(), v);
let v = evaluator.parse_evaluate_raw(&format!(
"std.manifestJsonEx(__tmp__to_json__, \"{}\")",
" ".repeat(opts.line_padding),
@@ -195,7 +195,7 @@
if opts.no_stdlib {
evaluator.with_stdlib();
}
- evaluator.add_global("__tmp__to_yaml__".to_owned(), v);
+ evaluator.add_global("__tmp__to_yaml__".into(), v);
let v = evaluator
.parse_evaluate_raw("std.manifestYamlDoc(__tmp__to_yaml__, \" \")");
match v {
crates/jsonnet-evaluator/build.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/build.rs
+++ b/crates/jsonnet-evaluator/build.rs
@@ -34,7 +34,7 @@
Member::Field(FieldMember {
name: FieldName::Fixed(name),
..
- }) if name == "join"
+ }) if **name == *"join"
)
})
.collect(),
crates/jsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/ctx.rs
+++ b/crates/jsonnet-evaluator/src/ctx.rs
@@ -16,7 +16,7 @@
dollar: Option<ObjValue>,
this: Option<ObjValue>,
super_obj: Option<ObjValue>,
- bindings: LayeredHashMap<String, LazyVal>,
+ bindings: LayeredHashMap<Rc<str>, LazyVal>,
}
pub struct Context(Rc<ContextInternals>);
impl Debug for Context {
@@ -53,9 +53,9 @@
}))
}
- pub fn binding(&self, name: &str) -> Result<LazyVal> {
- self.0.bindings.get(name).cloned().ok_or_else(|| {
- create_error::<()>(Error::UnknownVariable(name.to_owned()))
+ pub fn binding(&self, name: Rc<str>) -> Result<LazyVal> {
+ self.0.bindings.get(&name).cloned().ok_or_else(|| {
+ create_error::<()>(Error::UnknownVariable(name))
.err()
.unwrap()
})
@@ -67,7 +67,7 @@
ctx.unwrap()
}
- pub fn with_var(&self, name: String, value: Val) -> Result<Context> {
+ pub fn with_var(&self, name: Rc<str>, value: Val) -> Result<Context> {
let mut new_bindings = HashMap::with_capacity(1);
new_bindings.insert(name, resolved_lazy_val!(value));
self.extend(new_bindings, None, None, None)
@@ -75,7 +75,7 @@
pub fn extend(
&self,
- new_bindings: HashMap<String, LazyVal>,
+ new_bindings: HashMap<Rc<str>, LazyVal>,
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
@@ -97,7 +97,7 @@
}
pub fn extend_unbound(
&self,
- new_bindings: HashMap<String, LazyBinding>,
+ new_bindings: HashMap<Rc<str>, LazyBinding>,
new_dollar: Option<ObjValue>,
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
crates/jsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/error.rs
+++ b/crates/jsonnet-evaluator/src/error.rs
@@ -6,20 +6,20 @@
pub enum Error {
VariableIsNotDefined(String),
TypeMismatch(&'static str, Vec<ValType>, ValType),
- NoSuchField(String),
+ NoSuchField(Rc<str>),
- UnknownVariable(String),
+ UnknownVariable(Rc<str>),
UnknownFunctionParameter(String),
- BindingParameterASecondTime(String),
+ BindingParameterASecondTime(Rc<str>),
TooManyArgsFunctionHas(usize),
- FunctionParameterNotBoundInCall(String),
+ FunctionParameterNotBoundInCall(Rc<str>),
- UndefinedExternalVariable(String),
+ UndefinedExternalVariable(Rc<str>),
FieldMustBeStringGot(ValType),
- AttemptedIndexAnArrayWithString(String),
+ AttemptedIndexAnArrayWithString(Rc<str>),
ValueIndexMustBeTypeGot(ValType, ValType, ValType),
CantIndexInto(ValType),
@@ -31,7 +31,7 @@
ImportNotSupported(PathBuf, PathBuf),
ImportSyntaxError(jsonnet_parser::ParseError),
- RuntimeError(String),
+ RuntimeError(Rc<str>),
StackOverflow,
FractionalIndex,
DivisionByZero,
crates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth14 rc::Rc,14 rc::Rc,15};15};161617pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {17pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {18 let b = b.clone();18 let b = b.clone();19 if let Some(params) = &b.params {19 if let Some(params) = &b.params {20 let params = params.clone();20 let params = params.clone();54pub fn evaluate_field_name(54pub fn evaluate_field_name(55 context: Context,55 context: Context,56 field_name: &jsonnet_parser::FieldName,56 field_name: &jsonnet_parser::FieldName,57) -> Result<Option<String>> {57) -> Result<Option<Rc<str>>> {58 Ok(match field_name {58 Ok(match field_name {59 jsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),59 jsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),60 jsonnet_parser::FieldName::Dyn(expr) => {60 jsonnet_parser::FieldName::Dyn(expr) => {61 let value = evaluate(context, expr)?.unwrap_if_lazy()?;61 let lazy = evaluate(context, expr)?;62 let value = lazy.unwrap_if_lazy()?;62 if matches!(value, Val::Null) {63 if matches!(value, Val::Null) {63 None64 None64 } else {65 } else {808181pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {82pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {82 Ok(match (a, b) {83 Ok(match (a, b) {83 (Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),84 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),848585 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)86 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)86 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o)),87 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),87 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n)),88 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),888989 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?)),90 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?).into()),90 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s)),91 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s).into()),919292 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),93 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),93 (Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),94 (Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),94 (Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),95 (Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),95 _ => panic!("can't add: {:?} and {:?}", a, b),96 _ => panic!("can't add: {:?} and {:?}", a, b),96 })97 })117 Ok(match (a, op, b) {118 Ok(match (a, op, b) {118 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,119 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,119120120 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),121 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),121122122 // Bool X Bool123 // Bool X Bool123 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),124 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),165 })166 })166}167}167168168future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);169future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);169future_wrapper!(ObjValue, FutureObjValue);170future_wrapper!(ObjValue, FutureObjValue);170171171pub fn evaluate_comp<T>(172pub fn evaluate_comp<T>(186 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {187 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {187 Val::Arr(list) => {188 Val::Arr(list) => {188 let mut out = Vec::new();189 let mut out = Vec::new();189 for item in list {190 for item in list.iter() {190 let item = item.clone().unwrap_if_lazy()?;191 let item = item.unwrap_if_lazy()?;191 out.push(evaluate_comp(192 out.push(evaluate_comp(192 context.with_var(var.clone(), item)?,193 context.with_var(var.clone(), item.clone())?,193 value,194 value,194 &specs[1..],195 &specs[1..],195 )?);196 )?);202 })203 })203}204}204205206pub fn evaluate_member_list_object(context: Context, members: &Vec<Member>) -> Result<ObjValue> {207 let new_bindings = FutureNewBindings::new();208 let future_this = FutureObjValue::new();209 let context_creator = context_creator!(210 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {211 Ok(context.extend_unbound(212 new_bindings.clone().unwrap(),213 context.dollar().clone().or_else(||this.clone()),214 Some(this.unwrap()),215 super_obj216 )?)217 })218 );219 {220 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();221 for (n, b) in members222 .iter()223 .filter_map(|m| match m {224 Member::BindStmt(b) => Some(b.clone()),225 _ => None,226 })227 .map(|b| evaluate_binding(&b, context_creator.clone()))228 {229 bindings.insert(n, b);230 }231 new_bindings.fill(bindings);232 }233234 let mut new_members = BTreeMap::new();235 for member in members.iter() {236 match member {237 Member::Field(FieldMember {238 name,239 plus,240 params: None,241 visibility,242 value,243 }) => {244 let name = evaluate_field_name(context.clone(), &name)?;245 if name.is_none() {246 continue;247 }248 let name = name.unwrap();249 new_members.insert(250 name.clone(),251 ObjMember {252 add: *plus,253 visibility: *visibility,254 invoke: LazyBinding::Bindable(Rc::new(255 closure!(clone name, clone value, clone context_creator, |this, super_obj| {256 Ok(LazyVal::new_resolved(push(&value.1, "object field", ||{257 let context = context_creator.0(this, super_obj)?;258 evaluate(259 context,260 &value,261 )262 })?))263 }),264 )),265 },266 );267 }268 Member::Field(FieldMember {269 name,270 params: Some(params),271 value,272 ..273 }) => {274 let name = evaluate_field_name(context.clone(), &name)?;275 if name.is_none() {276 continue;277 }278 let name = name.unwrap();279 new_members.insert(280 name,281 ObjMember {282 add: false,283 visibility: Visibility::Hidden,284 invoke: LazyBinding::Bindable(Rc::new(285 closure!(clone value, clone context_creator, clone params, |this, super_obj| {205// TODO: Asserts286 // TODO: Assert287 Ok(LazyVal::new_resolved(evaluate_method(288 context_creator.0(this, super_obj)?,289 params.clone(),290 value.clone(),291 )))292 }),293 )),294 },295 );296 }297 Member::BindStmt(_) => {}298 Member::AssertStmt(_) => {}299 }300 }301 Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))302}303206pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {304pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {207 Ok(match object {305 Ok(match object {208 ObjBody::MemberList(members) => {306 ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,209 let new_bindings = FutureNewBindings::new();210 let future_this = FutureObjValue::new();211 let context_creator = context_creator!(212 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {213 Ok(context.extend_unbound(214 new_bindings.clone().unwrap(),215 context.dollar().clone().or_else(||this.clone()),216 Some(this.unwrap()),217 super_obj218 )?)219 })220 );221 {222 let mut bindings: HashMap<String, LazyBinding> = HashMap::new();223 for (n, b) in members224 .iter()225 .filter_map(|m| match m {226 Member::BindStmt(b) => Some(b.clone()),227 _ => None,228 })229 .map(|b| evaluate_binding(&b, context_creator.clone()))230 {231 bindings.insert(n, b);232 }233 new_bindings.fill(bindings);234 }235236 let mut new_members = BTreeMap::new();237 for member in members.into_iter() {238 match member {239 Member::Field(FieldMember {240 name,241 plus,242 params: None,243 visibility,244 value,245 }) => {246 let name = evaluate_field_name(context.clone(), &name)?;247 if name.is_none() {248 continue;249 }250 let name = name.unwrap();251 new_members.insert(252 name.clone(),253 ObjMember {254 add: plus,255 visibility: visibility.clone(),256 invoke: LazyBinding::Bindable(Rc::new(257 closure!(clone name, clone value, clone context_creator, |this, super_obj| {258 Ok(LazyVal::new_resolved(push(&value.1, "object field", ||{259 let context = context_creator.0(this, super_obj)?;260 evaluate(261 context,262 &value,263 )?.unwrap_if_lazy()264 })?))265 }),266 )),267 },268 );269 }270 Member::Field(FieldMember {271 name,272 params: Some(params),273 value,274 ..275 }) => {276 let name = evaluate_field_name(context.clone(), &name)?;277 if name.is_none() {278 continue;279 }280 let name = name.unwrap();281 new_members.insert(282 name,283 ObjMember {284 add: false,285 visibility: Visibility::Hidden,286 invoke: LazyBinding::Bindable(Rc::new(287 closure!(clone value, clone context_creator, |this, super_obj| {288 // TODO: Assert289 Ok(LazyVal::new_resolved(evaluate_method(290 context_creator.0(this, super_obj)?,291 params.clone(),292 value.clone(),293 )))294 }),295 )),296 },297 );298 }299 Member::BindStmt(_) => {}300 Member::AssertStmt(_) => {}301 }302 }303 future_this.fill(ObjValue::new(None, Rc::new(new_members)))304 }305 ObjBody::ObjComp {307 ObjBody::ObjComp(obj) => {306 pre_locals,307 key,308 value,309 post_locals,310 compspecs,311 } => {312 let future_this = FutureObjValue::new();308 let future_this = FutureObjValue::new();313 let mut new_members = BTreeMap::new();309 let mut new_members = BTreeMap::new();314 for (k, v) in evaluate_comp(310 for (k, v) in evaluate_comp(325 )?)321 )?)326 })322 })327 );323 );328 let mut bindings: HashMap<String, LazyBinding> = HashMap::new();324 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();329 for (n, b) in pre_locals325 for (n, b) in obj326 .pre_locals330 .iter()327 .iter()331 .chain(post_locals.iter())328 .chain(obj.post_locals.iter())332 .map(|b| evaluate_binding(b, context_creator.clone()))329 .map(|b| evaluate_binding(b, context_creator.clone()))333 {330 {334 bindings.insert(n, b);331 bindings.insert(n, b);335 }332 }336 let bindings = new_bindings.fill(bindings);333 let bindings = new_bindings.fill(bindings);337 let ctx = ctx.extend_unbound(bindings, None, None, None)?;334 let ctx = ctx.extend_unbound(bindings, None, None, None)?;338 let key = evaluate(ctx.clone(), &key)?;335 let key = evaluate(ctx.clone(), &obj.key)?;339 let value = LazyBinding::Bindable(Rc::new(336 let value = LazyBinding::Bindable(Rc::new(340 closure!(clone ctx, clone value, |this, _super_obj| {337 closure!(clone ctx, clone obj.value, |this, _super_obj| {341 Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))338 Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))342 }),339 }),343 ));340 ));344341345 Ok((key, value))342 Ok((key, value))346 },343 },347 &compspecs,344 &obj.compspecs,348 )?345 )?349 .unwrap()346 .unwrap()350 {347 {394 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,391 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,395 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,392 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,396 Var(name) => push(loc, "var", || {393 Var(name) => push(loc, "var", || {397 Val::Lazy(context.binding(&name)?).unwrap_if_lazy()394 Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?)398 })?,395 })?,399 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {396 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {400 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;397 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;411 evaluate(context, index)?,408 evaluate(context, index)?,412 ) {409 ) {413 (Val::Obj(v), Val::Str(s)) => {410 (Val::Obj(v), Val::Str(s)) => {414 if let Some(v) = v.get(&s)? {411 if let Some(v) = v.get(s.clone())? {415 v.unwrap_if_lazy()?412 v.unwrap_if_lazy()?416 } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {413 } else if let Some(Val::Str(n)) = v.get("__intristic_namespace__".into())? {417 Val::Intristic(n, s)414 Val::Intristic(n, s)418 } else {415 } else {419 create_error(crate::Error::NoSuchField(s))?416 create_error(crate::Error::NoSuchField(s))?443 n.value_type()?,440 n.value_type()?,444 ))?,441 ))?,445442446 (Val::Str(s), Val::Num(n)) => {443 (Val::Str(s), Val::Num(n)) => Val::Str(447 Val::Str(s.chars().skip(n as usize).take(1).collect())444 s.chars()448 }445 .skip(n as usize)446 .take(1)447 .collect::<String>()448 .into(),449 ),449 (Val::Str(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(450 (Val::Str(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(450 ValType::Str,451 ValType::Str,451 ValType::Num,452 ValType::Num,456 }457 }457 }458 }458 LocalExpr(bindings, returned) => {459 LocalExpr(bindings, returned) => {459 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();460 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();460 let future_context = Context::new_future();461 let future_context = Context::new_future();461462462 let context_creator = context_creator!(463 let context_creator = context_creator!(484 })485 })485 )));486 )));486 }487 }487 Val::Arr(out)488 Val::Arr(Rc::new(out))488 }489 }489 ArrComp(expr, compspecs) => Val::Arr(490 ArrComp(expr, compspecs) => Val::Arr(490 // First compspec should be forspec, so no "None" possible here491 // First compspec should be forspec, so no "None" possible here491 evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap(),492 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),492 ),493 ),493 Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),494 Obj(body) => Val::Obj(evaluate_object(context, body)?),494 ObjExtend(s, t) => evaluate_add_op(495 ObjExtend(s, t) => evaluate_add_op(495 &evaluate(context.clone(), s)?,496 &evaluate(context.clone(), s)?,496 &Val::Obj(evaluate_object(context, t.clone())?),497 &Val::Obj(evaluate_object(context, t)?),497 )?,498 )?,498 Apply(value, args, tailstrict) => {499 Apply(value, args, tailstrict) => {499 let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;500 let lazy = evaluate(context.clone(), value)?;501 let value = lazy.unwrap_if_lazy()?;500 match value {502 match value {501 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {503 Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {502 // arr/string/function504 // arr/string/function519 ("std", "type") => {521 ("std", "type") => {520 assert_eq!(args.len(), 1);522 assert_eq!(args.len(), 1);521 let expr = &args.get(0).unwrap().1;523 let expr = &args.get(0).unwrap().1;522 Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())524 Val::Str(evaluate(context, expr)?.value_type()?.name().into())523 }525 }524 // length, idx=>any526 // length, idx=>any525 ("std", "makeArray") => {527 ("std", "makeArray") => {532 let mut out = Vec::with_capacity(v as usize);534 let mut out = Vec::with_capacity(v as usize);533 for i in 0..v as usize {535 for i in 0..v as usize {534 let call_ctx =536 let call_ctx =535 Context::new().with_var("v".to_owned(), Val::Num(i as f64))?;537 Context::new().with_var("v".into(), Val::Num(i as f64))?;536 out.push(d.evaluate(538 out.push(d.evaluate(537 call_ctx,539 call_ctx,538 &ArgsDesc(vec![Arg(None, el!(Expr::Var("v".to_owned())))]),540 &ArgsDesc(vec![Arg(None, el!(Expr::Var("v".into())))]),539 true,541 true,540 )?)542 )?)541 }543 }542 Val::Arr(out)544 Val::Arr(Rc::new(out))543 } else {545 } else {544 panic!("bad makeArray call");546 panic!("bad makeArray call");545 }547 }564 evaluate(context.clone(), &args[0].1)?,566 evaluate(context.clone(), &args[0].1)?,565 evaluate(context, &args[1].1)?,567 evaluate(context, &args[1].1)?,566 ) {568 ) {567 Val::Arr(569 Val::Arr(Rc::new(568 body.fields_visibility()570 body.fields_visibility()569 .into_iter()571 .into_iter()570 .filter(|(_k, v)| *v || include_hidden)572 .filter(|(_k, v)| *v || include_hidden)571 .map(|(k, _v)| Val::Str(k))573 .map(|(k, _v)| Val::Str(k))572 .collect(),574 .collect(),573 )575 ))574 } else {576 } else {575 panic!("bad objectFieldsEx call");577 panic!("bad objectFieldsEx call");576 }578 }587 body.fields_visibility()589 body.fields_visibility()588 .into_iter()590 .into_iter()589 .filter(|(_k, v)| *v || include_hidden)591 .filter(|(_k, v)| *v || include_hidden)590 .any(|(k, _v)| k == name),592 .any(|(k, _v)| *k == *name),591 )593 )592 } else {594 } else {593 panic!("bad objectHasEx call");595 panic!("bad objectHasEx call");664 evaluate(context.clone(), &args[0].1)?,666 evaluate(context.clone(), &args[0].1)?,665 evaluate(context.clone(), &args[1].1)?,667 evaluate(context.clone(), &args[1].1)?,666 ) {668 ) {667 Val::Arr(669 Val::Arr(Rc::new(668 arr.into_iter()670 arr.iter()669 .filter(|e| {671 .filter(|e| {670 predicate672 predicate671 .evaluate_values(context.clone(), &[e.clone()])673 .evaluate_values(context.clone(), &[e.clone()])672 .unwrap()674 .unwrap()673 .try_cast_bool("filter predicate")675 .try_cast_bool("filter predicate")674 .unwrap()676 .unwrap()675 })677 })678 .cloned()676 .collect(),679 .collect(),677 )680 ))678 } else {681 } else {679 panic!("bad filter call");682 panic!("bad filter call");680 }683 }681 }684 }682 // faster685 // faster683 ("std", "join") => {686 ("std", "join") => {684 assert_eq!(args.len(), 2);687 assert_eq!(args.len(), 2);685 let joiner = evaluate(context.clone(), &args[0].1)?.unwrap_if_lazy()?;688 let joiner = evaluate(context.clone(), &args[0].1)?;686 let items = evaluate(context, &args[1].1)?.unwrap_if_lazy()?;689 let items = evaluate(context, &args[1].1)?;687 match (joiner, items) {690 match (joiner.unwrap_if_lazy()?, items.unwrap_if_lazy()?) {688 (Val::Arr(joiner_items), Val::Arr(items)) => {691 (Val::Arr(joiner_items), Val::Arr(items)) => {689 // TODO: Minimal size should be known692 // TODO: Minimal size should be known690 let mut out = Vec::new();693 let mut out = Vec::new();691694692 let mut first = true;695 let mut first = true;693 for item in items {696 for item in items.iter().cloned() {694 if let Val::Arr(items) = item.unwrap_if_lazy()? {697 if let Val::Arr(items) = item.unwrap_if_lazy()? {695 if !first {698 if !first {699 out.reserve(joiner_items.len());696 out.extend(joiner_items.iter().cloned());700 out.extend(joiner_items.iter().cloned());697 }701 }698 first = false;702 first = false;703 out.reserve(items.len());699 out.extend(items);704 out.extend(items.iter().cloned());700 } else {705 } else {701 panic!("all array items should be arrays")706 panic!("all array items should be arrays")702 }707 }703 }708 }704709705 Val::Arr(out)710 Val::Arr(Rc::new(out))706 }711 }707 (Val::Str(joiner), Val::Arr(items)) => {712 (Val::Str(joiner), Val::Arr(items)) => {708 let mut out = String::new();713 let mut out = String::new();709714710 let mut first = true;715 let mut first = true;711 for item in items {716 for item in items.iter().cloned() {712 if let Val::Str(item) = item.unwrap_if_lazy()? {717 if let Val::Str(item) = item.unwrap_if_lazy()? {713 if !first {718 if !first {714 out += &joiner;719 out += &joiner;720 }725 }721 }726 }722727723 Val::Str(out)728 Val::Str(out.into())724 }729 }725 (joiner, items) => panic!("bad join call: {:?} {:?}", joiner, items),730 (joiner, items) => panic!("bad join call: {:?} {:?}", joiner, items),726 }731 }776 }781 }777 }782 }778 Import(path) => {783 Import(path) => {779 let mut import_location = loc784 let mut tmp = loc780 .clone()785 .clone()781 .expect("imports can't be used without loc_data")786 .expect("imports can't be used without loc_data")782 .0787 .0;783 .clone();788 let import_location = Rc::make_mut(&mut tmp);784 import_location.pop();789 import_location.pop();785 with_state(|s| s.import_file(&import_location, path))?790 with_state(|s| s.import_file(&import_location, path))?786 }791 }787 ImportStr(path) => {792 ImportStr(path) => {788 let mut import_location = loc793 let mut tmp = loc789 .clone()794 .clone()790 .expect("imports can't be used without loc_data")795 .expect("imports can't be used without loc_data")791 .0796 .0;792 .clone();797 let import_location = Rc::make_mut(&mut tmp);793 import_location.pop();798 import_location.pop();794 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)799 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)795 }800 }crates/jsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/function.rs
+++ b/crates/jsonnet-evaluator/src/function.rs
@@ -35,7 +35,7 @@
let mut positioned_args = vec![None; params.0.len()];
for (id, arg) in args.iter().enumerate() {
let idx = if let Some(name) = &arg.0 {
- params.iter().position(|p| &p.0 == name).ok_or_else(|| {
+ params.iter().position(|p| *p.0 == *name).ok_or_else(|| {
create_error::<()>(Error::UnknownFunctionParameter(name.clone()))
.err()
.unwrap()
crates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/lib.rs
+++ b/crates/jsonnet-evaluator/src/lib.rs
@@ -65,11 +65,11 @@
/// Contains file source codes and evaluated results for imports and pretty
/// printing stacktraces
files: RefCell<HashMap<PathBuf, FileData>>,
- str_files: RefCell<HashMap<PathBuf, String>>,
- globals: RefCell<HashMap<String, Val>>,
+ str_files: RefCell<HashMap<PathBuf, Rc<str>>>,
+ globals: RefCell<HashMap<Rc<str>, Val>>,
/// Values to use with std.extVar
- ext_vars: RefCell<HashMap<String, Val>>,
+ ext_vars: RefCell<HashMap<Rc<str>, Val>>,
settings: EvaluationSettings,
import_resolver: Box<dyn ImportResolver>,
@@ -87,7 +87,7 @@
with_state(|s| s.error(err))
}
pub(crate) fn push<T>(
- e: &Option<Rc<ExprLocation>>,
+ e: &Option<ExprLocation>,
comment: &str,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
@@ -185,11 +185,14 @@
})?;
self.evaluate_file(&file_path)
}
- pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<String> {
+ pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<str>> {
let path = self.0.import_resolver.resolve_file(from, path)?;
if !self.0.str_files.borrow().contains_key(&path) {
let file_str = self.0.import_resolver.load_file_contents(&path)?;
- self.0.str_files.borrow_mut().insert(path.clone(), file_str);
+ self.0
+ .str_files
+ .borrow_mut()
+ .insert(path.clone(), file_str.into());
}
Ok(self.0.str_files.borrow().get(&path).cloned().unwrap())
}
@@ -210,10 +213,10 @@
self.run_in_state(|| evaluate(self.create_default_context()?, &code))
}
- pub fn add_global(&self, name: String, value: Val) {
+ pub fn add_global(&self, name: Rc<str>, value: Val) {
self.0.globals.borrow_mut().insert(name, value);
}
- pub fn add_ext_var(&self, name: String, value: Val) {
+ pub fn add_ext_var(&self, name: Rc<str>, value: Val) {
self.0.ext_vars.borrow_mut().insert(name, value);
}
@@ -236,14 +239,14 @@
.unwrap();
}
let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();
- self.add_global("std".to_owned(), val);
+ self.add_global("std".into(), val);
});
self
}
pub fn create_default_context(&self) -> Result<Context> {
let globals = self.0.globals.borrow();
- let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();
+ let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();
for (name, value) in globals.iter() {
new_bindings.insert(
name.clone(),
@@ -255,7 +258,7 @@
pub fn push<T>(
&self,
- e: Rc<ExprLocation>,
+ e: ExprLocation,
comment: String,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
@@ -362,7 +365,7 @@
let evaluator = EvaluationState::default();
evaluator.with_stdlib();
let val = evaluator.parse_evaluate_raw($str).unwrap();
- evaluator.add_global("__tmp__to_yaml__".to_owned(), val);
+ evaluator.add_global("__tmp__to_yaml__".into(), val);
evaluator
.parse_evaluate_raw("std.manifestJsonEx(__tmp__to_yaml__, \"\")")
.unwrap()
crates/jsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/obj.rs
+++ b/crates/jsonnet-evaluator/src/obj.rs
@@ -18,9 +18,10 @@
#[derive(Debug)]
pub struct ObjValueInternals {
super_obj: Option<ObjValue>,
- this_entries: Rc<BTreeMap<String, ObjMember>>,
- value_cache: RefCell<HashMap<String, Val>>,
+ this_entries: Rc<BTreeMap<Rc<str>, ObjMember>>,
+ value_cache: RefCell<HashMap<Rc<str>, Val>>,
}
+#[derive(Clone)]
pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);
impl Debug for ObjValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -43,7 +44,7 @@
impl ObjValue {
pub fn new(
super_obj: Option<ObjValue>,
- this_entries: Rc<BTreeMap<String, ObjMember>>,
+ this_entries: Rc<BTreeMap<Rc<str>, ObjMember>>,
) -> ObjValue {
ObjValue(Rc::new(ObjValueInternals {
super_obj,
@@ -57,7 +58,7 @@
Some(v) => ObjValue::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),
}
}
- pub fn enum_fields(&self, handler: &impl Fn(&str, &Visibility)) {
+ pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {
if let Some(s) = &self.0.super_obj {
s.enum_fields(handler);
}
@@ -65,7 +66,7 @@
handler(&name, &member.visibility);
}
}
- pub fn fields_visibility(&self) -> IndexMap<String, bool> {
+ pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {
let out = Rc::new(RefCell::new(IndexMap::new()));
self.enum_fields(&|name, visibility| {
let mut out = out.borrow_mut();
@@ -85,16 +86,20 @@
});
Rc::try_unwrap(out).unwrap().into_inner()
}
- pub fn get(&self, key: &str) -> Result<Option<Val>> {
- if let Some(v) = self.0.value_cache.borrow().get(key) {
+ pub fn visible_fields(&self) -> Vec<Rc<str>> {
+ self.fields_visibility()
+ .into_iter()
+ .filter(|(_k, v)| *v)
+ .map(|(k, _)| k)
+ .collect()
+ }
+ pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {
+ if let Some(v) = self.0.value_cache.borrow().get(&key) {
return Ok(Some(v.clone()));
}
- if let Some(v) = self.get_raw(key, self)? {
+ if let Some(v) = self.get_raw(&key, self)? {
let v = v.unwrap_if_lazy()?;
- self.0
- .value_cache
- .borrow_mut()
- .insert(key.to_owned(), v.clone());
+ self.0.value_cache.borrow_mut().insert(key, v.clone());
Ok(Some(v))
} else {
Ok(None)
@@ -108,10 +113,10 @@
.evaluate()?,
)),
(Some(k), Some(s)) => {
- let our = k
+ let lazy = k
.invoke
- .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?
- .evaluate()?;
+ .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?;
+ let our = lazy.evaluate()?;
if k.add {
s.get_raw(key, real_this)?
.map_or(Ok(Some(our.clone())), |v| {
@@ -124,11 +129,6 @@
(None, Some(s)) => s.get_raw(key, real_this),
(None, None) => Ok(None),
}
- }
-}
-impl Clone for ObjValue {
- fn clone(&self) -> Self {
- ObjValue(self.0.clone())
}
}
impl PartialEq for ObjValue {
crates/jsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/val.rs
+++ b/crates/jsonnet-evaluator/src/val.rs
@@ -81,7 +81,7 @@
}
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ValType {
Bool,
Null,
@@ -115,42 +115,46 @@
pub enum Val {
Bool(bool),
Null,
- Str(String),
+ Str(Rc<str>),
Num(f64),
Lazy(LazyVal),
- Arr(Vec<Val>),
+ Arr(Rc<Vec<Val>>),
Obj(ObjValue),
Func(FuncDesc),
// Library functions implemented in native
- Intristic(String, String),
+ Intristic(Rc<str>, Rc<str>),
+}
+macro_rules! matches_unwrap {
+ ($e: expr, $p: pat, $r: expr) => {
+ match $e {
+ $p => $r,
+ _ => panic!("no match"),
+ }
+ };
}
impl Val {
+ pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {
+ let this_type = self.value_type()?;
+ if this_type != val_type {
+ create_error(Error::TypeMismatch(context, vec![val_type], this_type))
+ } else {
+ Ok(())
+ }
+ }
pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
- match self.unwrap_if_lazy()? {
- Val::Bool(v) => Ok(v),
- v => create_error(Error::TypeMismatch(
- context,
- vec![ValType::Bool],
- v.value_type()?,
- )),
- }
+ self.assert_type(context, ValType::Bool)?;
+ Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))
}
- pub fn try_cast_str(self, context: &'static str) -> Result<String> {
- match self.unwrap_if_lazy()? {
- Val::Str(v) => Ok(v),
- v => create_error(Error::TypeMismatch(
- context,
- vec![ValType::Str],
- v.value_type()?,
- )),
- }
+ pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {
+ self.assert_type(context, ValType::Str)?;
+ Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))
}
- pub fn unwrap_if_lazy(self) -> Result<Self> {
+ pub fn unwrap_if_lazy(&self) -> Result<Self> {
Ok(if let Val::Lazy(v) = self {
v.evaluate()?.unwrap_if_lazy()?
} else {
- self
+ self.clone()
})
}
pub fn value_type(&self) -> Result<ValType> {
@@ -166,26 +170,30 @@
Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
})
}
- pub fn into_json(self, padding: usize) -> Result<String> {
+ pub fn into_json(self, padding: usize) -> Result<Rc<str>> {
with_state(|s| {
let ctx = s
.create_default_context()?
- .with_var("__tmp__to_json__".to_owned(), self)?;
- if let Val::Str(result) = evaluate(
+ .with_var("__tmp__to_json__".into(), self)?;
+ Ok(evaluate(
ctx,
&el!(Expr::Apply(
el!(Expr::Index(
- el!(Expr::Var("std".to_owned())),
- el!(Expr::Str("manifestJsonEx".to_owned()))
+ el!(Expr::Var("std".into())),
+ el!(Expr::Str("manifestJsonEx".into()))
)),
ArgsDesc(vec![
- Arg(None, el!(Expr::Var("__tmp__to_json__".to_owned()))),
- Arg(None, el!(Expr::Str(" ".repeat(padding))))
+ Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),
+ Arg(None, el!(Expr::Str(" ".repeat(padding).into())))
]),
false
)),
- )? {
- Ok(result)
+ )?
+ .try_cast_str("to json")?)
+ })
+ }
+}
+
} else {
unreachable!()
}
crates/jsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jsonnet-parser/src/expr.rs
+++ b/crates/jsonnet-parser/src/expr.rs
@@ -1,15 +1,15 @@
use serde::{Deserialize, Serialize};
use std::{fmt::Debug, ops::Deref, path::PathBuf, rc::Rc};
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum FieldName {
/// {fixed: 2}
- Fixed(String),
+ Fixed(Rc<str>),
/// {["dyn"+"amic"]: 3}
Dyn(LocExpr),
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Visibility {
/// :
Normal,
@@ -19,10 +19,10 @@
Unhide,
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct FieldMember {
pub name: FieldName,
pub plus: bool,
@@ -31,7 +31,7 @@
pub value: LocExpr,
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum Member {
Field(FieldMember),
BindStmt(BindSpec),
@@ -71,11 +71,11 @@
}
/// name, default value
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub struct Param(pub String, pub Option<LocExpr>);
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+pub struct Param(pub Rc<str>, pub Option<LocExpr>);
/// Defined function parameters
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub struct ParamsDesc(pub Vec<Param>);
+pub struct ParamsDesc(pub Rc<Vec<Param>>);
impl Deref for ParamsDesc {
type Target = Vec<Param>;
fn deref(&self) -> &Self::Target {
@@ -83,9 +83,9 @@
}
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Arg(pub Option<String>, pub LocExpr);
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct ArgsDesc(pub Vec<Arg>);
impl Deref for ArgsDesc {
type Target = Vec<Arg>;
@@ -96,35 +96,38 @@
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BindSpec {
- pub name: String,
+ pub name: Rc<str>,
pub params: Option<ParamsDesc>,
pub value: LocExpr,
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct IfSpecData(pub LocExpr);
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub struct ForSpecData(pub String, pub LocExpr);
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+pub struct ForSpecData(pub Rc<str>, pub LocExpr);
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum CompSpec {
IfSpec(IfSpecData),
ForSpec(ForSpecData),
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+pub struct ObjComp {
+ pub pre_locals: Vec<BindSpec>,
+ pub key: LocExpr,
+ pub value: LocExpr,
+ pub post_locals: Vec<BindSpec>,
+ pub compspecs: Vec<CompSpec>,
+}
+
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum ObjBody {
MemberList(Vec<Member>),
- ObjComp {
- pre_locals: Vec<BindSpec>,
- key: LocExpr,
- value: LocExpr,
- post_locals: Vec<BindSpec>,
- compspecs: Vec<CompSpec>,
- },
+ ObjComp(ObjComp),
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Copy)]
pub enum LiteralType {
This,
Super,
@@ -134,7 +137,7 @@
False,
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct SliceDesc {
pub start: Option<LocExpr>,
pub end: Option<LocExpr>,
@@ -142,16 +145,16 @@
}
/// Syntax base
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum Expr {
Literal(LiteralType),
/// String value: "hello"
- Str(String),
+ Str(Rc<str>),
/// Number: 1, 2.0, 2e+20
Num(f64),
/// Variable name: test
- Var(String),
+ Var(Rc<str>),
/// Array of expressions: [1, 2, "Hello"]
Arr(Vec<LocExpr>),
crates/jsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jsonnet-parser/src/lib.rs
+++ b/crates/jsonnet-parser/src/lib.rs
@@ -39,7 +39,7 @@
/// Reserved word followed by any non-alphanumberic
rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()
- rule id() -> String = quiet!{ !reserved() s:$(alpha() (alpha() / digit())*) {s.to_owned()}} / expected!("<identifier>")
+ rule id() = quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")
rule keyword(id: &'static str)
= ##parse_string_literal(id) end_of_ident()
@@ -47,7 +47,7 @@
rule l(s: &ParserSettings, x: rule<Expr>) -> LocExpr
= start:position!() v:x() end:position!() {loc_expr!(v, s.loc_data, (s.file_name.clone(), start, end))}
- pub rule param(s: &ParserSettings) -> expr::Param = name:id() expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name, expr) }
+ pub rule param(s: &ParserSettings) -> expr::Param = name:$(id()) expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name.into(), expr) }
pub rule params(s: &ParserSettings) -> expr::ParamsDesc
= params:(param(s) ** comma()) {
let mut defaults_started = false;
@@ -55,12 +55,12 @@
defaults_started = defaults_started || param.1.is_some();
assert_eq!(defaults_started, param.1.is_some(), "defauld parameters should be used after all positionals");
}
- expr::ParamsDesc(params)
+ expr::ParamsDesc(Rc::new(params))
}
- / { expr::ParamsDesc(Vec::new()) }
+ / { expr::ParamsDesc(Rc::new(Vec::new())) }
pub rule arg(s: &ParserSettings) -> expr::Arg
- = name:id() _ "=" _ expr:expr(s) {expr::Arg(Some(name), expr)}
+ = name:$(id()) _ "=" _ expr:expr(s) {expr::Arg(Some(name.into()), expr)}
/ expr:expr(s) {expr::Arg(None, expr)}
pub rule args(s: &ParserSettings) -> expr::ArgsDesc
= args:arg(s) ** comma() comma()? {
@@ -74,8 +74,8 @@
/ { expr::ArgsDesc(Vec::new()) }
pub rule bind(s: &ParserSettings) -> expr::BindSpec
- = name:id() _ "=" _ expr:expr(s) {expr::BindSpec{name, params: None, value: expr}}
- / name:id() _ "(" _ params:params(s) _ ")" _ "=" _ expr:expr(s) {expr::BindSpec{name, params: Some(params), value: expr}}
+ = name:$(id()) _ "=" _ expr:expr(s) {expr::BindSpec{name:name.into(), params: None, value: expr}}
+ / name:$(id()) _ "(" _ params:params(s) _ ")" _ "=" _ expr:expr(s) {expr::BindSpec{name:name.into(), params: Some(params), value: expr}}
pub rule assertion(s: &ParserSettings) -> expr::AssertStmt
= keyword("assert") _ cond:expr(s) msg:(_ ":" _ e:expr(s) {e})? { expr::AssertStmt(cond, msg) }
@@ -95,8 +95,8 @@
/ string_block()
pub rule field_name(s: &ParserSettings) -> expr::FieldName
- = name:id() {expr::FieldName::Fixed(name)}
- / name:string() {expr::FieldName::Fixed(name)}
+ = name:$(id()) {expr::FieldName::Fixed(name.into())}
+ / name:string() {expr::FieldName::Fixed(name.into())}
/ "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}
pub rule visibility() -> expr::Visibility
= ":::" {expr::Visibility::Unhide}
@@ -125,35 +125,41 @@
/ field:field(s) {expr::Member::Field(field)}
pub rule objinside(s: &ParserSettings) -> expr::ObjBody
= pre_locals:(b: obj_local(s) comma() {b})* "[" _ key:expr(s) _ "]" _ ":" _ value:expr(s) post_locals:(comma() b:obj_local(s) {b})* _ forspec:forspec(s) others:(_ rest:compspec(s) {rest})? {
- expr::ObjBody::ObjComp {
+ let mut compspecs = vec![CompSpec::ForSpec(forspec)];
+ compspecs.extend(others.unwrap_or_default());
+ expr::ObjBody::ObjComp(expr::ObjComp{
pre_locals,
key,
value,
post_locals,
- compspecs: [vec![CompSpec::ForSpec(forspec)], others.unwrap_or_default()].concat(),
- }
+ compspecs,
+ })
}
/ members:(member(s) ** comma()) comma()? {expr::ObjBody::MemberList(members)}
pub rule ifspec(s: &ParserSettings) -> IfSpecData
= keyword("if") _ expr:expr(s) {IfSpecData(expr)}
pub rule forspec(s: &ParserSettings) -> ForSpecData
- = keyword("for") _ id:id() _ keyword("in") _ cond:expr(s) {ForSpecData(id, cond)}
+ = keyword("for") _ id:$(id()) _ keyword("in") _ cond:expr(s) {ForSpecData(id.into(), cond)}
pub rule compspec(s: &ParserSettings) -> Vec<expr::CompSpec>
= s:(i:ifspec(s) { expr::CompSpec::IfSpec(i) } / f:forspec(s) {expr::CompSpec::ForSpec(f)} ) ** _ {s}
pub rule local_expr(s: &ParserSettings) -> LocExpr
= l(s,<keyword("local") _ binds:bind(s) ** comma() _ ";" _ expr:expr(s) { Expr::LocalExpr(binds, expr) }>)
pub rule string_expr(s: &ParserSettings) -> LocExpr
- = l(s, <s:string() {Expr::Str(s)}>)
+ = l(s, <s:string() {Expr::Str(s.into())}>)
pub rule obj_expr(s: &ParserSettings) -> LocExpr
= l(s,<"{" _ body:objinside(s) _ "}" {Expr::Obj(body)}>)
pub rule array_expr(s: &ParserSettings) -> LocExpr
= l(s,<"[" _ elems:(expr(s) ** comma()) _ comma()? "]" {Expr::Arr(elems)}>)
pub rule array_comp_expr(s: &ParserSettings) -> LocExpr
- = l(s,<"[" _ expr:expr(s) _ comma()? _ forspec:forspec(s) _ others:(others: compspec(s) _ {others})? "]" {Expr::ArrComp(expr, [vec![CompSpec::ForSpec(forspec)], others.unwrap_or_default()].concat())}>)
+ = l(s,<"[" _ expr:expr(s) _ comma()? _ forspec:forspec(s) _ others:(others: compspec(s) _ {others})? "]" {
+ let mut specs = vec![CompSpec::ForSpec(forspec)];
+ specs.extend(others.unwrap_or_default());
+ Expr::ArrComp(expr, specs)
+ }>)
pub rule number_expr(s: &ParserSettings) -> LocExpr
= l(s,<n:number() { expr::Expr::Num(n) }>)
pub rule var_expr(s: &ParserSettings) -> LocExpr
- = l(s,<n:id() { expr::Expr::Var(n) }>)
+ = l(s,<n:$(id()) { expr::Expr::Var(n.into()) }>)
pub rule if_then_else_expr(s: &ParserSettings) -> LocExpr
= l(s,<cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{
cond,
@@ -219,16 +225,16 @@
--
a:(@) _ "==" _ b:@ {loc_expr_todo!(Expr::Apply(
el!(Expr::Index(
- el!(Expr::Var("std".to_owned())),
- el!(Expr::Str("equals".to_owned()))
+ el!(Expr::Var("std".into())),
+ el!(Expr::Str("equals".into()))
)),
ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
true
))}
a:(@) _ "!=" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, el!(Expr::Apply(
el!(Expr::Index(
- el!(Expr::Var("std".to_owned())),
- el!(Expr::Str("equals".to_owned()))
+ el!(Expr::Var("std".into())),
+ el!(Expr::Str("equals".into()))
)),
ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
true
@@ -240,8 +246,8 @@
a:(@) _ ">=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gte, b))}
a:(@) _ keyword("in") _ b:@ {loc_expr_todo!(Expr::Apply(
el!(Expr::Index(
- el!(Expr::Var("std".to_owned())),
- el!(Expr::Str("objectHasEx".to_owned()))
+ el!(Expr::Var("std".into())),
+ el!(Expr::Str("objectHasEx".into()))
)), ArgsDesc(vec![Arg(None, b), Arg(None, a), Arg(None, el!(Expr::Literal(LiteralType::True)))]),
true
))}
@@ -256,8 +262,8 @@
a:(@) _ "/" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Div, b))}
a:(@) _ "%" _ b:@ {loc_expr_todo!(Expr::Apply(
el!(Expr::Index(
- el!(Expr::Var("std".to_owned())),
- el!(Expr::Str("mod".to_owned()))
+ el!(Expr::Var("std".into())),
+ el!(Expr::Str("mod".into()))
)), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
true
))}
@@ -268,8 +274,8 @@
--
a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Apply(
el!(Expr::Index(
- el!(Expr::Var("std".to_owned())),
- el!(Expr::Str("slice".to_owned())),
+ el!(Expr::Var("std".into())),
+ el!(Expr::Str("slice".into())),
)),
ArgsDesc(vec![
Arg(None, a),
@@ -279,7 +285,7 @@
]),
true,
))}
- a:(@) _ "." _ s:id() {loc_expr_todo!(Expr::Index(a, el!(Expr::Str(s))))}
+ a:(@) _ "." _ s:$(id()) {loc_expr_todo!(Expr::Index(a, el!(Expr::Str(s.into()))))}
a:(@) _ "[" _ s:expr(s) _ "]" {loc_expr_todo!(Expr::Index(a, s))}
a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {loc_expr_todo!(Expr::Apply(a, args, ts.is_some()))}
a:(@) _ "{" _ body:objinside(s) _ "}" {loc_expr_todo!(Expr::ObjExtend(a, body))}
@@ -352,7 +358,7 @@
fn multiline_string() {
assert_eq!(
parse!("|||\n Hello world!\n a\n|||"),
- el!(Expr::Str("Hello world!\n a\n".to_owned())),
+ el!(Expr::Str("Hello world!\n a\n".into())),
)
}
@@ -369,20 +375,20 @@
fn string_escaping() {
assert_eq!(
parse!(r#""Hello, \"world\"!""#),
- el!(Expr::Str(r#"Hello, "world"!"#.to_owned())),
+ el!(Expr::Str(r#"Hello, "world"!"#.into())),
);
assert_eq!(
parse!(r#"'Hello \'world\'!'"#),
- el!(Expr::Str("Hello 'world'!".to_owned())),
+ el!(Expr::Str("Hello 'world'!".into())),
);
- assert_eq!(parse!(r#"'\\\\'"#), el!(Expr::Str("\\\\".to_owned())),);
+ assert_eq!(parse!(r#"'\\\\'"#), el!(Expr::Str("\\\\".into())),);
}
#[test]
fn string_unescaping() {
assert_eq!(
parse!(r#""Hello\nWorld""#),
- el!(Expr::Str("Hello\nWorld".to_owned())),
+ el!(Expr::Str("Hello\nWorld".into())),
);
}
@@ -390,7 +396,7 @@
fn string_verbantim() {
assert_eq!(
parse!(r#"@"Hello\n""World""""#),
- el!(Expr::Str("Hello\\n\"World\"".to_owned())),
+ el!(Expr::Str("Hello\\n\"World\"".into())),
);
}
@@ -489,16 +495,13 @@
parse!("[std.deepJoin(x) for x in arr]"),
el!(ArrComp(
el!(Apply(
- el!(Index(
- el!(Var("std".to_owned())),
- el!(Str("deepJoin".to_owned()))
- )),
- ArgsDesc(vec![Arg(None, el!(Var("x".to_owned())))]),
+ el!(Index(el!(Var("std".into())), el!(Str("deepJoin".into())))),
+ ArgsDesc(vec![Arg(None, el!(Var("x".into())))]),
false,
)),
vec![CompSpec::ForSpec(ForSpecData(
- "x".to_owned(),
- el!(Var("arr".to_owned()))
+ "x".into(),
+ el!(Var("arr".into()))
))]
)),
)
@@ -508,7 +511,7 @@
fn reserved() {
use Expr::*;
assert_eq!(parse!("null"), el!(Literal(LiteralType::Null)));
- assert_eq!(parse!("nulla"), el!(Var("nulla".to_owned())));
+ assert_eq!(parse!("nulla"), el!(Var("nulla".into())));
}
#[test]
@@ -522,9 +525,9 @@
assert_eq!(
parse!("!a && !b"),
el!(BinaryOp(
- el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned())))),
+ el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into())))),
BinaryOpType::And,
- el!(UnaryOp(UnaryOpType::Not, el!(Var("b".to_owned()))))
+ el!(UnaryOp(UnaryOpType::Not, el!(Var("b".into()))))
))
);
}
@@ -535,9 +538,9 @@
assert_eq!(
parse!("!a / !b"),
el!(BinaryOp(
- el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned())))),
+ el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into())))),
BinaryOpType::Div,
- el!(UnaryOp(UnaryOpType::Not, el!(Var("b".to_owned()))))
+ el!(UnaryOp(UnaryOpType::Not, el!(Var("b".into()))))
))
);
}
@@ -549,7 +552,7 @@
parse!("!!a"),
el!(UnaryOp(
UnaryOpType::Not,
- el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned()))))
+ el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into()))))
))
)
}