difftreelog
feat(macro) pass call location to builtins
in: master
8 files changed
cmds/jrsonnet-fmt/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/cmds/jrsonnet-fmt/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "jrsonnet-fmt"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+dprint-core = "0.47.1"
+jrsonnet-parser = { path = "../../crates/jrsonnet-parser" }
cmds/jrsonnet-fmt/src/main.rsdiffbeforeafterboth--- /dev/null
+++ b/cmds/jrsonnet-fmt/src/main.rs
@@ -0,0 +1,373 @@
+use std::path::PathBuf;
+
+use dprint_core::formatting::{PrintItems, PrintOptions, Signal};
+use jrsonnet_parser::{
+ ArgsDesc, BinaryOpType, BindSpec, Expr, FieldName, LocExpr, Member, ObjBody, Param, ParamsDesc,
+ ParserSettings, Visibility,
+};
+
+pub trait Printable {
+ fn print(&self) -> PrintItems;
+}
+
+macro_rules! pi {
+ (@i; $($t:tt)*) => {{
+ let mut o = PrintItems::new();
+ pi!(@s; o: $($t)*);
+ o
+ }};
+ (@s; $o:ident: str($e:expr) $($t:tt)*) => {{
+ $o.push_str($e);
+ pi!(@s; $o: $($t)*);
+ }};
+ (@s; $o:ident: nl $($t:tt)*) => {{
+ $o.push_signal(Signal::NewLine);
+ pi!(@s; $o: $($t)*);
+ }};
+ (@s; $o:ident: >i $($t:tt)*) => {{
+ $o.push_signal(Signal::StartIndent);
+ pi!(@s; $o: $($t)*);
+ }};
+ (@s; $o:ident: <i $($t:tt)*) => {{
+ $o.push_signal(Signal::FinishIndent);
+ pi!(@s; $o: $($t)*);
+ }};
+ (@s; $o:ident: {$expr:expr} $($t:tt)*) => {{
+ $o.extend($expr.print());
+ pi!(@s; $o: $($t)*);
+ }};
+ (@s; $o:ident: if ($e:expr)($($then:tt)*) $($t:tt)*) => {{
+ if $e {
+ pi!(@s; $o: $($then)*);
+ }
+ pi!(@s; $o: $($t)*);
+ }};
+ (@s; $o:ident: ifelse ($e:expr)($($then:tt)*)($($else:tt)*) $($t:tt)*) => {{
+ if $e {
+ pi!(@s; $o: $($then)*);
+ } else {
+ pi!(@s; $o: $($else)*);
+ }
+ pi!(@s; $o: $($t)*);
+ }};
+ (@s; $i:ident:) => {}
+}
+macro_rules! p {
+ (new: $($t:tt)*) => {
+ pi!(@i; $($t)*)
+ };
+ ($o:ident: $($t:tt)*) => {
+ pi!(@s; $o: $($t)*)
+ };
+}
+
+impl Printable for FieldName {
+ fn print(&self) -> PrintItems {
+ match self {
+ FieldName::Fixed(f) => {
+ p!(new: str(&f))
+ }
+ FieldName::Dyn(_) => todo!(),
+ }
+ }
+}
+
+impl Printable for Visibility {
+ fn print(&self) -> PrintItems {
+ match self {
+ Visibility::Normal => p!(new: str(":")),
+ Visibility::Hidden => p!(new: str("::")),
+ Visibility::Unhide => p!(new: str(":::")),
+ }
+ }
+}
+
+impl Printable for BinaryOpType {
+ fn print(&self) -> PrintItems {
+ let o = self.to_string();
+ p!(new: str(&o))
+ }
+}
+
+impl<T: Printable> Printable for Option<T> {
+ fn print(&self) -> PrintItems {
+ if let Some(v) = self {
+ v.print()
+ } else {
+ PrintItems::new()
+ }
+ }
+}
+
+impl Printable for Param {
+ fn print(&self) -> PrintItems {
+ p!(new:
+ str(&self.0)
+ if(self.1.is_some())(str(" = ") {self.1})
+ )
+ }
+}
+
+impl Printable for ParamsDesc {
+ fn print(&self) -> PrintItems {
+ let mut out = PrintItems::new();
+ for (i, item) in self.0.iter().enumerate() {
+ if i != 0 {
+ p!(out: str(", "));
+ }
+ out.extend(item.print());
+ }
+ out
+ }
+}
+
+impl Printable for ArgsDesc {
+ fn print(&self) -> PrintItems {
+ let mut out = PrintItems::new();
+ let mut first = Some(());
+ for u in self.unnamed.iter() {
+ if first.take().is_none() {
+ p!(out: str(", "));
+ }
+ p!(out: {u})
+ }
+ for (n, u) in self.named.iter() {
+ if first.take().is_none() {
+ p!(out: str(", "));
+ }
+ p!(out: str(&n) str(" = ") {u})
+ }
+
+ out
+ }
+}
+
+impl Printable for BindSpec {
+ fn print(&self) -> PrintItems {
+ p!(new: str(&self.name) if(self.params.is_some())(str("(") {self.params} str(")")) str(" = ") {self.value})
+ }
+}
+
+struct StrExpr<'s>(&'s str);
+
+impl<'s> Printable for StrExpr<'s> {
+ fn print(&self) -> PrintItems {
+ todo!()
+ }
+}
+
+impl Printable for ObjBody {
+ fn print(&self) -> PrintItems {
+ let mut pi = PrintItems::new();
+ p!(pi: str("{"));
+ match self {
+ ObjBody::MemberList(m) => {
+ if !m.is_empty() {
+ p!(pi: nl > i);
+ for m in m {
+ match m {
+ Member::Field(f) => {
+ p!(pi:
+ {f.name} {f.params}
+ if(f.plus)(str("+"))
+ {f.visibility} str(" ")
+ {f.value}
+ str(",") nl
+ );
+ }
+ Member::BindStmt(s) => {
+ p!(pi: str("local ") {s} str(",") nl)
+ }
+ Member::AssertStmt(a) => p!(pi: str("assert ") {a.0} if(a.1.is_some())(
+ str(" : ") {a.1}
+ ) str(",") nl),
+ }
+ }
+ p!(pi: <i);
+ } else {
+ p!(pi: str(" "))
+ }
+ }
+ ObjBody::ObjComp(_) => todo!(),
+ }
+ p!(pi: str("}"));
+ pi
+ }
+}
+
+impl Printable for Expr {
+ fn print(&self) -> PrintItems {
+ let mut pi = PrintItems::new();
+ match self {
+ Expr::Literal(l) => match l {
+ jrsonnet_parser::LiteralType::This => p!(pi: str("self")),
+ jrsonnet_parser::LiteralType::Super => p!(pi: str("super")),
+ jrsonnet_parser::LiteralType::Dollar => p!(pi: str("$")),
+ jrsonnet_parser::LiteralType::Null => p!(pi: str("null")),
+ jrsonnet_parser::LiteralType::True => p!(pi: str("true")),
+ jrsonnet_parser::LiteralType::False => p!(pi: str("false")),
+ },
+ Expr::Str(s) => {
+ p!(pi: str("\"") str(s) str("\""))
+ }
+ Expr::Num(n) => {
+ let n = n.to_string();
+ p!(pi: str(&n));
+ }
+ Expr::Var(v) => p!(pi: str(&v)),
+ Expr::Arr(a) => {
+ p!(pi: str("["));
+ for (i, v) in a.iter().enumerate() {
+ if i != 0 {
+ p!(pi: str(", "));
+ }
+ p!(pi: {v})
+ }
+ p!(pi: str("]"));
+ }
+ Expr::ArrComp(_, _) => todo!(),
+ Expr::Obj(o) => {
+ p!(pi: {o});
+ }
+ Expr::ObjExtend(a, b) => p!(pi: {a} str(" ") {b}),
+ Expr::Parened(v) => {
+ if let Expr::Parened(_) = &v.0 as &Expr {
+ p!(pi: {v})
+ } else {
+ p!(pi: str("(") {v} str(")"))
+ }
+ }
+ Expr::UnaryOp(_, _) => todo!(),
+ Expr::BinaryOp(a, o, b) => {
+ p!(pi:
+ {a} str(" ") if(!matches!(&b.0 as &Expr, Expr::Obj(_)))({o} str(" ")) {b}
+ )
+ }
+ Expr::AssertExpr(_, _) => todo!(),
+ Expr::LocalExpr(s, v) => {
+ p!(pi:
+ str("local") nl >i
+ );
+ for spec in s.iter() {
+ p!(pi: {spec} str(";") nl)
+ }
+ p!(pi:
+ <i
+ {v}
+ );
+ }
+ Expr::Import(i) => {
+ let v = i.to_str().unwrap();
+ p!(pi: str("import \"") str(&v) str("\""));
+ }
+ Expr::ImportStr(_) => todo!(),
+ Expr::ErrorStmt(_) => todo!(),
+ Expr::Apply(f, a, t) => p!(pi:
+ {f} str("(") {a} str(")") if(*t)(str("tailstrict"))
+ ),
+ Expr::Index(a, b) => p!(pi: {a} str("[") {b} str("]")),
+ Expr::Function(_, _) => todo!(),
+ Expr::Intrinsic(_) => todo!(),
+ Expr::IfElse {
+ cond,
+ cond_then,
+ cond_else,
+ } => p!(pi:
+ str("if ") {cond.0} str(" then") ifelse(cond_else.is_some())(
+ nl >i
+ {cond_then} nl
+ <i str("else") nl >i
+ {cond_else}
+ <i
+ )(str(" ") {cond_then})
+ ),
+ Expr::Slice(v, d) => {
+ p!(pi:
+ {v}
+ str("[") {d.start} str(":") {d.end}
+ if(d.step.is_some())(
+ str(":")
+ {d.step}
+ )
+ str("]")
+ )
+ }
+ }
+ pi
+ }
+}
+
+impl Printable for LocExpr {
+ fn print(&self) -> PrintItems {
+ self.0.print()
+ }
+}
+
+fn main() {
+ let parsed = jrsonnet_parser::parse(
+ r#"
+
+
+ # Edit me!
+ local b = import "b.libsonnet"; # comment
+ local a = import "a.libsonnet";
+
+ local f(x,y)=x+y;
+
+
+ local Template = {z: "foo"};
+
+ Template + {
+ local
+
+ h = 3,
+ assert self.a == 1
+
+ : "error",
+ "f": ((((((3)))))) ,
+ "g g":
+ f(4,2),
+ arr: [[
+ 1, 2,
+ ],
+ 3,
+ {
+ b: {
+ c: {
+ k: [16]
+ }
+ }
+ }
+ ],
+ m: a[1::],
+ m: b[::],
+ k: if a == b then
+
+
+ 2
+
+ else Template {}
+ }
+
+
+"#,
+ &ParserSettings {
+ file_name: PathBuf::from("example").into(),
+ },
+ )
+ .unwrap();
+
+ let o = dprint_core::formatting::format(
+ || {
+ let print_items = parsed.print();
+ print_items
+ },
+ PrintOptions {
+ indent_width: 2,
+ max_width: 100,
+ use_tabs: false,
+ new_line_text: "\n",
+ },
+ );
+ println!("{}", o);
+}
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -5,14 +5,13 @@
equals,
error::{Error::*, Result},
operator::evaluate_mod_op,
- parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,
+ primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,
IndexableVal, Val,
};
use format::{format_arr, format_obj};
use gcmodule::Cc;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, ExprLocation};
-use jrsonnet_types::ty;
use serde::Deserialize;
use serde_yaml::DeserializingQuirks;
use std::{
@@ -466,19 +465,19 @@
Ok(format!("{:x}", md5::compute(&str.as_bytes())))
}
-fn builtin_trace(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "trace", args, 2, [
- 0, str: ty!(string) => Val::Str;
- 1, rest: ty!(any);
- ], {
- eprint!("TRACE:");
- with_state(|s|{
- let locs = s.map_source_locations(&loc.0, &[loc.1]);
- eprint!(" {}:{}", loc.0.file_name().unwrap().to_str().unwrap(), locs[0].line);
- });
- eprintln!(" {}", str);
- Ok(rest)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_trace(#[location] loc: &ExprLocation, str: IStr, rest: Any) -> Result<Any> {
+ eprint!("TRACE:");
+ with_state(|s| {
+ let locs = s.map_source_locations(&loc.0, &[loc.1]);
+ eprint!(
+ " {}:{}",
+ loc.0.file_name().unwrap().to_str().unwrap(),
+ locs[0].line
+ );
+ });
+ eprintln!(" {}", str);
+ Ok(rest) as Result<Any>
}
#[jrsonnet_macros::builtin]
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -16,8 +16,6 @@
pub enum Error {
#[error("intrinsic not found: {0}")]
IntrinsicNotFound(IStr),
- #[error("argument reordering in intrisics not supported yet")]
- IntrinsicArgumentReorderingIsNotSupportedYet,
#[error("operator {0} does not operate on type {1}")]
UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -311,45 +311,3 @@
Ok(body_ctx.extend(out, None, None, None))
}
-
-#[macro_export]
-macro_rules! parse_args {
- ($ctx: expr, $fn_name: expr, $args: expr, $total_args: expr, [
- $($id: expr, $name: ident: $ty: expr $(=>$match: path)?);+ $(;)?
- ], $handler:block) => {{
- use $crate::{error::Error::*, throw, evaluate, push_description_frame, typed::CheckType};
-
- let args = $args;
- if args.unnamed.len() + args.named.len() > $total_args {
- throw!(TooManyArgsFunctionHas($total_args));
- }
- $(
- if args.unnamed.len() + args.named.len() <= $id {
- throw!(FunctionParameterNotBoundInCall(stringify!($name).into()));
- }
- // Is named
- let $name = if $id >= $args.unnamed.len() {
- let named = &args.named[$id - $args.unnamed.len()];
- if &named.0 != stringify!($name) {
- throw!(IntrinsicArgumentReorderingIsNotSupportedYet);
- }
- &named.1
- } else {
- &$args.unnamed[$id]
- };
- let $name = push_description_frame(|| format!("evaluating builtin argument {}", stringify!($name)), || {
- let value = evaluate($ctx.clone(), &$name)?;
- $ty.check(&value)?;
- Ok(value)
- })?;
- $(
- let $name = if let $match(v) = $name {
- v
- } else {
- unreachable!();
- };
- )?
- )+
- ($handler as crate::Result<_>)
- }};
-}
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -1,6 +1,10 @@
use proc_macro2::Span;
use quote::quote;
-use syn::{parse_macro_input, FnArg, Ident, ItemFn, Pat};
+use syn::{parse_macro_input, FnArg, Ident, ItemFn, Pat, PatType};
+
+fn is_location_arg(t: &PatType) -> bool {
+ t.attrs.iter().any(|a| a.path.is_ident("location"))
+}
#[proc_macro_attribute]
pub fn builtin(
@@ -8,14 +12,11 @@
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
// syn::ItemFn::parse(input)
- let fun: ItemFn = parse_macro_input!(item);
+ let mut fun: ItemFn = parse_macro_input!(item);
- let inner_name = Ident::new("inner", Span::call_site());
- let mut inner_fun = fun.clone();
- inner_fun.sig.ident = inner_name.clone();
let result = match fun.sig.output {
syn::ReturnType::Default => panic!("builtin should return something"),
- syn::ReturnType::Type(_, ty) => ty,
+ syn::ReturnType::Type(_, ref ty) => ty.clone(),
};
let params = fun
@@ -26,6 +27,7 @@
FnArg::Receiver(_) => unreachable!(),
FnArg::Typed(t) => t,
})
+ .filter(|a| !is_location_arg(a))
.map(|t| {
let ident = match &t.pat as &Pat {
Pat::Ident(i) => i.ident.to_string(),
@@ -39,38 +41,53 @@
has_default: #optional,
}
}
- });
+ })
+ .collect::<Vec<_>>();
let args = fun
.sig
.inputs
- .iter()
+ .iter_mut()
.map(|i| match i {
FnArg::Receiver(_) => unreachable!(),
FnArg::Typed(t) => t,
})
.map(|t| {
- let ident = match &t.pat as &Pat {
- Pat::Ident(i) => i.ident.to_string(),
- _ => panic!("only idents supported yet"),
- };
- let ty = &t.ty;
- quote! {{
- let value = parsed.get(#ident).unwrap();
+ let count_before = t.attrs.len();
+ t.attrs.retain(|a| !a.path.is_ident("location"));
+ let count_after = t.attrs.len();
+ let is_location = count_before != count_after;
+ if is_location {
+ quote! {{
+ loc
+ }}
+ } else {
+ let ident = match &t.pat as &Pat {
+ Pat::Ident(i) => i.ident.to_string(),
+ _ => panic!("only idents supported yet"),
+ };
+ let ty = &t.ty;
+ quote! {{
+ let value = parsed.get(#ident).unwrap();
- jrsonnet_evaluator::push_description_frame(
- || format!("argument <{}> evaluation", #ident),
- || <#ty>::try_from(value.evaluate()?),
- )?
- }}
- });
+ jrsonnet_evaluator::push_description_frame(
+ || format!("argument <{}> evaluation", #ident),
+ || <#ty>::try_from(value.evaluate()?),
+ )?
+ }}
+ }
+ }).collect::<Vec<_>>();
+
+ let inner_name = Ident::new("inner", Span::call_site());
+ let mut inner_fun = fun.clone();
+ inner_fun.sig.ident = inner_name.clone();
let attrs = &fun.attrs;
let vis = &fun.vis;
let name = &fun.sig.ident;
(quote! {
#(#attrs)*
- #vis fn #name(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
+ #vis fn #name(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
#inner_fun
use jrsonnet_evaluator::function::BuiltinParam;
const PARAMS: &'static [BuiltinParam] = &[
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth1#![allow(clippy::redundant_closure_call)]23use gcmodule::Trace;4use std::fmt::Display;56#[macro_export]7macro_rules! ty {8 ((Array<number>)) => {{9 $crate::ComplexValType::ArrayRef(&$crate::ComplexValType::Simple($crate::ValType::Num))10 }};11 ((Array<ubyte>)) => {{12 $crate::ComplexValType::ArrayRef(&$crate::ComplexValType::BoundedNumber(Some(0.0), Some(255.0)))13 }};14 (array) => {15 $crate::ComplexValType::Simple($crate::ValType::Arr)16 };17 (boolean) => {18 $crate::ComplexValType::Simple($crate::ValType::Bool)19 };20 (null) => {21 $crate::ComplexValType::Simple($crate::ValType::Null)22 };23 (string) => {24 $crate::ComplexValType::Simple($crate::ValType::Str)25 };26 (char) => {27 $crate::ComplexValType::Char28 };29 (number) => {30 $crate::ComplexValType::Simple($crate::ValType::Num)31 };32 (BoundedNumber<($min:expr), ($max:expr)>) => {{33 $crate::ComplexValType::BoundedNumber($min, $max)34 }};35 (object) => {36 $crate::ComplexValType::Simple($crate::ValType::Obj)37 };38 (any) => {39 $crate::ComplexValType::Any40 };41 (function) => {42 $crate::ComplexValType::Simple($crate::ValType::Func)43 };44 (($($a:tt) |+)) => {{45 static CONTENTS: &'static [&'static $crate::ComplexValType] = &[46 $(&ty!($a)),+47 ];48 $crate::ComplexValType::UnionRef(CONTENTS)49 }};50 (($($a:tt) &+)) => {{51 static CONTENTS: &'static [&'static $crate::ComplexValType] = &[52 $(&ty!($a)),+53 ];54 $crate::ComplexValType::SumRef(CONTENTS)55 }};56}5758#[test]59fn test() {60 assert_eq!(61 ty!((Array<number>)),62 ComplexValType::ArrayRef(&ComplexValType::Simple(ValType::Num))63 );64 assert_eq!(ty!(array), ComplexValType::Simple(ValType::Arr));65 assert_eq!(ty!(any), ComplexValType::Any);66 assert_eq!(67 ty!((string | number)),68 ComplexValType::UnionRef(&[69 &ComplexValType::Simple(ValType::Str),70 &ComplexValType::Simple(ValType::Num)71 ])72 );73 assert_eq!(74 format!("{}", ty!(((string & number) | (object & null)))),75 "string & number | object & null"76 );77 assert_eq!(format!("{}", ty!((string | array))), "string | array");78 assert_eq!(79 format!("{}", ty!(((string & number) | array))),80 "string & number | array"81 );82}8384#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]85pub enum ValType {86 Bool,87 Null,88 Str,89 Num,90 Arr,91 Obj,92 Func,93}9495impl ValType {96 pub const fn name(&self) -> &'static str {97 use ValType::*;98 match self {99 Bool => "boolean",100 Null => "null",101 Str => "string",102 Num => "number",103 Arr => "array",104 Obj => "object",105 Func => "function",106 }107 }108}109110impl Display for ValType {111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {112 write!(f, "{}", self.name())113 }114}115116#[derive(Debug, Clone, PartialEq, Trace)]117#[skip_trace]118pub enum ComplexValType {119 Any,120 Char,121 Simple(ValType),122 BoundedNumber(Option<f64>, Option<f64>),123 Array(Box<ComplexValType>),124 ArrayRef(&'static ComplexValType),125 ObjectRef(&'static [(&'static str, ComplexValType)]),126 Union(Vec<ComplexValType>),127 UnionRef(&'static [&'static ComplexValType]),128 Sum(Vec<ComplexValType>),129 SumRef(&'static [&'static ComplexValType]),130}131132impl From<ValType> for ComplexValType {133 fn from(s: ValType) -> Self {134 Self::Simple(s)135 }136}137138fn write_union<'i>(139 f: &mut std::fmt::Formatter<'_>,140 is_union: bool,141 union: impl Iterator<Item = &'i ComplexValType>,142) -> std::fmt::Result {143 for (i, v) in union.enumerate() {144 let should_add_braces =145 matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);146 if i != 0 {147 write!(f, " {} ", if is_union { '|' } else { '&' })?;148 }149 if should_add_braces {150 write!(f, "(")?;151 }152 write!(f, "{}", v)?;153 if should_add_braces {154 write!(f, ")")?;155 }156 }157 Ok(())158}159160fn print_array(a: &ComplexValType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {161 if *a == ComplexValType::Any {162 write!(f, "array")?163 } else {164 write!(f, "Array<{}>", a)?165 }166 Ok(())167}168169impl Display for ComplexValType {170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {171 match self {172 ComplexValType::Any => write!(f, "any")?,173 ComplexValType::Simple(s) => write!(f, "{}", s)?,174 ComplexValType::Char => write!(f, "char")?,175 ComplexValType::BoundedNumber(a, b) => write!(176 f,177 "BoundedNumber<{}, {}>",178 a.map(|e| e.to_string()).unwrap_or_else(|| "".into()),179 b.map(|e| e.to_string()).unwrap_or_else(|| "".into())180 )?,181 ComplexValType::ArrayRef(a) => print_array(a, f)?,182 ComplexValType::Array(a) => print_array(a, f)?,183 ComplexValType::ObjectRef(fields) => {184 write!(f, "{{")?;185 for (i, (k, v)) in fields.iter().enumerate() {186 if i != 0 {187 write!(f, ", ")?;188 }189 write!(f, "{}: {}", k, v)?;190 }191 write!(f, "}}")?;192 }193 ComplexValType::Union(v) => write_union(f, true, v.iter())?,194 ComplexValType::UnionRef(v) => write_union(f, true, v.iter().map(|v| *v))?,195 ComplexValType::Sum(v) => write_union(f, false, v.iter())?,196 ComplexValType::SumRef(v) => write_union(f, false, v.iter().map(|v| *v))?,197 };198 Ok(())199 }200}201202peg::parser! {203pub grammar parser() for str {204 rule number() -> f64205 = n:$(['0'..='9']+) { n.parse().unwrap() }206207 rule any_ty() -> ComplexValType = "any" { ComplexValType::Any }208 rule char_ty() -> ComplexValType = "character" { ComplexValType::Char }209 rule bool_ty() -> ComplexValType = "boolean" { ComplexValType::Simple(ValType::Bool) }210 rule null_ty() -> ComplexValType = "null" { ComplexValType::Simple(ValType::Null) }211 rule str_ty() -> ComplexValType = "string" { ComplexValType::Simple(ValType::Str) }212 rule num_ty() -> ComplexValType = "number" { ComplexValType::Simple(ValType::Num) }213 rule simple_array_ty() -> ComplexValType = "array" { ComplexValType::Simple(ValType::Arr) }214 rule simple_object_ty() -> ComplexValType = "object" { ComplexValType::Simple(ValType::Obj) }215 rule simple_function_ty() -> ComplexValType = "function" { ComplexValType::Simple(ValType::Func) }216217 rule array_ty() -> ComplexValType218 = "Array<" t:ty() ">" { ComplexValType::Array(Box::new(t)) }219220 rule bounded_number_ty() -> ComplexValType221 = "BoundedNumber<" a:number() ", " b:number() ">" { ComplexValType::BoundedNumber(Some(a), Some(b)) }222223 rule ty_basic() -> ComplexValType224 = any_ty()225 / char_ty()226 / bool_ty()227 / null_ty()228 / str_ty()229 / num_ty()230 / simple_array_ty()231 / simple_object_ty()232 / simple_function_ty()233 / array_ty()234 / bounded_number_ty()235236 pub rule ty() -> ComplexValType237 = precedence! {238 a:(@) " | " b:@ {239 match a {240 ComplexValType::Union(mut a) => {241 a.push(b);242 ComplexValType::Union(a)243 }244 _ => ComplexValType::Union(vec![a, b]),245 }246 }247 --248 a:(@) " & " b:@ {249 match a {250 ComplexValType::Sum(mut a) => {251 a.push(b);252 ComplexValType::Sum(a)253 }254 _ => ComplexValType::Sum(vec![a, b]),255 }256 }257 --258 "(" t:ty() ")" { t }259 t:ty_basic() { t }260 }261}262}263264#[cfg(test)]265pub mod tests {266 use super::parser;267268 #[test]269 fn precedence() {270 assert_eq!(271 parser::ty("(any & any) | (any | any) & any")272 .unwrap()273 .to_string(),274 "any & any | (any | any) & any"275 );276 }277278 #[test]279 fn array() {280 assert_eq!(parser::ty("Array<any>").unwrap().to_string(), "array");281 assert_eq!(282 parser::ty("Array<number>").unwrap().to_string(),283 "Array<number>"284 );285 }286 #[test]287 fn bounded_number() {288 assert_eq!(289 parser::ty("BoundedNumber<1, 2>").unwrap().to_string(),290 "BoundedNumber<1, 2>"291 );292 }293}flake.nixdiffbeforeafterboth--- a/flake.nix
+++ b/flake.nix
@@ -1,21 +1,59 @@
{
- description = "Rust jsonnet implementation";
-
- inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
- inputs.flake-utils.url = "github:numtide/flake-utils";
-
- outputs = { self, nixpkgs, flake-utils }:
+ description = "Dotfiles manager";
+ inputs = {
+ nixpkgs.url = "github:nixos/nixpkgs";
+ flake-utils.url = "github:numtide/flake-utils";
+ naersk.url = "github:nix-community/naersk";
+ rust-overlay.url = "github:oxalica/rust-overlay";
+ pre-commit-hooks.url = "github:cachix/pre-commit-hooks.nix";
+ };
+ outputs = { self, nixpkgs, flake-utils, rust-overlay, pre-commit-hooks, naersk }:
flake-utils.lib.eachDefaultSystem (system:
let
- pkgs = nixpkgs.legacyPackages.${system};
- jrsonnet = pkgs.rustPlatform.buildRustPackage rec {
- pname = "jrsonnet";
- version = "0.1.0";
- src = self;
- cargoSha256 = "sha256-cez8pJ/uwj+PHAPQwpSB4CKaxcP8Uvv8xguOrVXR2xE=";
+ pkgs = import nixpkgs
+ {
+ inherit system;
+ overlays = [ rust-overlay.overlay ];
+ };
+ rust = ((pkgs.rustChannelOf { date = "2021-11-11"; channel = "nightly"; }).default.override {
+ extensions = [ "rust-src" ];
+ });
+ naersk-lib = naersk.lib."${system}".override {
+ rustc = rust;
+ cargo = rust;
+ };
+ in
+ rec {
+ checks = {
+ pre-commit-check = pre-commit-hooks.lib.${system}.run {
+ src = ./.;
+ hooks = {
+ nixpkgs-fmt.enable = true;
+ };
+ };
+ };
+ defaultPackage = naersk-lib.buildPackage {
+ pname = "dotman";
+ root = ./.;
+ buildInputs = with pkgs; [
+ pkgs.sqlite
+ ];
};
- in {
- defaultPackage = jrsonnet;
- devShell = pkgs.mkShell {};
- });
+ devShell = pkgs.mkShell {
+ inherit (checks.pre-commit-check) shellHook;
+ nativeBuildInputs = with pkgs;[
+ pkgs.binutils
+ pkgs.pkgconfig
+ pkgs.clang
+ pkgs.x11
+ pkgs.alsaLib
+ pkgs.libudev
+ pkgs.sqlite
+ rust
+ cargo-edit
+ go-jsonnet
+ ];
+ };
+ }
+ );
}