Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

All notable milestones for the nera project are documented in this file.

## Bare binary comprehension bodies match `erlc`

- Bare calls, signed expressions, map literals, record literals and record
indexes are syntax errors as binary comprehension bodies. For example, write
`<< (id(X)) || X <- L >>` instead of `<< id(X) || X <- L >>`.
- `nera fmt` leaves rejected bodies as written and keeps required parentheses
on valid bodies.

## Native `erlang:send/2,3`

- Direct and dynamic `erlang:send/2,3` calls now send to a pid, a registered
Expand Down Expand Up @@ -104,10 +112,10 @@ All notable milestones for the nera project are documented in this file.
Previously it removed them. `erlc` rejects the result, and Nera read the
remote call as a segment `erlang` with a size, so a second format deleted
the call.
- A body that OTP only accepts in parentheses, such as a call, an operator
expression, a map, a record or a signed number, is always printed with them.
Binaries and variables stay bare, and other bodies keep the form they were
written in.
- The formatter keeps the parentheses on valid bodies that OTP requires to be
parenthesized, such as calls, operator expressions, maps, records and signed
numbers. Binaries and variables stay bare, and other bodies keep the form
they were written in.

## Non-boolean comprehension filters raise bad_filter

Expand Down
41 changes: 3 additions & 38 deletions crates/nera-fmt/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1607,17 +1607,12 @@ impl<'src> Formatter<'src> {
needs_parens_in_bin_segment(size) || self.span_text(size.span()).starts_with(['-', '+'])
}

/// Whether a binary comprehension body is printed in parentheses.
///
/// OTP accepts only a primary expression here, and Nera reads a bare
/// `M:F(...)` as a segment with a size. The AST drops source parentheses,
/// so a body that may stay bare keeps the ones it was written with: what
/// a macro expands to can depend on them.
/// The parser checks which bodies require parentheses, but drops them from
/// the AST. Keep source parentheses where a macro may expand to a body
/// that needs them.
fn bin_comp_body_needs_parens(&self, comp_start: usize, body: &Expr) -> bool {
match body {
Expr::Variable(..) | Expr::Binary(..) | Expr::BinComp(..) => false,
_ if !is_primary_expr(body) => true,
_ if self.span_text(body.span()).starts_with(['-', '+']) => true,
_ => {
// Only blanks, comments and open parentheses precede the body.
let before_body = Span::new(comp_start + "<<".len(), body.span().start);
Expand Down Expand Up @@ -1777,36 +1772,6 @@ fn needs_parens_in_bin_segment(expr: &Expr) -> bool {
)
}

/// Returns true for the forms OTP's grammar calls `expr_max`, which need no
/// parentheses where only a primary expression is allowed. A macro counts:
/// its expansion decides, and it may expand to a binary.
fn is_primary_expr(expr: &Expr) -> bool {
matches!(
expr,
Expr::Integer(..)
| Expr::BigInteger(..)
| Expr::Float(..)
| Expr::Atom(..)
| Expr::String(..)
| Expr::Nil(..)
| Expr::Variable(..)
| Expr::Tuple(..)
| Expr::Cons(..)
| Expr::Binary(..)
| Expr::ListComp(..)
| Expr::BinComp(..)
| Expr::Block(..)
| Expr::If(..)
| Expr::Case(..)
| Expr::Receive(..)
| Expr::Try { .. }
| Expr::Fun(..)
| Expr::FunRef(..)
| Expr::Maybe { .. }
| Expr::MacroCall { .. }
)
}

fn binop_str(op: BinOp) -> &'static str {
match op {
BinOp::Add => "+",
Expand Down
15 changes: 12 additions & 3 deletions crates/nera-fmt/tests/binary_comprehension_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ fn check(written: &str, printed: &str) {

#[test]
fn call_bodies_keep_their_parentheses() {
// A bare remote call would read as a segment with a size, and OTP rejects
// any bare call in this position.
check("(erlang:error(boom))", "(erlang:error(boom))");
check("(?MODULE:id(X))", "(?MODULE:id(X))");
check("(id(1))", "(id(1))");
check("id(1)", "(id(1))");

// Leave an invalid call as written rather than silently fixing its syntax.
let source = comprehension("id(1)");
assert_eq!(format_source(&source, &FormatConfig::default()).unwrap(), source);
}

#[test]
Expand Down Expand Up @@ -89,6 +90,14 @@ fn a_parenthesis_in_a_leading_comment_is_not_a_parenthesis() {
assert!(formatted.contains("1 ||") && !formatted.contains("(1)"), "{formatted}");
}

#[test]
fn bare_non_call_bodies_otp_rejects_are_left_as_written() {
for body in ["-1", "+1", "#{a => X}", "#r{a = X}", "#r.a"] {
let source = comprehension(body);
assert_eq!(format_source(&source, &FormatConfig::default()).unwrap(), source);
}
}

// 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]
Expand Down
35 changes: 29 additions & 6 deletions crates/nera-syntax/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1554,10 +1554,11 @@ impl<'src> Parser<'src> {
// ── Binary expression or binary comprehension ──
Token::BinOpen => {
self.advance();
let body_start = self.pos;
let segments = self.parse_bin_segments_expr()?;
// Check for binary comprehension: << Body || Qualifiers >>
if self.check(&Token::DoublePipe) {
let body_expr = self.bin_comp_body(segments)?;
let body_expr = self.bin_comp_body(body_start, segments)?;
self.advance(); // consume '||'
let qualifiers = self.parse_lc_qualifiers()?;
self.expect(&Token::BinClose)?;
Expand Down Expand Up @@ -2547,13 +2548,35 @@ 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<BinSegment<Expr>>) -> Result<Expr, ParseError> {
/// OTP takes one primary expression (`expr_max`) before `||`, not a segment.
fn bin_comp_body(
&self,
body_start: usize,
mut segments: Vec<BinSegment<Expr>>,
) -> Result<Expr, ParseError> {
if let [segment] = segments.as_slice() {
if segment.size.is_none() && !segment.type_spec.explicit {
// The AST drops parentheses and can fold a leading sign into a literal.
let first = &self.tokens[body_start].0;
if !matches!(first, Token::LParen)
&& (matches!(first, Token::Minus | Token::Plus)
|| matches!(
segment.value,
Expr::Call(..)
| Expr::Map(..)
| Expr::RecordCreate { .. }
| Expr::RecordIndex { .. }
))
{
return Err(ParseError::UnexpectedToken {
expected: "parentheses around this binary comprehension body".into(),
found: "a bare expression".into(),
span: segment.span,
hint: Some(
"wrap the body in parentheses, as in `<< (id(X)) || X <- L >>`".into(),
),
});
}
return Ok(segments.remove(0).value);
}
}
Expand Down
23 changes: 23 additions & 0 deletions crates/nera-syntax/tests/binary_comprehension_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,29 @@ fn a_body_written_as_a_segment_is_a_syntax_error() {
}
}

#[test]
fn otp_requires_parentheses_around_non_primary_bodies() {
for body in [
"id(1)",
"F(X)",
"-1",
"+1",
"-0",
"-1.5",
"-123456789012345678901234567890",
"#{a => 1}",
"#r{a = X}",
"#r.a",
] {
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);
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 [
Expand Down
Loading