Skip to content

Commit 64b88b9

Browse files
authored
fix(compiler): support checked unary plus expressions
Compile unary plus in expressions, guards, binary values and signed literal patterns. Preserve big integers, floating-point bits and signed zero without converting numbers. Keep unary-plus grouping when formatting Erlang programs.
1 parent 52001d3 commit 64b88b9

11 files changed

Lines changed: 365 additions & 18 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@ All notable milestones for the nera project are documented in this file.
1414
including a pending kill signal, and checks blocked-only termination through
1515
the worker's idle path. Ready, running and unwoken waits are controls.
1616

17+
## Unary plus compiles and checks its operand
18+
19+
- Unary plus expressions such as `+X` and `+id(1)` now compile natively.
20+
As on BEAM, a number is returned unchanged, including big integers and
21+
the sign of floating-point zero; a non-number raises `error:badarith`.
22+
- In a guard, an invalid operand fails the guard. In a `try` body, the
23+
error reaches the handler before later expressions run.
24+
- Formatting preserves unary plus and its operand grouping.
25+
- The `unary_plus` fixture checks these behaviors natively and on BEAM.
26+
1727
## Funs stored in ETS and persistent_term keep their captured values
1828

1929
- A fun inserted into an ETS table or stored with `persistent_term:put/2`

‎crates/nera-codegen/src/func_translator/instructions.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,9 @@ impl FuncTranslator {
261261
let needs_exception_check = true;
262262

263263
let val = match op {
264+
nera_syntax::ast::UnaryOp::Pos => {
265+
self.emit_ffi_call(module, builder, "nera_rt_unary_plus", ctx_var, &[operand_val])?
266+
}
264267
nera_syntax::ast::UnaryOp::Neg => {
265268
self.emit_ffi_call(module, builder, "nera_rt_negate", ctx_var, &[operand_val])?
266269
}
@@ -306,7 +309,7 @@ impl FuncTranslator {
306309
builder.def_var(*var, val);
307310
}
308311

309-
// Check for exception after negate FFI call
312+
// Check for exception after the unary operation
310313
// (skip if inside a try block — CheckException handles it)
311314
if needs_exception_check && !is_try_protected {
312315
self.emit_ffi_exception_check(module, builder, ctx_var)?;

‎crates/nera-fmt/src/format.rs‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -589,15 +589,18 @@ impl<'src> Formatter<'src> {
589589
}
590590
Expr::UnaryOp(op, operand, _) => {
591591
let op_str = match op {
592+
UnaryOp::Pos => "+",
592593
UnaryOp::Neg => "-",
593594
UnaryOp::Not => "not ",
594595
UnaryOp::Bnot => "bnot ",
595596
};
596597
let operand_doc = self.format_expr(operand);
597-
// Preserve weaker-binding operands and avoid turning nested
598-
// negation into the `--` token after parentheses are discarded.
598+
// Preserve weaker-binding operands and avoid turning repeated
599+
// signs into the `++` or `--` token after grouping is discarded.
599600
let needs_grouping = matches!(operand.as_ref(),
600601
Expr::BinOp(..) | Expr::Match(..) | Expr::Send(..) | Expr::Catch(..))
602+
|| (*op == UnaryOp::Pos && matches!(operand.as_ref(),
603+
Expr::UnaryOp(UnaryOp::Pos, ..)))
601604
|| (*op == UnaryOp::Neg && match operand.as_ref() {
602605
Expr::UnaryOp(UnaryOp::Neg, ..) => true,
603606
Expr::Integer(value, _) => *value < 0,
@@ -1500,7 +1503,11 @@ impl<'src> Formatter<'src> {
15001503

15011504
fn format_bin_segment_expr(&mut self, seg: &BinSegment<Expr>) -> Doc {
15021505
let value_doc = self.format_expr(&seg.value);
1503-
let mut parts = if needs_parens_in_bin_segment(&seg.value) {
1506+
// Numeric unary plus may retain several signs in its source spelling
1507+
// (for example +-0.0); only one bare sign is valid in a binary value.
1508+
let mut parts = if needs_parens_in_bin_segment(&seg.value)
1509+
|| self.span_text(seg.value.span()).starts_with('+')
1510+
{
15041511
vec![text("("), value_doc, text(")")]
15051512
} else {
15061513
vec![value_doc]
@@ -1561,9 +1568,9 @@ impl<'src> Formatter<'src> {
15611568
}
15621569

15631570
fn bin_size_needs_parens(&self, size: &Expr) -> bool {
1564-
// The parser folds negative numbers into literals, but their leading
1565-
// minus still needs grouping in a size, including spellings like -0.
1566-
needs_parens_in_bin_segment(size) || self.span_text(size.span()).starts_with('-')
1571+
// The parser folds signed numbers into literals, but their leading
1572+
// sign still needs grouping in a size, including spellings like -0.
1573+
needs_parens_in_bin_segment(size) || self.span_text(size.span()).starts_with(['-', '+'])
15671574
}
15681575

15691576
fn format_bin_type_spec(&mut self, spec: &BinSegmentType) -> String {
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
use nera_fmt::{config::FormatConfig, format_source};
2+
use nera_syntax::{
3+
ast::{BinOp, Expr, UnaryOp},
4+
parser::Parser,
5+
};
6+
7+
// Newly accepted unary plus must not become list append or lose the grouping
8+
// of a weaker-binding operand when a program is formatted.
9+
#[test]
10+
fn formatted_unary_plus_keeps_the_expression_tree() {
11+
let source = "-module(unary_plus).
12+
f(X) -> +(+X).
13+
g(X) -> +(X + 2) * 2.
14+
h(X) -> id((+X)), m:f((+X)), F((+X)), {(+X)}, ?IDENTITY((+X)), maybe (+X) end.";
15+
let formatted = format_source(source, &FormatConfig::default()).unwrap();
16+
let result = Parser::new(&formatted).parse_module();
17+
assert!(result.errors.is_empty(), "{:?}", result.errors);
18+
assert!(matches!(&result.module.functions[0].clauses[0].body[0],
19+
Expr::UnaryOp(UnaryOp::Pos, operand, _)
20+
if matches!(operand.as_ref(), Expr::UnaryOp(UnaryOp::Pos, inner, _)
21+
if matches!(inner.as_ref(), Expr::Variable(..)))));
22+
let Expr::BinOp(BinOp::Mul, positive, _, _) = &result.module.functions[1].clauses[0].body[0]
23+
else {
24+
panic!("lost outer multiplication: {formatted}");
25+
};
26+
assert!(
27+
matches!(positive.as_ref(), Expr::UnaryOp(UnaryOp::Pos, operand, _)
28+
if matches!(operand.as_ref(), Expr::BinOp(BinOp::Add, ..)))
29+
);
30+
let body = &result.module.functions[2].clauses[0].body;
31+
for call in &body[..3] {
32+
assert!(matches!(call, Expr::Call(_, args, _)
33+
if matches!(args.as_slice(), [Expr::UnaryOp(UnaryOp::Pos, _, _)])));
34+
}
35+
assert!(matches!(&body[3], Expr::Tuple(elements, _)
36+
if matches!(elements.as_slice(), [Expr::UnaryOp(UnaryOp::Pos, _, _)])));
37+
assert!(matches!(&body[4], Expr::MacroCall { args: Some(args), .. }
38+
if matches!(args.as_slice(), [Expr::UnaryOp(UnaryOp::Pos, _, _)])));
39+
assert!(matches!(&body[5], Expr::Maybe { .. }));
40+
assert_eq!(
41+
formatted,
42+
format_source(&formatted, &FormatConfig::default()).unwrap()
43+
);
44+
}
45+
46+
// Numeric normalization must keep the whole consumed spelling, including the
47+
// closing parenthesis, in expressions and expression-derived match patterns.
48+
#[test]
49+
fn formatted_parenthesized_positive_literals_keep_complete_spans() {
50+
for literal in ["1", "9223372036854775808", "1.5"] {
51+
let source = format!(
52+
"-module(unary_plus). f() -> +({literal}).
53+
g() -> +({literal}) = id({literal}).
54+
h() -> <<+({literal})/float>>."
55+
);
56+
let formatted = format_source(&source, &FormatConfig::default()).unwrap();
57+
let result = Parser::new(&formatted).parse_module();
58+
assert!(result.errors.is_empty(), "{:?}: {formatted}", result.errors);
59+
assert!(matches!(
60+
&result.module.functions[0].clauses[0].body[0],
61+
Expr::Integer(..) | Expr::BigInteger(..) | Expr::Float(..)
62+
));
63+
assert!(matches!(
64+
&result.module.functions[1].clauses[0].body[0],
65+
Expr::Match(..)
66+
));
67+
assert_eq!(
68+
formatted,
69+
format_source(&formatted, &FormatConfig::default()).unwrap()
70+
);
71+
}
72+
}
73+
74+
// Construction and pattern segments share size formatting; both must preserve
75+
// the parentheses required around a signed size, including comprehension sites.
76+
#[test]
77+
fn formatted_positive_binary_sizes_keep_required_grouping() {
78+
let source = "-module(unary_plus).
79+
f() -> <<1:(+8)>>.
80+
g(<<X:(+8)>>) -> X.
81+
h() -> << <<X:(+8)>> || <<X:(+8)>> <= <<1, 2>> >>.";
82+
let formatted = format_source(source, &FormatConfig::default()).unwrap();
83+
let result = Parser::new(&formatted).parse_module();
84+
assert!(result.errors.is_empty(), "{:?}: {formatted}", result.errors);
85+
assert_eq!(result.module.functions.len(), 3);
86+
assert_eq!(
87+
formatted,
88+
format_source(&formatted, &FormatConfig::default()).unwrap()
89+
);
90+
}
91+
92+
// A folded number may retain compound signs in its spelling. Such spellings
93+
// are expressions, not bare binary values, even though the AST is a literal.
94+
#[test]
95+
fn formatted_compound_signed_binary_values_keep_grouping() {
96+
let source = "-module(unary_plus). f() -> <<(+-0.0)/float, (+-1):8, (+ +1):8>>.";
97+
let formatted = format_source(source, &FormatConfig::default()).unwrap();
98+
let result = Parser::new(&formatted).parse_module();
99+
assert!(result.errors.is_empty(), "{:?}: {formatted}", result.errors);
100+
let Expr::Binary(segments, _) = &result.module.functions[0].clauses[0].body[0] else {
101+
panic!("lost binary construction: {formatted}");
102+
};
103+
assert_eq!(segments.len(), 3);
104+
assert!(matches!(&segments[0].value, Expr::Float(value, _) if value.is_sign_negative()));
105+
assert!(matches!(&segments[1].value, Expr::Integer(-1, _)));
106+
assert!(matches!(&segments[2].value, Expr::Integer(1, _)));
107+
assert_eq!(
108+
formatted,
109+
format_source(&formatted, &FormatConfig::default()).unwrap()
110+
);
111+
}

‎crates/nera-ir/src/lower/expr.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1608,8 +1608,8 @@ impl IrBuilder {
16081608
}
16091609
}
16101610
ast::Expr::UnaryOp(op, _operand, _) => match op {
1611-
// not/neg/bnot can throw (badarg/badarith) on non-boolean/non-numeric operands
1612-
ast::UnaryOp::Not | ast::UnaryOp::Neg | ast::UnaryOp::Bnot => true,
1611+
// Unary operators can throw (badarg/badarith) on invalid operand types.
1612+
ast::UnaryOp::Not | ast::UnaryOp::Pos | ast::UnaryOp::Neg | ast::UnaryOp::Bnot => true,
16131613
},
16141614
// Function calls can throw
16151615
ast::Expr::Call(_, _, _) => true,

‎crates/nera-runtime/src/ffi/arith.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,20 @@ pub unsafe extern "C" fn nera_rt_int_rem(ctx: *mut ProcessContext, a: u64, b: u6
223223
raise_badarith(ctx)
224224
}
225225

226+
/// Unary plus preserves the original number, including bigint and float storage.
227+
///
228+
/// # Safety
229+
/// The context must be live and exclusively accessible. Boxed input storage
230+
/// must remain live and unmoved for this call.
231+
#[no_mangle]
232+
pub unsafe extern "C" fn nera_rt_unary_plus(ctx: *mut ProcessContext, value: u64) -> u64 {
233+
if is_numeric(ErlTerm(value)) {
234+
value
235+
} else {
236+
raise_badarith(ctx)
237+
}
238+
}
239+
226240
/// Unary negation. Works on ints and floats.
227241
#[no_mangle]
228242
pub unsafe extern "C" fn nera_rt_negate(ctx: *mut ProcessContext, a: u64) -> u64 {

‎crates/nera-syntax/src/ast.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,7 @@ pub enum BinOp {
616616
/// Unary operators.
617617
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
618618
pub enum UnaryOp {
619+
Pos,
619620
Neg,
620621
Not,
621622
Bnot,

‎crates/nera-syntax/src/parser.rs‎

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,6 +1207,13 @@ impl<'src> Parser<'src> {
12071207
}
12081208

12091209
fn parse_unary(&mut self) -> Result<Expr, ParseError> {
1210+
if self.check(&Token::Plus) {
1211+
let span_start = self.current_span();
1212+
self.advance();
1213+
let operand = self.parse_expr_bp(14)?;
1214+
let span = span_start.merge(self.prev_span());
1215+
return Ok(unary_plus_expr(operand, span));
1216+
}
12101217
if self.check(&Token::Minus) {
12111218
let span_start = self.current_span();
12121219
self.advance();
@@ -1715,7 +1722,7 @@ impl<'src> Parser<'src> {
17151722
| Token::KwBnot | Token::KwFun | Token::KwModule | Token::KwExport
17161723
| Token::KwImport | Token::KwThrow | Token::KwBegin | Token::KwMaybe
17171724
| Token::KwTry | Token::LParen | Token::LBrace | Token::LBracket
1718-
| Token::BinOpen | Token::Hash | Token::Minus
1725+
| Token::BinOpen | Token::Hash | Token::Minus | Token::Plus
17191726
| Token::MacroFunctionName | Token::MacroFunctionArity)
17201727
} {
17211728
self.advance();
@@ -1946,6 +1953,7 @@ impl<'src> Parser<'src> {
19461953
| Token::BinOpen
19471954
| Token::Hash
19481955
| Token::Minus
1956+
| Token::Plus
19491957
| Token::MacroFunctionName
19501958
| Token::MacroFunctionArity
19511959
| Token::Question
@@ -2170,16 +2178,17 @@ impl<'src> Parser<'src> {
21702178
}
21712179
Ok(Pattern::String(content, str_span))
21722180
}
2173-
Token::Minus => {
2174-
// Negative number pattern
2181+
Token::Plus | Token::Minus => {
2182+
// Signed numeric literal pattern.
2183+
let negative = tok == Token::Minus;
21752184
self.advance();
21762185
if let Some((Token::Integer(n), int_span)) = self.peek_token() {
21772186
let n = *n;
21782187
let int_span = *int_span;
21792188
self.advance();
2180-
Ok(Pattern::Integer(-n, span.merge(int_span)))
2189+
Ok(Pattern::Integer(if negative { -n } else { n }, span.merge(int_span)))
21812190
} else if let Some((Token::BigInteger(value), int_span)) = self.peek_token() {
2182-
let value = format!("-{value}");
2191+
let value = if negative { format!("-{value}") } else { value.clone() };
21832192
let span = span.merge(*int_span);
21842193
self.advance();
21852194
Ok(match value.parse::<i64>() {
@@ -2190,10 +2199,10 @@ impl<'src> Parser<'src> {
21902199
let f = *f;
21912200
let f_span = *f_span;
21922201
self.advance();
2193-
Ok(Pattern::Float(-f, span.merge(f_span)))
2202+
Ok(Pattern::Float(if negative { -f } else { f }, span.merge(f_span)))
21942203
} else {
21952204
Err(ParseError::UnexpectedToken {
2196-
expected: "number after '-' in pattern".into(),
2205+
expected: format!("number after {} in pattern", tok.description()),
21972206
found: self.current_description(),
21982207
span,
21992208
hint: None,
@@ -2345,6 +2354,7 @@ impl<'src> Parser<'src> {
23452354
| Token::KwFalse
23462355
| Token::KwThrow
23472356
| Token::Minus
2357+
| Token::Plus
23482358
| Token::LBrace
23492359
| Token::LBracket
23502360
| Token::LParen
@@ -2523,7 +2533,13 @@ impl<'src> Parser<'src> {
25232533
let start = self.current_span();
25242534
// Handle unary minus for negative numeric literals in binary segments
25252535
// e.g., <<-1.5:64/float>> or <<-42:16>>
2526-
let value = if self.check(&Token::Minus) {
2536+
let value = if self.eat(&Token::Plus) {
2537+
// A segment's size colon and type slash belong to this parser,
2538+
// not to unary expression parsing (which also reads remote calls).
2539+
let operand = self.parse_primary()?;
2540+
let span = start.merge(self.prev_span());
2541+
unary_plus_expr(operand, span)
2542+
} else if self.check(&Token::Minus) {
25272543
let neg_start = self.current_span();
25282544
self.advance();
25292545
if let Some((Token::Integer(n), int_span)) = self.peek_token() {
@@ -3614,9 +3630,20 @@ impl<'src> Parser<'src> {
36143630
}
36153631

36163632
// ---------------------------------------------------------------------------
3617-
// Span helpers for AST nodes
3633+
// AST construction and span helpers
36183634
// ---------------------------------------------------------------------------
36193635

3636+
// Keep numeric unary plus usable wherever a literal is required, while
3637+
// retaining the checked operation for every dynamic or nonnumeric operand.
3638+
fn unary_plus_expr(operand: Expr, span: Span) -> Expr {
3639+
match operand {
3640+
Expr::Integer(value, _) => Expr::Integer(value, span),
3641+
Expr::BigInteger(value, _) => Expr::BigInteger(value, span),
3642+
Expr::Float(value, _) => Expr::Float(value, span),
3643+
other => Expr::UnaryOp(UnaryOp::Pos, Box::new(other), span),
3644+
}
3645+
}
3646+
36203647
fn expr_span(expr: &Expr) -> Span {
36213648
match expr {
36223649
Expr::Integer(_, s)

0 commit comments

Comments
 (0)