diff --git a/CHANGELOG.md b/CHANGELOG.md index 0659938..9912a23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable milestones for the nera project are documented in this file. +## Binary comprehension bodies written as segments are rejected + +- A binary comprehension body with a size, a type or several segments, such as + `<< X:16 || X <- L >>` or `<< X, Y || X <- L >>`, is now a compile error, as + in `erlc`. Previously Nera compiled it and ignored the size and type. +- A bare remote call such as `<< erlang:error(boom) || _ <- L >>` is also an + error. Previously Nera read `erlang` as the value and the call as its size, + so the call never ran. Write `<< (erlang:error(boom)) || _ <- L >>`. +- `nera fmt` leaves these bodies as written instead of deleting the size, the + type or the call. + ## Formatter keeps trailing comments on their lines - `nera fmt` now keeps a trailing comment on the line of the code it follows, diff --git a/crates/nera-fmt/tests/binary_comprehension_body.rs b/crates/nera-fmt/tests/binary_comprehension_body.rs index 26eca94..925bc6d 100644 --- a/crates/nera-fmt/tests/binary_comprehension_body.rs +++ b/crates/nera-fmt/tests/binary_comprehension_body.rs @@ -88,3 +88,20 @@ fn a_parenthesis_in_a_leading_comment_is_not_a_parenthesis() { let formatted = format_source(&source, &FormatConfig::default()).unwrap(); assert!(formatted.contains("1 ||") && !formatted.contains("(1)"), "{formatted}"); } + +// OTP rejects these bodies, so the formatter has no valid form to print and +// must not delete the size, the type or the call. +#[test] +fn a_body_written_as_a_segment_is_left_as_written() { + for body in ["X:16", "X/binary", "erlang:error(boom)", "X, X"] { + let source = comprehension(body); + assert_eq!(format_source(&source, &FormatConfig::default()).unwrap(), source); + } +} + +// erlc accepts a macro that is never used, whatever its body is. +#[test] +fn an_unused_macro_keeps_a_body_written_as_a_segment() { + let source = "-module(t).\n-define(U(E), << E:8 || _ <- [a] >>).\n"; + assert_eq!(format_source(source, &FormatConfig::default()).unwrap(), source); +} diff --git a/crates/nera-syntax/src/parser.rs b/crates/nera-syntax/src/parser.rs index 2a98da7..5deb951 100644 --- a/crates/nera-syntax/src/parser.rs +++ b/crates/nera-syntax/src/parser.rs @@ -1532,14 +1532,9 @@ impl<'src> Parser<'src> { self.advance(); let segments = self.parse_bin_segments_expr()?; // Check for binary comprehension: << Body || Qualifiers >> - if self.eat(&Token::DoublePipe) { - // Binary comprehension: extract body expression from the single segment - let body_expr = if segments.len() == 1 { - segments.into_iter().next().unwrap().value - } else { - // Multiple segments or empty: wrap back into Binary - Expr::Binary(segments, span) - }; + if self.check(&Token::DoublePipe) { + let body_expr = self.bin_comp_body(segments)?; + self.advance(); // consume '||' let qualifiers = self.parse_lc_qualifiers()?; self.expect(&Token::BinClose)?; let end = self.prev_span(); @@ -2528,6 +2523,29 @@ impl<'src> Parser<'src> { Ok(segments) } + /// The body of a binary comprehension, read from the segments before `||`. + /// + /// OTP's grammar takes one expression here, not a segment, so a size, a + /// type or a second segment is a syntax error rather than a part to drop. + fn bin_comp_body(&self, mut segments: Vec>) -> Result { + if let [segment] = segments.as_slice() { + if segment.size.is_none() && !segment.type_spec.explicit { + return Ok(segments.remove(0).value); + } + } + let body_span = segments[0].span.merge(segments[segments.len() - 1].span); + Err(ParseError::UnexpectedToken { + expected: "a single expression as the binary comprehension body".into(), + found: "a binary segment".into(), + span: body_span, + hint: Some( + "put segments in their own binary, as in `<< <> || ... >>`, \ + and a remote call in parentheses, as in `<< (m:f(X)) || ... >>`" + .into(), + ), + }) + } + /// Parse a single binary segment expression: `Value[:Size][/TypeSpecifiers]` fn parse_bin_segment_expr(&mut self) -> Result, ParseError> { let start = self.current_span(); diff --git a/crates/nera-syntax/tests/binary_comprehension_body.rs b/crates/nera-syntax/tests/binary_comprehension_body.rs new file mode 100644 index 0000000..d30a959 --- /dev/null +++ b/crates/nera-syntax/tests/binary_comprehension_body.rs @@ -0,0 +1,59 @@ +use nera_syntax::{ast::Expr, error::ParseError, parser::Parser}; + +fn parse(body: &str) -> (String, nera_syntax::parser::ParseResult) { + let source = format!("-module(t).\nf(X) -> << {body} || _ <- [a] >>.\n"); + let result = Parser::new(&source).parse_module(); + (source, result) +} + +// Each form is a syntax error in OTP's erl_parse, which takes one expression +// before `||`. Nera used to keep the value and drop the rest. +#[test] +fn a_body_written_as_a_segment_is_a_syntax_error() { + for body in [ + "X:16", + "X/binary", + "X/utf8", + "X:16/little", + "X:8/integer-unit:1", + "<>:8", + "(X):8", + "1:8", + "\"a\":8", + "-1:8", + "+1:8", + "?S:8", + "erlang:error(boom)", + "lists:reverse(X)", + "?MODULE:id(X)", + "m:f", + "X, X", + "X:8, X", + "<>, <>", + ] { + let (source, result) = parse(body); + let [ParseError::UnexpectedToken { span, hint, .. }] = result.errors.as_slice() else { + panic!("{body} should be one syntax error, got {:?}", result.errors); + }; + assert_eq!(&source[span.start..span.end], body, "the error should mark the body"); + assert!(hint.is_some(), "{body} should say how to write it"); + } +} + +#[test] +fn a_body_of_one_expression_keeps_its_value() { + for (body, is_expected) in [ + ("X", (|e| matches!(e, Expr::Variable(..))) as fn(&Expr) -> bool), + ("<>", |e| matches!(e, Expr::Binary(segments, _) if segments[0].size.is_some())), + ("<>", |e| matches!(e, Expr::Binary(segments, _) if segments.len() == 2)), + ("<< <> || Y <- [X] >>", |e| matches!(e, Expr::BinComp(..))), + ("(erlang:error(boom))", |e| matches!(e, Expr::Call(..))), + ] { + let (_, result) = parse(body); + assert!(!result.has_errors(), "{body}: {:?}", result.errors); + let Expr::BinComp(kept, ..) = &result.module.functions[0].clauses[0].body[0] else { + panic!("{body} is not a binary comprehension"); + }; + assert!(is_expected(kept), "{body} parsed as {kept:?}"); + } +}