1#![allow(clippy::redundant_closure_call, clippy::derive_partial_eq_without_eq)]23use std::rc::Rc;45use peg::parser;6mod expr;7pub use expr::*;8pub use jrsonnet_interner::IStr;9pub use peg;10mod location;11mod source;12mod unescape;13pub use location::CodeLocation;14pub use source::{15 Source, SourceDirectory, SourceFifo, SourceFile, SourcePath, SourcePathT, SourceVirtual,16};1718pub struct ParserSettings {19 pub source: Source,20}2122macro_rules! expr_bin {23 ($a:ident $op:ident $b:ident) => {24 Expr::BinaryOp($a, $op, $b)25 };26}27macro_rules! expr_un {28 ($op:ident $a:ident) => {29 Expr::UnaryOp($op, $a)30 };31}3233parser! {34 grammar jsonnet_parser() for str {35 use peg::ParseLiteral;3637 rule eof() = quiet!{![_]} / expected!("<eof>")38 rule eol() = "\n" / eof()3940 41 rule comment()42 = "//" (!eol()[_])* eol()43 / "/*" (!("*/")[_])* "*/"44 / "#" (!eol()[_])* eol()4546 rule single_whitespace() = quiet!{([' ' | '\r' | '\n' | '\t'] / comment())} / expected!("<whitespace>")47 rule _() = quiet!{([' ' | '\r' | '\n' | '\t']+) / comment()}* / expected!("<whitespace>")4849 50 rule comma() = quiet!{_ "," _} / expected!("<comma>")51 rule alpha() -> char = c:$(['_' | 'a'..='z' | 'A'..='Z']) {c.chars().next().unwrap()}52 rule digit() -> char = d:$(['0'..='9']) {d.chars().next().unwrap()}53 rule end_of_ident() = !['0'..='9' | '_' | 'a'..='z' | 'A'..='Z']54 55 rule uint_str() -> &'input str = a:$(digit()+) { a }56 57 rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.parse().map_err(|_| "<number>") }} / expected!("<number>")5859 60 rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "importbin" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()61 rule id() -> IStr = v:$(quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")) { v.into() }6263 rule keyword(id: &'static str) -> ()64 = ##parse_string_literal(id) end_of_ident()6566 pub rule param(s: &ParserSettings) -> expr::Param = name:destruct(s) expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name, expr) }67 pub rule params(s: &ParserSettings) -> expr::ParamsDesc68 = params:param(s) ** comma() comma()? { expr::ParamsDesc(Rc::new(params)) }69 / { expr::ParamsDesc(Rc::new(Vec::new())) }7071 pub rule arg(s: &ParserSettings) -> (Option<IStr>, LocExpr)72 = name:(quiet! { (s:id() _ "=" !['='] _ {s})? } / expected!("<argument name>")) expr:expr(s) {(name, expr)}7374 pub rule args(s: &ParserSettings) -> expr::ArgsDesc75 = args:arg(s)**comma() comma()? {?76 let unnamed_count = args.iter().take_while(|(n, _)| n.is_none()).count();77 let mut unnamed = Vec::with_capacity(unnamed_count);78 let mut named = Vec::with_capacity(args.len() - unnamed_count);79 let mut named_started = false;80 for (name, value) in args {81 if let Some(name) = name {82 named_started = true;83 named.push((name, value));84 } else {85 if named_started {86 return Err("<named argument>")87 }88 unnamed.push(value);89 }90 }91 Ok(expr::ArgsDesc::new(unnamed, named))92 }9394 pub rule destruct_rest() -> expr::DestructRest95 = "..." into:(_ into:id() {into})? {if let Some(into) = into {96 expr::DestructRest::Keep(into)97 } else {expr::DestructRest::Drop}}98 pub rule destruct_array(s: &ParserSettings) -> expr::Destruct99 = "[" _ start:destruct(s)**comma() rest:(100 comma() _ rest:destruct_rest()? end:(101 comma() end:destruct(s)**comma() (_ comma())? {end}102 / comma()? {Vec::new()}103 ) {(rest, end)}104 / comma()? {(None, Vec::new())}105 ) _ "]" {?106 #[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Array {107 start,108 rest: rest.0,109 end: rest.1,110 });111 #[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")112 }113 pub rule destruct_object(s: &ParserSettings) -> expr::Destruct114 = "{" _115 fields:(name:id() into:(_ ":" _ into:destruct(s) {into})? default:(_ "=" _ v:expr(s) {v})? {(name, into, default)})**comma()116 rest:(117 comma() rest:destruct_rest()? {rest}118 / comma()? {None}119 )120 _ "}" {?121 #[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Object {122 fields,123 rest,124 });125 #[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")126 }127 pub rule destruct(s: &ParserSettings) -> expr::Destruct128 = v:id() {expr::Destruct::Full(v)}129 / "?" {?130 #[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Skip);131 #[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")132 }133 / arr:destruct_array(s) {arr}134 / obj:destruct_object(s) {obj}135136 pub rule bind(s: &ParserSettings) -> expr::BindSpec137 = into:destruct(s) _ "=" _ expr:expr(s) {expr::BindSpec::Field{into, value: expr}}138 / name:id() _ "(" _ params:params(s) _ ")" _ "=" _ expr:expr(s) {expr::BindSpec::Function{name, params, value: expr}}139140 pub rule assertion(s: &ParserSettings) -> expr::AssertStmt141 = keyword("assert") _ cond:expr(s) msg:(_ ":" _ e:expr(s) {e})? { expr::AssertStmt(cond, msg) }142143 pub rule whole_line() -> &'input str144 = str:$((!['\n'][_])* "\n") {str}145 pub rule string_block() -> String146 = "|||" (!['\n']single_whitespace())* "\n"147 empty_lines:$(['\n']*)148 prefix:[' ' | '\t']+ first_line:whole_line()149 lines:("\n" {"\n"} / [' ' | '\t']*<{prefix.len()}> s:whole_line() {s})*150 [' ' | '\t']*<, {prefix.len() - 1}> "|||"151 {let mut l = empty_lines.to_owned(); l.push_str(first_line); l.extend(lines); l}152153 rule hex_char()154 = quiet! { ['0'..='9' | 'a'..='f' | 'A'..='F'] } / expected!("<hex char>")155156 rule string_char(c: rule<()>)157 = (!['\\']!c()[_])+158 / "\\\\"159 / "\\u" hex_char() hex_char() hex_char() hex_char()160 / "\\x" hex_char() hex_char()161 / ['\\'] (quiet! { ['b' | 'f' | 'n' | 'r' | 't' | '"' | '\''] } / expected!("<escape character>"))162 pub rule string() -> String163 = ['"'] str:$(string_char(<"\"">)*) ['"'] {? unescape::unescape(str).ok_or("<escaped string>")}164 / ['\''] str:$(string_char(<"\'">)*) ['\''] {? unescape::unescape(str).ok_or("<escaped string>")}165 / quiet!{ "@'" str:$(("''" / (!['\''][_]))*) "'" {str.replace("''", "'")}166 / "@\"" str:$(("\"\"" / (!['"'][_]))*) "\"" {str.replace("\"\"", "\"")}167 / string_block() } / expected!("<string>")168169 pub rule field_name(s: &ParserSettings) -> expr::FieldName170 = name:id() {expr::FieldName::Fixed(name)}171 / name:string() {expr::FieldName::Fixed(name.into())}172 / "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}173 pub rule visibility() -> expr::Visibility174 = ":::" {expr::Visibility::Unhide}175 / "::" {expr::Visibility::Hidden}176 / ":" {expr::Visibility::Normal}177 pub rule field(s: &ParserSettings) -> expr::FieldMember178 = name:field_name(s) _ plus:"+"? _ visibility:visibility() _ value:expr(s) {expr::FieldMember{179 name,180 plus: plus.is_some(),181 params: None,182 visibility,183 value,184 }}185 / name:field_name(s) _ "(" _ params:params(s) _ ")" _ visibility:visibility() _ value:expr(s) {expr::FieldMember{186 name,187 plus: false,188 params: Some(params),189 visibility,190 value,191 }}192 pub rule obj_local(s: &ParserSettings) -> BindSpec193 = keyword("local") _ bind:bind(s) {bind}194 pub rule member(s: &ParserSettings) -> expr::Member195 = bind:obj_local(s) {expr::Member::BindStmt(bind)}196 / assertion:assertion(s) {expr::Member::AssertStmt(assertion)}197 / field:field(s) {expr::Member::Field(field)}198 pub rule objinside(s: &ParserSettings) -> expr::ObjBody199 = pre_locals:(b: obj_local(s) comma() {b})* &"[" field:field(s) post_locals:(comma() b:obj_local(s) {b})* _ ("," _)? forspec:forspec(s) others:(_ rest:compspec(s) {rest})? {200 let mut compspecs = vec![CompSpec::ForSpec(forspec)];201 compspecs.extend(others.unwrap_or_default());202 expr::ObjBody::ObjComp(expr::ObjComp{203 pre_locals,204 field,205 post_locals,206 compspecs,207 })208 }209 / members:(member(s) ** comma()) comma()? {expr::ObjBody::MemberList(members)}210 pub rule ifspec(s: &ParserSettings) -> IfSpecData211 = keyword("if") _ expr:expr(s) {IfSpecData(expr)}212 pub rule forspec(s: &ParserSettings) -> ForSpecData213 = keyword("for") _ id:destruct(s) _ keyword("in") _ cond:expr(s) {ForSpecData(id, cond)}214 pub rule compspec(s: &ParserSettings) -> Vec<expr::CompSpec>215 = s:(i:ifspec(s) { expr::CompSpec::IfSpec(i) } / f:forspec(s) {expr::CompSpec::ForSpec(f)} ) ** _ {s}216 pub rule local_expr(s: &ParserSettings) -> Expr217 = keyword("local") _ binds:bind(s) ** comma() (_ ",")? _ ";" _ expr:expr(s) { Expr::LocalExpr(binds, expr) }218 pub rule string_expr(s: &ParserSettings) -> Expr219 = s:string() {Expr::Str(s.into())}220 pub rule obj_expr(s: &ParserSettings) -> Expr221 = "{" _ body:objinside(s) _ "}" {Expr::Obj(body)}222 pub rule array_expr(s: &ParserSettings) -> Expr223 = "[" _ elems:(expr(s) ** comma()) _ comma()? "]" {Expr::Arr(elems)}224 pub rule array_comp_expr(s: &ParserSettings) -> Expr225 = "[" _ expr:expr(s) _ comma()? _ forspec:forspec(s) _ others:(others: compspec(s) _ {others})? "]" {226 let mut specs = vec![CompSpec::ForSpec(forspec)];227 specs.extend(others.unwrap_or_default());228 Expr::ArrComp(expr, specs)229 }230 pub rule number_expr(s: &ParserSettings) -> Expr231 = n:number() { expr::Expr::Num(n) }232 pub rule var_expr(s: &ParserSettings) -> Expr233 = n:id() { expr::Expr::Var(n) }234 pub rule id_loc(s: &ParserSettings) -> LocExpr235 = a:position!() n:id() b:position!() { LocExpr::new(expr::Expr::Str(n), Span(s.source.clone(), a as u32,b as u32)) }236 pub rule if_then_else_expr(s: &ParserSettings) -> Expr237 = cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{238 cond,239 cond_then,240 cond_else,241 }}242243 pub rule literal(s: &ParserSettings) -> Expr244 = v:(245 keyword("null") {LiteralType::Null}246 / keyword("true") {LiteralType::True}247 / keyword("false") {LiteralType::False}248 / keyword("self") {LiteralType::This}249 / keyword("$") {LiteralType::Dollar}250 / keyword("super") {LiteralType::Super}251 ) {Expr::Literal(v)}252253 pub rule expr_basic(s: &ParserSettings) -> Expr254 = literal(s)255256 / string_expr(s) / number_expr(s)257 / array_expr(s)258 / obj_expr(s)259 / array_expr(s)260 / array_comp_expr(s)261262 / keyword("importstr") _ path:expr(s) {Expr::ImportStr(path)}263 / keyword("importbin") _ path:expr(s) {Expr::ImportBin(path)}264 / keyword("import") _ path:expr(s) {Expr::Import(path)}265266 / var_expr(s)267 / local_expr(s)268 / if_then_else_expr(s)269270 / keyword("function") _ "(" _ params:params(s) _ ")" _ expr:expr(s) {Expr::Function(params, expr)}271 / assertion:assertion(s) _ ";" _ expr:expr(s) { Expr::AssertExpr(assertion, expr) }272273 / keyword("error") _ expr:expr(s) { Expr::ErrorStmt(expr) }274275 rule slice_part(s: &ParserSettings) -> Option<LocExpr>276 = _ e:(e:expr(s) _{e})? {e}277 pub rule slice_desc(s: &ParserSettings) -> SliceDesc278 = start:slice_part(s) ":" pair:(end:slice_part(s) step:(":" e:slice_part(s){e})? {(end, step.flatten())})? {279 let (end, step) = if let Some((end, step)) = pair {280 (end, step)281 }else{282 (None, None)283 };284285 SliceDesc { start, end, step }286 }287288 rule binop(x: rule<()>) -> ()289 = quiet!{ x() } / expected!("<binary op>")290 rule unaryop(x: rule<()>) -> ()291 = quiet!{ x() } / expected!("<unary op>")292293 rule ensure_null_coaelse()294 = "" {?295 #[cfg(not(feature = "exp-null-coaelse"))] return Err("!!!experimental null coaelscing was not enabled");296 #[cfg(feature = "exp-null-coaelse")] Ok(())297 }298 use BinaryOpType::*;299 use UnaryOpType::*;300 rule expr(s: &ParserSettings) -> LocExpr301 = precedence! {302 start:position!() v:@ end:position!() { LocExpr::new(v, Span(s.source.clone(), start as u32, end as u32)) }303 --304 a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}305 a:(@) _ binop(<"??">) _ ensure_null_coaelse() b:@ {306 #[cfg(feature = "exp-null-coaelse")] return expr_bin!(a NullCoaelse b);307 unreachable!("ensure_null_coaelse will fail if feature is not enabled")308 }309 --310 a:(@) _ binop(<"&&">) _ b:@ {expr_bin!(a And b)}311 --312 a:(@) _ binop(<"|">) _ b:@ {expr_bin!(a BitOr b)}313 --314 a:@ _ binop(<"^">) _ b:(@) {expr_bin!(a BitXor b)}315 --316 a:(@) _ binop(<"&">) _ b:@ {expr_bin!(a BitAnd b)}317 --318 a:(@) _ binop(<"==">) _ b:@ {expr_bin!(a Eq b)}319 a:(@) _ binop(<"!=">) _ b:@ {expr_bin!(a Neq b)}320 --321 a:(@) _ binop(<"<">) _ b:@ {expr_bin!(a Lt b)}322 a:(@) _ binop(<">">) _ b:@ {expr_bin!(a Gt b)}323 a:(@) _ binop(<"<=">) _ b:@ {expr_bin!(a Lte b)}324 a:(@) _ binop(<">=">) _ b:@ {expr_bin!(a Gte b)}325 a:(@) _ binop(<keyword("in")>) _ b:@ {expr_bin!(a In b)}326 --327 a:(@) _ binop(<"<<">) _ b:@ {expr_bin!(a Lhs b)}328 a:(@) _ binop(<">>">) _ b:@ {expr_bin!(a Rhs b)}329 --330 a:(@) _ binop(<"+">) _ b:@ {expr_bin!(a Add b)}331 a:(@) _ binop(<"-">) _ b:@ {expr_bin!(a Sub b)}332 --333 a:(@) _ binop(<"*">) _ b:@ {expr_bin!(a Mul b)}334 a:(@) _ binop(<"/">) _ b:@ {expr_bin!(a Div b)}335 a:(@) _ binop(<"%">) _ b:@ {expr_bin!(a Mod b)}336 --337 unaryop(<"+">) _ b:@ {expr_un!(Plus b)}338 unaryop(<"-">) _ b:@ {expr_un!(Minus b)}339 unaryop(<"!">) _ b:@ {expr_un!(Not b)}340 unaryop(<"~">) _ b:@ {expr_un!(BitNot b)}341 --342 a:(@) _ "[" _ e:slice_desc(s) _ "]" {Expr::Slice(a, e)}343 indexable:(@) _ parts:index_part(s)+ {Expr::Index{indexable, parts}}344 a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {Expr::Apply(a, args, ts.is_some())}345 a:(@) _ "{" _ body:objinside(s) _ "}" {Expr::ObjExtend(a, body)}346 --347 e:expr_basic(s) {e}348 "(" _ e:expr(s) _ ")" {Expr::Parened(e)}349 }350 pub rule index_part(s: &ParserSettings) -> IndexPart351 = n:("?" _ ensure_null_coaelse())? "." _ value:id_loc(s) {IndexPart {352 value,353 #[cfg(feature = "exp-null-coaelse")]354 null_coaelse: n.is_some(),355 }}356 / n:("?" _ "." _ ensure_null_coaelse())? "[" _ value:expr(s) _ "]" {IndexPart {357 value,358 #[cfg(feature = "exp-null-coaelse")]359 null_coaelse: n.is_some(),360 }}361362 pub rule jsonnet(s: &ParserSettings) -> LocExpr = _ e:expr(s) _ {e}363 }364}365366pub type ParseError = peg::error::ParseError<peg::str::LineCol>;367pub fn parse(str: &str, settings: &ParserSettings) -> Result<LocExpr, ParseError> {368 jsonnet_parser::jsonnet(str, settings)369}370371pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> LocExpr {372 let len = str.len();373 LocExpr::new(Expr::Str(str), Span(settings.source.clone(), 0, len as u32))374}375376#[cfg(test)]377pub mod tests {378 use jrsonnet_interner::IStr;379 use BinaryOpType::*;380381 use super::{expr::*, parse};382 use crate::{source::Source, ParserSettings};383384 macro_rules! parse {385 ($s:expr) => {386 parse(387 $s,388 &ParserSettings {389 source: Source::new_virtual("<test>".into(), IStr::empty()),390 },391 )392 .unwrap()393 };394 }395396 macro_rules! el {397 ($expr:expr, $from:expr, $to:expr$(,)?) => {398 LocExpr::new(399 $expr,400 Span(401 Source::new_virtual("<test>".into(), IStr::empty()),402 $from,403 $to,404 ),405 )406 };407 }408409 #[test]410 fn multiline_string() {411 assert_eq!(412 parse!("|||\n Hello world!\n a\n|||"),413 el!(Expr::Str("Hello world!\n a\n".into()), 0, 31),414 );415 assert_eq!(416 parse!("|||\n Hello world!\n a\n|||"),417 el!(Expr::Str("Hello world!\n a\n".into()), 0, 27),418 );419 assert_eq!(420 parse!("|||\n\t\tHello world!\n\t\t\ta\n|||"),421 el!(Expr::Str("Hello world!\n\ta\n".into()), 0, 27),422 );423 assert_eq!(424 parse!("|||\n Hello world!\n a\n |||"),425 el!(Expr::Str("Hello world!\n a\n".into()), 0, 30),426 );427 }428429 #[test]430 fn slice() {431 parse!("a[1:]");432 parse!("a[1::]");433 parse!("a[:1:]");434 parse!("a[::1]");435 parse!("str[:len - 1]");436 }437438 #[test]439 fn string_escaping() {440 assert_eq!(441 parse!(r#""Hello, \"world\"!""#),442 el!(Expr::Str(r#"Hello, "world"!"#.into()), 0, 19),443 );444 assert_eq!(445 parse!(r#"'Hello \'world\'!'"#),446 el!(Expr::Str("Hello 'world'!".into()), 0, 18),447 );448 assert_eq!(parse!(r#"'\\\\'"#), el!(Expr::Str("\\\\".into()), 0, 6));449 }450451 #[test]452 fn string_unescaping() {453 assert_eq!(454 parse!(r#""Hello\nWorld""#),455 el!(Expr::Str("Hello\nWorld".into()), 0, 14),456 );457 }458459 #[test]460 fn string_verbantim() {461 assert_eq!(462 parse!(r#"@"Hello\n""World""""#),463 el!(Expr::Str("Hello\\n\"World\"".into()), 0, 19),464 );465 }466467 #[test]468 fn imports() {469 assert_eq!(470 parse!("import \"hello\""),471 el!(Expr::Import(el!(Expr::Str("hello".into()), 7, 14)), 0, 14),472 );473 assert_eq!(474 parse!("importstr \"garnish.txt\""),475 el!(476 Expr::ImportStr(el!(Expr::Str("garnish.txt".into()), 10, 23)),477 0,478 23479 )480 );481 assert_eq!(482 parse!("importbin \"garnish.bin\""),483 el!(484 Expr::ImportBin(el!(Expr::Str("garnish.bin".into()), 10, 23)),485 0,486 23487 )488 );489 }490491 #[test]492 fn empty_object() {493 assert_eq!(494 parse!("{}"),495 el!(Expr::Obj(ObjBody::MemberList(vec![])), 0, 2)496 );497 }498499 #[test]500 fn basic_math() {501 assert_eq!(502 parse!("2+2*2"),503 el!(504 Expr::BinaryOp(505 el!(Expr::Num(2.0), 0, 1),506 Add,507 el!(508 Expr::BinaryOp(el!(Expr::Num(2.0), 2, 3), Mul, el!(Expr::Num(2.0), 4, 5)),509 2,510 5511 )512 ),513 0,514 5515 )516 );517 }518519 #[test]520 fn basic_math_with_indents() {521 assert_eq!(522 parse!("2 + 2 * 2 "),523 el!(524 Expr::BinaryOp(525 el!(Expr::Num(2.0), 0, 1),526 Add,527 el!(528 Expr::BinaryOp(el!(Expr::Num(2.0), 7, 8), Mul, el!(Expr::Num(2.0), 13, 14),),529 7,530 14531 ),532 ),533 0,534 14535 )536 );537 }538539 #[test]540 fn basic_math_parened() {541 assert_eq!(542 parse!("2+(2+2*2)"),543 el!(544 Expr::BinaryOp(545 el!(Expr::Num(2.0), 0, 1),546 Add,547 el!(548 Expr::Parened(el!(549 Expr::BinaryOp(550 el!(Expr::Num(2.0), 3, 4),551 Add,552 el!(553 Expr::BinaryOp(554 el!(Expr::Num(2.0), 5, 6),555 Mul,556 el!(Expr::Num(2.0), 7, 8),557 ),558 5,559 8560 ),561 ),562 3,563 8564 )),565 2,566 9567 ),568 ),569 0,570 9571 )572 );573 }574575 576 #[test]577 fn comments() {578 assert_eq!(579 parse!("2//comment\n+//comment\n3/*test*/*/*test*/4"),580 el!(581 Expr::BinaryOp(582 el!(Expr::Num(2.0), 0, 1),583 Add,584 el!(585 Expr::BinaryOp(586 el!(Expr::Num(3.0), 22, 23),587 Mul,588 el!(Expr::Num(4.0), 40, 41)589 ),590 22,591 41592 )593 ),594 0,595 41596 )597 );598 }599600 #[test]601 fn suffix() {602 603 604 605 606 }607608 #[test]609 fn array_comp() {610 use Expr::*;611 612613614615 assert_eq!(616 parse!("[std.deepJoin(x) for x in arr]"),617 el!(618 ArrComp(619 el!(620 Apply(621 el!(622 Index {623 indexable: el!(Var("std".into()), 1, 4),624 parts: vec![IndexPart {625 value: el!(Str("deepJoin".into()), 5, 13),626 #[cfg(feature = "exp-null-coaelse")]627 null_coaelse: false,628 }],629 },630 1,631 13632 ),633 ArgsDesc::new(vec![el!(Var("x".into()), 14, 15)], vec![]),634 false,635 ),636 1,637 16638 ),639 vec![CompSpec::ForSpec(ForSpecData(640 Destruct::Full("x".into()),641 el!(Var("arr".into()), 26, 29)642 ))]643 ),644 0,645 30646 ),647 )648 }649650 #[test]651 fn reserved() {652 use Expr::*;653 assert_eq!(parse!("null"), el!(Literal(LiteralType::Null), 0, 4));654 assert_eq!(parse!("nulla"), el!(Var("nulla".into()), 0, 5));655 }656657 #[test]658 fn multiple_args_buf() {659 parse!("a(b, null_fields)");660 }661662 #[test]663 fn infix_precedence() {664 use Expr::*;665 assert_eq!(666 parse!("!a && !b"),667 el!(668 BinaryOp(669 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into()), 1, 2)), 0, 2),670 And,671 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".into()), 7, 8)), 6, 8)672 ),673 0,674 8675 )676 );677 }678679 #[test]680 fn infix_precedence_division() {681 use Expr::*;682 assert_eq!(683 parse!("!a / !b"),684 el!(685 BinaryOp(686 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into()), 1, 2)), 0, 2),687 Div,688 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".into()), 6, 7)), 5, 7)689 ),690 0,691 7692 )693 );694 }695696 #[test]697 fn double_negation() {698 use Expr::*;699 assert_eq!(700 parse!("!!a"),701 el!(702 UnaryOp(703 UnaryOpType::Not,704 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into()), 2, 3)), 1, 3)705 ),706 0,707 3708 )709 )710 }711712 #[test]713 fn array_test_error() {714 parse!("[a for a in b if c for e in f]");715 716 }717718 #[test]719 fn missing_newline_between_comment_and_eof() {720 parse!(721 "{a:1}722723 //+213"724 );725 }726727 #[test]728 fn default_param_before_nondefault() {729 parse!("local x(foo = 'foo', bar) = null; null");730 }731732 #[test]733 fn add_location_info_to_all_sub_expressions() {734 use Expr::*;735736 let file_name = Source::new_virtual("<test>".into(), IStr::empty());737 let expr = parse(738 "{} { local x = 1, x: x } + {}",739 &ParserSettings { source: file_name },740 )741 .unwrap();742 assert_eq!(743 expr,744 el!(745 BinaryOp(746 el!(747 ObjExtend(748 el!(Obj(ObjBody::MemberList(vec![])), 0, 2),749 ObjBody::MemberList(vec![750 Member::BindStmt(BindSpec::Field {751 into: Destruct::Full("x".into()),752 value: el!(Num(1.0), 15, 16)753 }),754 Member::Field(FieldMember {755 name: FieldName::Fixed("x".into()),756 plus: false,757 params: None,758 visibility: Visibility::Normal,759 value: el!(Var("x".into()), 21, 22),760 })761 ])762 ),763 0,764 24765 ),766 BinaryOpType::Add,767 el!(Obj(ObjBody::MemberList(vec![])), 27, 29),768 ),769 0,770 29771 ),772 );773 }774}