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: Rc<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(ExprLocation(s.file_name.clone(), 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;320 use std::rc::Rc;321322 macro_rules! parse {323 ($s:expr) => {324 parse(325 $s,326 &ParserSettings {327 loc_data: false,328 file_name: Rc::new(PathBuf::from("/test.jsonnet")),329 },330 )331 .unwrap()332 };333 }334335 mod expressions {336 use super::*;337338 pub fn basic_math() -> LocExpr {339 el!(Expr::BinaryOp(340 el!(Expr::Num(2.0)),341 BinaryOpType::Add,342 el!(Expr::BinaryOp(343 el!(Expr::Num(2.0)),344 BinaryOpType::Mul,345 el!(Expr::Num(2.0)),346 )),347 ))348 }349 }350351 #[test]352 fn multiline_string() {353 assert_eq!(354 parse!("|||\n Hello world!\n a\n|||"),355 el!(Expr::Str("Hello world!\n a\n".to_owned())),356 )357 }358359 #[test]360 fn slice() {361 parse!("a[1:]");362 parse!("a[1::]");363 parse!("a[:1:]");364 parse!("a[::1]");365 parse!("str[:len - 1]");366 }367368 #[test]369 fn string_escaping() {370 assert_eq!(371 parse!(r#""Hello, \"world\"!""#),372 el!(Expr::Str(r#"Hello, "world"!"#.to_owned())),373 );374 assert_eq!(375 parse!(r#"'Hello \'world\'!'"#),376 el!(Expr::Str("Hello 'world'!".to_owned())),377 );378 assert_eq!(parse!(r#"'\\\\'"#), el!(Expr::Str("\\\\".to_owned())),);379 }380381 #[test]382 fn string_unescaping() {383 assert_eq!(384 parse!(r#""Hello\nWorld""#),385 el!(Expr::Str("Hello\nWorld".to_owned())),386 );387 }388389 #[test]390 fn string_verbantim() {391 assert_eq!(392 parse!(r#"@"Hello\n""World""""#),393 el!(Expr::Str("Hello\\n\"World\"".to_owned())),394 );395 }396397 #[test]398 fn imports() {399 assert_eq!(400 parse!("import \"hello\""),401 el!(Expr::Import(PathBuf::from("hello"))),402 );403 assert_eq!(404 parse!("importstr \"garnish.txt\""),405 el!(Expr::ImportStr(PathBuf::from("garnish.txt")))406 );407 }408409 #[test]410 fn empty_object() {411 assert_eq!(parse!("{}"), el!(Expr::Obj(ObjBody::MemberList(vec![]))));412 }413414 #[test]415 fn basic_math() {416 assert_eq!(417 parse!("2+2*2"),418 el!(Expr::BinaryOp(419 el!(Expr::Num(2.0)),420 BinaryOpType::Add,421 el!(Expr::BinaryOp(422 el!(Expr::Num(2.0)),423 BinaryOpType::Mul,424 el!(Expr::Num(2.0))425 ))426 ))427 );428 }429430 #[test]431 fn basic_math_with_indents() {432 assert_eq!(parse!("2 + 2 * 2 "), expressions::basic_math());433 }434435 #[test]436 fn basic_math_parened() {437 assert_eq!(438 parse!("2+(2+2*2)"),439 el!(Expr::BinaryOp(440 el!(Expr::Num(2.0)),441 BinaryOpType::Add,442 el!(Expr::Parened(expressions::basic_math())),443 ))444 );445 }446447 448 #[test]449 fn comments() {450 assert_eq!(451 parse!("2//comment\n+//comment\n3/*test*/*/*test*/4"),452 el!(Expr::BinaryOp(453 el!(Expr::Num(2.0)),454 BinaryOpType::Add,455 el!(Expr::BinaryOp(456 el!(Expr::Num(3.0)),457 BinaryOpType::Mul,458 el!(Expr::Num(4.0))459 ))460 ))461 );462 }463464 465 #[test]466 fn comment_escaping() {467 assert_eq!(468 parse!("2/*\\*/+*/ - 22"),469 el!(Expr::BinaryOp(470 el!(Expr::Num(2.0)),471 BinaryOpType::Sub,472 el!(Expr::Num(22.0))473 ))474 );475 }476477 #[test]478 fn suffix() {479 480 481 482 483 }484485 #[test]486 fn array_comp() {487 use Expr::*;488 assert_eq!(489 parse!("[std.deepJoin(x) for x in arr]"),490 el!(ArrComp(491 el!(Apply(492 el!(Index(493 el!(Var("std".to_owned())),494 el!(Str("deepJoin".to_owned()))495 )),496 ArgsDesc(vec![Arg(None, el!(Var("x".to_owned())))]),497 false,498 )),499 vec![CompSpec::ForSpec(ForSpecData(500 "x".to_owned(),501 el!(Var("arr".to_owned()))502 ))]503 )),504 )505 }506507 #[test]508 fn reserved() {509 use Expr::*;510 assert_eq!(parse!("null"), el!(Literal(LiteralType::Null)));511 assert_eq!(parse!("nulla"), el!(Var("nulla".to_owned())));512 }513514 #[test]515 fn multiple_args_buf() {516 parse!("a(b, null_fields)");517 }518519 #[test]520 fn infix_precedence() {521 use Expr::*;522 assert_eq!(523 parse!("!a && !b"),524 el!(BinaryOp(525 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned())))),526 BinaryOpType::And,527 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".to_owned()))))528 ))529 );530 }531532 #[test]533 fn infix_precedence_division() {534 use Expr::*;535 assert_eq!(536 parse!("!a / !b"),537 el!(BinaryOp(538 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned())))),539 BinaryOpType::Div,540 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".to_owned()))))541 ))542 );543 }544545 #[test]546 fn double_negation() {547 use Expr::*;548 assert_eq!(549 parse!("!!a"),550 el!(UnaryOp(551 UnaryOpType::Not,552 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".to_owned()))))553 ))554 )555 }556557 #[test]558 fn array_test_error() {559 parse!("[a for a in b if c for e in f]");560 561 }562563 #[test]564 fn can_parse_stdlib() {565 parse!(jsonnet_stdlib::STDLIB_STR);566 }567568 use test::Bencher;569570 571 #[bench]572 fn bench_parse_peg(b: &mut Bencher) {573 b.iter(|| parse!(jsonnet_stdlib::STDLIB_STR))574 }575576 577 #[bench]578 fn bench_parse_serde_bincode(b: &mut Bencher) {579 let serialized = bincode::serialize(&parse!(jsonnet_stdlib::STDLIB_STR)).unwrap();580 b.iter(|| bincode::deserialize::<LocExpr>(&serialized))581 }582}