1#![feature(box_syntax)]2#![feature(test)]34extern crate test;56use peg::parser;7use std::{path::PathBuf, rc::Rc};8mod expr;9pub use expr::*;10pub use peg;1112pub struct ParserSettings {13 pub loc_data: bool,14 pub file_name: PathBuf,15}1617parser! {18 grammar jsonnet_parser() for str {19 use peg::ParseLiteral;2021 22 rule comment()23 = "//" (!['\n'][_])* "\n"24 / "/*" ("\\*/" / "\\\\" / (!("*/")[_]))* "*/"25 / "#" (!['\n'][_])* "\n"2627 rule single_whitespace() = quiet!{([' ' | '\r' | '\n' | '\t'] / comment())} / expected!("<whitespace>")28 rule _() = single_whitespace()*2930 31 rule comma() = quiet!{_ "," _} / expected!("<comma>")32 rule alpha() -> char = c:$(['_' | 'a'..='z' | 'A'..='Z']) {c.chars().next().unwrap()}33 rule digit() -> char = d:$(['0'..='9']) {d.chars().next().unwrap()}34 rule end_of_ident() = !['0'..='9' | '_' | 'a'..='z' | 'A'..='Z']35 36 rule uint() -> u64 = a:$(digit()+) { a.parse().unwrap() }37 38 rule number() -> f64 = quiet!{a:$(uint() ("." uint())? (['e'|'E'] (s:['+'|'-'])? uint())?) { a.parse().unwrap() }} / expected!("<number>")3940 41 rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()42 rule id() -> String = quiet!{ !reserved() s:$(alpha() (alpha() / digit())*) {s.to_owned()}} / expected!("<identifier>")4344 rule keyword(id: &'static str)45 = ##parse_string_literal(id) end_of_ident()46 47 rule l(s: &ParserSettings, x: rule<Expr>) -> LocExpr48 = start:position!() v:x() end:position!() {loc_expr!(v, s.loc_data, (s.file_name.clone(), start, end))}4950 pub rule param(s: &ParserSettings) -> expr::Param = name:id() expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name, expr) }51 pub rule params(s: &ParserSettings) -> expr::ParamsDesc52 = params:(param(s) ** comma()) {53 let mut defaults_started = false;54 for param in ¶ms {55 defaults_started = defaults_started || param.1.is_some();56 assert_eq!(defaults_started, param.1.is_some(), "defauld parameters should be used after all positionals");57 }58 expr::ParamsDesc(params)59 }60 / { expr::ParamsDesc(Vec::new()) }6162 pub rule arg(s: &ParserSettings) -> expr::Arg63 = name:id() _ "=" _ expr:expr(s) {expr::Arg(Some(name), expr)}64 / expr:expr(s) {expr::Arg(None, expr)}65 pub rule args(s: &ParserSettings) -> expr::ArgsDesc66 = args:arg(s) ** comma() comma()? {67 let mut named_started = false;68 for arg in &args {69 named_started = named_started || arg.0.is_some();70 assert_eq!(named_started, arg.0.is_some(), "named args should be used after all positionals");71 }72 expr::ArgsDesc(args)73 }74 / { expr::ArgsDesc(Vec::new()) }7576 pub rule bind(s: &ParserSettings) -> expr::BindSpec77 = name:id() _ "=" _ expr:expr(s) {expr::BindSpec{name, params: None, value: expr}}78 / name:id() _ "(" _ params:params(s) _ ")" _ "=" _ expr:expr(s) {expr::BindSpec{name, params: Some(params), value: expr}}79 pub rule assertion(s: &ParserSettings) -> expr::AssertStmt80 = keyword("assert") _ cond:expr(s) msg:(_ ":" _ e:expr(s) {e})? { expr::AssertStmt(cond, msg) }8182 pub rule whole_line() -> &'input str83 = str:$((!['\n'][_])* "\n") {str}84 pub rule string_block() -> String85 = "|||" (!['\n']single_whitespace())* "\n"86 prefix:[' ']+ first_line:whole_line()87 lines:([' ']*<{prefix.len()}> s:whole_line() {s})*88 [' ']*<, {prefix.len() - 1}> "|||"89 {let mut l = first_line.to_owned(); l.extend(lines); l}90 pub rule string() -> String91 = "\"" str:$(("\\\"" / "\\\\" / (!['"'][_]))*) "\"" {unescape::unescape(str).unwrap()}92 / "'" str:$(("\\'" / "\\\\" / (!['\''][_]))*) "'" {unescape::unescape(str).unwrap()}93 / "@'" str:$(("''" / (!['\''][_]))*) "'" {str.replace("''", "'")}94 / "@\"" str:$(("\"\"" / (!['"'][_]))*) "\"" {str.replace("\"\"", "\"")}95 / string_block()9697 pub rule field_name(s: &ParserSettings) -> expr::FieldName98 = name:id() {expr::FieldName::Fixed(name)}99 / name:string() {expr::FieldName::Fixed(name)}100 / "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}101 pub rule visibility() -> expr::Visibility102 = ":::" {expr::Visibility::Unhide}103 / "::" {expr::Visibility::Hidden}104 / ":" {expr::Visibility::Normal}105 pub rule field(s: &ParserSettings) -> expr::FieldMember106 = name:field_name(s) _ plus:"+"? _ visibility:visibility() _ value:expr(s) {expr::FieldMember{107 name,108 plus: plus.is_some(),109 params: None,110 visibility,111 value,112 }}113 / name:field_name(s) _ "(" _ params:params(s) _ ")" _ visibility:visibility() _ value:expr(s) {expr::FieldMember{114 name,115 plus: false,116 params: Some(params),117 visibility,118 value,119 }}120 pub rule obj_local(s: &ParserSettings) -> BindSpec121 = keyword("local") _ bind:bind(s) {bind}122 pub rule member(s: &ParserSettings) -> expr::Member123 = bind:obj_local(s) {expr::Member::BindStmt(bind)}124 / assertion:assertion(s) {expr::Member::AssertStmt(assertion)}125 / field:field(s) {expr::Member::Field(field)}126 pub rule objinside(s: &ParserSettings) -> expr::ObjBody127 = 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})? {128 expr::ObjBody::ObjComp {129 pre_locals,130 key,131 value,132 post_locals,133 compspecs: [vec![CompSpec::ForSpec(forspec)], others.unwrap_or_default()].concat(),134 }135 }136 / members:(member(s) ** comma()) comma()? {expr::ObjBody::MemberList(members)}137 pub rule ifspec(s: &ParserSettings) -> IfSpecData138 = keyword("if") _ expr:expr(s) {IfSpecData(expr)}139 pub rule forspec(s: &ParserSettings) -> ForSpecData140 = keyword("for") _ id:id() _ keyword("in") _ cond:expr(s) {ForSpecData(id, cond)}141 pub rule compspec(s: &ParserSettings) -> Vec<expr::CompSpec>142 = s:(i:ifspec(s) { expr::CompSpec::IfSpec(i) } / f:forspec(s) {expr::CompSpec::ForSpec(f)} ) ** _ {s}143 pub rule local_expr(s: &ParserSettings) -> LocExpr144 = l(s,<keyword("local") _ binds:bind(s) ** comma() _ ";" _ expr:expr(s) { Expr::LocalExpr(binds, expr) }>)145 pub rule string_expr(s: &ParserSettings) -> LocExpr146 = l(s, <s:string() {Expr::Str(s)}>)147 pub rule obj_expr(s: &ParserSettings) -> LocExpr148 = l(s,<"{" _ body:objinside(s) _ "}" {Expr::Obj(body)}>)149 pub rule array_expr(s: &ParserSettings) -> LocExpr150 = l(s,<"[" _ elems:(expr(s) ** comma()) _ comma()? "]" {Expr::Arr(elems)}>)151 pub rule array_comp_expr(s: &ParserSettings) -> LocExpr152 = 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())}>)153 pub rule number_expr(s: &ParserSettings) -> LocExpr154 = l(s,<n:number() { expr::Expr::Num(n) }>)155 pub rule var_expr(s: &ParserSettings) -> LocExpr156 = l(s,<n:id() { expr::Expr::Var(n) }>)157 pub rule if_then_else_expr(s: &ParserSettings) -> LocExpr158 = l(s,<cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{159 cond,160 cond_then,161 cond_else,162 }}>)163164 pub rule literal(s: &ParserSettings) -> LocExpr165 = l(s,<v:(166 keyword("null") {LiteralType::Null}167 / keyword("true") {LiteralType::True}168 / keyword("false") {LiteralType::False}169 / keyword("self") {LiteralType::This}170 / keyword("$") {LiteralType::Dollar}171 / keyword("super") {LiteralType::Super}172 ) {Expr::Literal(v)}>)173174 pub rule expr_basic(s: &ParserSettings) -> LocExpr175 = literal(s)176177 / string_expr(s) / number_expr(s)178 / array_expr(s)179 / obj_expr(s)180 / array_expr(s)181 / array_comp_expr(s)182183 / l(s,<keyword("importstr") _ path:string() {Expr::ImportStr(PathBuf::from(path))}>)184 / l(s,<keyword("import") _ path:string() {Expr::Import(PathBuf::from(path))}>)185186 / var_expr(s)187 / local_expr(s)188 / if_then_else_expr(s)189190 / l(s,<keyword("function") _ "(" _ params:params(s) _ ")" _ expr:expr(s) {Expr::Function(params, expr)}>)191 / l(s,<assertion:assertion(s) _ ";" _ expr:expr(s) { Expr::AssertExpr(assertion, expr) }>)192193 / l(s,<keyword("error") _ expr:expr(s) { Expr::Error(expr) }>)194195 rule slice_part(s: &ParserSettings) -> Option<LocExpr>196 = e:(_ e:expr(s) _{e})? {e}197 pub rule slice_desc(s: &ParserSettings) -> SliceDesc198 = start:slice_part(s) ":" pair:(end:slice_part(s) step:(":" e:slice_part(s){e})? {(end, step.flatten())})? {199 let (end, step) = if let Some((end, step)) = pair {200 (end, step)201 }else{202 (None, None)203 };204205 SliceDesc { start, end, step }206 }207208 rule expr(s: &ParserSettings) -> LocExpr209 = start:position!() a:precedence! {210 a:(@) _ "||" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Or, b))}211 --212 a:(@) _ "&&" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::And, b))}213 --214 a:(@) _ "|" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitOr, b))}215 --216 a:@ _ "^" _ b:(@) {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitXor, b))}217 --218 a:(@) _ "&" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitAnd, b))}219 --220 a:(@) _ "==" _ b:@ {loc_expr_todo!(Expr::Apply(221 el!(Expr::Index(222 el!(Expr::Var("std".to_owned())),223 el!(Expr::Str("equals".to_owned()))224 )),225 ArgsDesc(vec![Arg(None, a), Arg(None, b)]),226 true227 ))}228 a:(@) _ "!=" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, el!(Expr::Apply(229 el!(Expr::Index(230 el!(Expr::Var("std".to_owned())),231 el!(Expr::Str("equals".to_owned()))232 )),233 ArgsDesc(vec![Arg(None, a), Arg(None, b)]),234 true235 ))))}236 --237 a:(@) _ "<" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lt, b))}238 a:(@) _ ">" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gt, b))}239 a:(@) _ "<=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lte, b))}240 a:(@) _ ">=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gte, b))}241 a:(@) _ keyword("in") _ b:@ {loc_expr_todo!(Expr::Apply(242 el!(Expr::Index(243 el!(Expr::Var("std".to_owned())),244 el!(Expr::Str("objectHasEx".to_owned()))245 )), ArgsDesc(vec![Arg(None, b), Arg(None, a), Arg(None, el!(Expr::Literal(LiteralType::True)))]),246 true247 ))}248 --249 a:(@) _ "<<" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lhs, b))}250 a:(@) _ ">>" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Rhs, b))}251 --252 a:(@) _ "+" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Add, b))}253 a:(@) _ "-" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Sub, b))}254 --255 a:(@) _ "*" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Mul, b))}256 a:(@) _ "/" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Div, b))}257 a:(@) _ "%" _ b:@ {loc_expr_todo!(Expr::Apply(258 el!(Expr::Index(259 el!(Expr::Var("std".to_owned())),260 el!(Expr::Str("mod".to_owned()))261 )), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),262 true263 ))}264 --265 "-" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Minus, b))}266 "!" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, b))}267 "~" _ b:@ { loc_expr_todo!(Expr::UnaryOp(UnaryOpType::BitNot, b)) }268 --269 a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Apply(270 el!(Expr::Index(271 el!(Expr::Var("std".to_owned())),272 el!(Expr::Str("slice".to_owned())),273 )),274 ArgsDesc(vec![275 Arg(None, a),276 Arg(None, s.start.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),277 Arg(None, s.end.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),278 Arg(None, s.step.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),279 ]),280 true,281 ))}282 a:(@) _ "." _ s:id() {loc_expr_todo!(Expr::Index(a, el!(Expr::Str(s))))}283 a:(@) _ "[" _ s:expr(s) _ "]" {loc_expr_todo!(Expr::Index(a, s))}284 a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {loc_expr_todo!(Expr::Apply(a, args, ts.is_some()))}285 a:(@) _ "{" _ body:objinside(s) _ "}" {loc_expr_todo!(Expr::ObjExtend(a, body))}286 --287 e:expr_basic(s) {e}288 "(" _ e:expr(s) _ ")" {loc_expr_todo!(Expr::Parened(e))}289 } end:position!() {290 let LocExpr(e, _) = a;291 LocExpr(e, if s.loc_data {292 Some(Rc::new(ExprLocation(s.file_name.to_owned(), start, end)))293 } else {294 None295 })296 }297 / e:expr_basic(s) {e}298299 pub rule jsonnet(s: &ParserSettings) -> LocExpr = _ e:expr(s) _ {e}300 }301}302303pub type ParseError = peg::error::ParseError<peg::str::LineCol>;304pub fn parse(str: &str, settings: &ParserSettings) -> Result<LocExpr, ParseError> {305 jsonnet_parser::jsonnet(str, settings)306}307308#[macro_export]309macro_rules! el {310 ($expr:expr) => {311 LocExpr(std::rc::Rc::new($expr), None)312 };313}314315#[cfg(test)]316pub mod tests {317 use super::{expr::*, parse};318 use crate::ParserSettings;319 use std::path::PathBuf;320321 macro_rules! parse {322 ($s:expr) => {323 parse(324 $s,325 &ParserSettings {326 loc_data: false,327 file_name: PathBuf::from("/test.jsonnet"),328 },329 )330 .unwrap()331 };332 }333334 mod expressions {335 use super::*;336337 pub fn basic_math() -> LocExpr {338 el!(Expr::BinaryOp(339 el!(Expr::Num(2.0)),340 BinaryOpType::Add,341 el!(Expr::BinaryOp(342 el!(Expr::Num(2.0)),343 BinaryOpType::Mul,344 el!(Expr::Num(2.0)),345 )),346 ))347 }348 }349350 #[test]351 fn multiline_string() {352 assert_eq!(353 parse!("|||\n Hello world!\n a\n|||"),354 el!(Expr::Str("Hello world!\n a\n".to_owned())),355 )356 }357358 #[test]359 fn slice() {360 parse!("a[1:]");361 parse!("a[1::]");362 parse!("a[:1:]");363 parse!("a[::1]");364 parse!("str[:len - 1]");365 }366367 #[test]368 fn string_escaping() {369 assert_eq!(370 parse!(r#""Hello, \"world\"!""#),371 el!(Expr::Str(r#"Hello, "world"!"#.to_owned())),372 );373 assert_eq!(374 parse!(r#"'Hello \'world\'!'"#),375 el!(Expr::Str("Hello 'world'!".to_owned())),376 );377 assert_eq!(parse!(r#"'\\\\'"#), el!(Expr::Str("\\\\".to_owned())),);378 }379380 #[test]381 fn string_unescaping() {382 assert_eq!(383 parse!(r#""Hello\nWorld""#),384 el!(Expr::Str("Hello\nWorld".to_owned())),385 );386 }387388 #[test]389 fn string_verbantim() {390 assert_eq!(391 parse!(r#"@"Hello\n""World""""#),392 el!(Expr::Str("Hello\\n\"World\"".to_owned())),393 );394 }395396 #[test]397 fn imports() {398 assert_eq!(399 parse!("import \"hello\""),400 el!(Expr::Import(PathBuf::from("hello"))),401 );402 assert_eq!(403 parse!("importstr \"garnish.txt\""),404 el!(Expr::ImportStr(PathBuf::from("garnish.txt")))405 );406 }407408 #[test]409 fn empty_object() {410 assert_eq!(parse!("{}"), el!(Expr::Obj(ObjBody::MemberList(vec![]))));411 }412413 #[test]414 fn basic_math() {415 assert_eq!(416 parse!("2+2*2"),417 el!(Expr::BinaryOp(418 el!(Expr::Num(2.0)),419 BinaryOpType::Add,420 el!(Expr::BinaryOp(421 el!(Expr::Num(2.0)),422 BinaryOpType::Mul,423 el!(Expr::Num(2.0))424 ))425 ))426 );427 }428429 #[test]430 fn basic_math_with_indents() {431 assert_eq!(parse!("2 + 2 * 2 "), expressions::basic_math());432 }433434 #[test]435 fn basic_math_parened() {436 assert_eq!(437 parse!("2+(2+2*2)"),438 el!(Expr::BinaryOp(439 el!(Expr::Num(2.0)),440 BinaryOpType::Add,441 el!(Expr::Parened(expressions::basic_math())),442 ))443 );444 }445446 447 #[test]448 fn comments() {449 assert_eq!(450 parse!("2//comment\n+//comment\n3/*test*/*/*test*/4"),451 el!(Expr::BinaryOp(452 el!(Expr::Num(2.0)),453 BinaryOpType::Add,454 el!(Expr::BinaryOp(455 el!(Expr::Num(3.0)),456 BinaryOpType::Mul,457 el!(Expr::Num(4.0))458 ))459 ))460 );461 }462463 464 #[test]465 fn comment_escaping() {466 assert_eq!(467 parse!("2/*\\*/+*/ - 22"),468 el!(Expr::BinaryOp(469 el!(Expr::Num(2.0)),470 BinaryOpType::Sub,471 el!(Expr::Num(22.0))472 ))473 );474 }475476 #[test]477 fn suffix() {478 479 480 481 482 }483484 #[test]485 fn array_comp() {486 use Expr::*;487 assert_eq!(488 parse!("[std.deepJoin(x) for x in arr]"),489 el!(ArrComp(490 el!(Apply(491 el!(Index(492 el!(Var("std".to_owned())),493 el!(Str("deepJoin".to_owned()))494 )),495 ArgsDesc(vec![Arg(None, el!(Var("x".to_owned())))]),496 false,497 )),498 vec![CompSpec::ForSpec(ForSpecData(499 "x".to_owned(),500 el!(Var("arr".to_owned()))501 ))]502 )),503 )504 }505506 #[test]507 fn reserved() {508 use Expr::*;509 assert_eq!(parse!("null"), el!(Literal(LiteralType::Null)));510 assert_eq!(parse!("nulla"), el!(Var("nulla".to_owned())));511 }512513 #[test]514 fn multiple_args_buf() {515 parse!("a(b, null_fields)");516 }517518 #[test]519 fn infix_precedence() {520 use Expr::*;521 assert_eq!(522 parse!("!a && !b"),523 el!(BinaryOp(524 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned())))),525 BinaryOpType::And,526 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".to_owned()))))527 ))528 );529 }530531 #[test]532 fn infix_precedence_division() {533 use Expr::*;534 assert_eq!(535 parse!("!a / !b"),536 el!(BinaryOp(537 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned())))),538 BinaryOpType::Div,539 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".to_owned()))))540 ))541 );542 }543544 #[test]545 fn double_negation() {546 use Expr::*;547 assert_eq!(548 parse!("!!a"),549 el!(UnaryOp(550 UnaryOpType::Not,551 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned()))))552 ))553 )554 }555556 #[test]557 fn array_test_error() {558 parse!("[a for a in b if c for e in f]");559 560 }561562 #[test]563 fn can_parse_stdlib() {564 parse!(jsonnet_stdlib::STDLIB_STR);565 }566567 use test::Bencher;568569 570 #[bench]571 fn bench_parse_peg(b: &mut Bencher) {572 b.iter(|| parse!(jsonnet_stdlib::STDLIB_STR))573 }574575 576 #[bench]577 fn bench_parse_serde_bincode(b: &mut Bencher) {578 let serialized = bincode::serialize(&parse!(jsonnet_stdlib::STDLIB_STR)).unwrap();579 b.iter(|| bincode::deserialize::<LocExpr>(&serialized))580 }581}