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
20 changes: 12 additions & 8 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ Supported format directives: `~w` (write term), `~p` (basic term rendering),
`~tw`/`~tp` (Unicode term modifiers), `~d` (legacy decimal extension),
`~b`/`~B` (integer with optional radix), `~x`/`~X` (integer with supplied
prefix), `~+`/`~#` (integer with radix prefix), `~f`/`~e`/`~g` (float),
`~c`/`~tc` (character), `~W`/`~P` (depth-limited `~w`/`~p`), `~n`
`~c`/`~tc` (character), `~W`/`~P` (depth-limited term writers), `~n`
(newline), `~~` (tilde) and `~i` (ignore).

`io:format/2`, `io:fwrite/2` and `io_lib:format/2` share field parsing:
Expand All @@ -306,19 +306,23 @@ truncate/pad; floats use decimal precision and BEAM-style rounding (six digits
by default). For example, `~.3f` prints `0.019` for `0.019`, while `~5w ~w`
prints ` a b` for `[a,b]`. Malformed fields and missing/extra arguments raise
`badarg` before stdout output. `~p` fields consume their arguments but do not
implement pretty-printer line wrapping/indentation. `~W` and `~P` take a term
and a depth and replace what lies deeper with `...`, as OTP does: `[1,2|...]`
for `[1,2,3,4,5]` at depth 3, `...` at depth 0 and the whole term at a negative
depth. They differ only for maps, where `~W` follows `io_lib:write/2` and `~P`
the pretty printer.
implement pretty-printer line wrapping/indentation. Plain `~p` quotes nonempty
printable Latin-1 binaries as `<<"abc">>` even inside other terms. Empty
binaries, binaries containing nonprintable bytes, and partial-byte bitstrings
keep their numeric form. `~lp` disables binary quoting, and `~w` writes bytes
numerically. `~tp` and `~P` still write binaries numerically.
`~W` and `~P` take a term and a depth and replace what lies deeper with `...`,
as OTP does: `[1,2|...]` for `[1,2,3,4,5]` at depth 3, `...` at depth 0 and the
whole term at a negative depth. They differ only for maps, where `~W` follows
`io_lib:write/2` and `~P` the pretty printer.
`~w`, `~p`, `~W` and `~P` write atoms as OTP does: bare only when they start
with a lowercase letter and hold only letters, digits, `_` and `@`, and are
not reserved words; otherwise quoted, with escapes inside the quotes
(`'EXIT'`, `'hello world'`, `'maybe'`, `'it\'s'`). Characters above 255 print
as `\x{...}` unless `t` is given.
Unicode string directives decode each binary independently as UTF-8, falling
back to Latin-1 bytes for that entire binary if decoding fails. The `l` modifier
accepts printable lists as numeric lists, as basic `~p` and `~P` already do.
back to Latin-1 bytes for that entire binary if decoding fails. Printable lists
still render as lists with or without the `l` modifier.
The `k` and `K` map-order modifiers are accepted, and `K`
consumes its order argument, but neither changes map output order yet.
The separate `error_logger` renderer is unchanged.
Expand Down
113 changes: 75 additions & 38 deletions crates/nera-runtime/src/bif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,12 @@
//! let _ = bif::bif_term_to_binary(&mut heap, &[ErlTerm::nil()]);
//! ```

use crate::binary::BinaryData;
use crate::atom_table::{global_atom_table, ATOM_BADARG, ATOM_FALSE, ATOM_OK, ATOM_TRUE};
use crate::bigint::{bigint_to_term, term_to_bigint};
use crate::heap::{MapPairs, ProcessHeap};
use crate::term::{
BoxedHeader, ErlTerm, BOXED_BIGINT, BOXED_BINARY, BOXED_CLOSURE, BOXED_FLOAT,
BOXED_MAP, BOXED_REFC_BINARY, BOXED_REFERENCE, BOXED_TUPLE,
REFC_BINARY_OFFSET_WORD_INDEX, REFC_BINARY_PTR_WORD_INDEX,
};

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -1091,6 +1089,30 @@ fn format_binary_bytes(bytes: &[u8], bit_count: usize) -> String {
}
}

fn format_binary_string(bytes: &[u8]) -> Option<String> {
if bytes.is_empty() {
return None;
}
let mut out = String::from("<<\"");
for &byte in bytes {
match byte {
b'"' => out.push_str("\\\""),
b'\\' => out.push_str("\\\\"),
b'\n' => out.push_str("\\n"),
b'\r' => out.push_str("\\r"),
b'\t' => out.push_str("\\t"),
11 => out.push_str("\\v"),
8 => out.push_str("\\b"),
12 => out.push_str("\\f"),
27 => out.push_str("\\e"),
b' '..=b'~' | 160..=255 => out.push(char::from(byte)),
_ => return None,
}
}
out.push_str("\">>");
Some(out)
}

/// Words OTP 29 always writes quoted: `erl_scan`'s fixed reserved words and
/// the keywords of the `maybe_expr` feature, which OTP enables by default.
const RESERVED_WORDS: [&str; 29] = [
Expand Down Expand Up @@ -1176,6 +1198,17 @@ pub unsafe fn format_term(term: ErlTerm) -> String {
/// # Safety
/// Source graphs obey [`format_term`]'s live, immutable, unmoved contract.
pub(crate) unsafe fn format_term_as(term: ErlTerm, unicode: bool) -> String {
format_term_inner(term, unicode, false)
}

/// `~p` may quote printable Latin-1 binaries without changing list rendering.
/// # Safety
/// Source graphs obey [`format_term`]'s live, immutable, unmoved contract.
pub(crate) unsafe fn format_term_with_binary_strings(term: ErlTerm) -> String {
format_term_inner(term, false, true)
}

unsafe fn format_term_inner(term: ErlTerm, unicode: bool, binary_strings: bool) -> String {
if term.is_nil() {
return "[]".to_string();
}
Expand All @@ -1197,11 +1230,11 @@ pub(crate) unsafe fn format_term_as(term: ErlTerm, unicode: bool) -> String {
}

if term.is_cons() {
return format_list(term, unicode);
return format_list(term, unicode, binary_strings);
}

if term.is_boxed() {
return format_boxed(term, unicode);
return format_boxed(term, unicode, binary_strings);
}

format!("#unknown<{:#x}>", term.0)
Expand All @@ -1211,29 +1244,33 @@ pub(crate) unsafe fn format_term_as(term: ErlTerm, unicode: bool) -> String {
/// lists or `[1,2|3]` for improper lists.
/// # Safety
/// Source graphs obey the enclosing BIF live, immutable, unmoved input contract.
unsafe fn format_list(term: ErlTerm, unicode: bool) -> String {
unsafe fn format_list(term: ErlTerm, unicode: bool, binary_strings: bool) -> String {
let mut parts: Vec<String> = Vec::new();
let mut cursor = term;

while cursor.is_cons() {
unsafe {
let cell = &*cursor.as_cons_ptr().unwrap();
parts.push(format_term_as(cell.head, unicode));
parts.push(format_term_inner(cell.head, unicode, binary_strings));
cursor = cell.tail;
}
}

if cursor.is_nil() {
format!("[{}]", parts.join(","))
} else {
format!("[{}|{}]", parts.join(","), format_term_as(cursor, unicode))
format!(
"[{}|{}]",
parts.join(","),
format_term_inner(cursor, unicode, binary_strings)
)
}
}

/// Format a boxed term: tuple, float, or generic.
/// # Safety
/// Source graphs obey the enclosing BIF live, immutable, unmoved input contract.
unsafe fn format_boxed(term: ErlTerm, unicode: bool) -> String {
unsafe fn format_boxed(term: ErlTerm, unicode: bool, binary_strings: bool) -> String {
unsafe {
let ptr = term.as_boxed_ptr().unwrap();
let header = BoxedHeader(*ptr);
Expand All @@ -1244,7 +1281,11 @@ unsafe fn format_boxed(term: ErlTerm, unicode: bool) -> String {
BOXED_TUPLE => {
let mut elems: Vec<String> = Vec::with_capacity(arity);
for i in 0..arity {
elems.push(format_term_as(ErlTerm(*ptr.add(1 + i)), unicode));
elems.push(format_term_inner(
ErlTerm(*ptr.add(1 + i)),
unicode,
binary_strings,
));
}
format!("{{{}}}", elems.join(","))
}
Expand All @@ -1253,23 +1294,15 @@ unsafe fn format_boxed(term: ErlTerm, unicode: bool) -> String {
let val = f64::from_bits(bits);
crate::float_format::format_short_float(val)
}
BOXED_BINARY => {
// arity stores bit count; derive byte count
BOXED_BINARY | BOXED_REFC_BINARY => {
let bit_count = arity;
let byte_len = bit_count.div_ceil(8);
let data_ptr = ptr.add(1) as *const u8;
let bytes = std::slice::from_raw_parts(data_ptr, byte_len);
format_binary_bytes(bytes, bit_count)
}
BOXED_REFC_BINARY => {
// arity stores bit count; derive byte count
let bit_count = arity;
let byte_len = bit_count.div_ceil(8);
let raw_arc_ptr = *ptr.add(REFC_BINARY_PTR_WORD_INDEX) as *const BinaryData;
let offset = *ptr.add(REFC_BINARY_OFFSET_WORD_INDEX) as usize;
let vec_ref = &*raw_arc_ptr;
let bytes = &vec_ref[offset..offset + byte_len];
format_binary_bytes(bytes, bit_count)
let bytes = term.binary_bytes_any().unwrap();
let text = if binary_strings && bit_count.is_multiple_of(8) {
format_binary_string(bytes)
} else {
None
};
text.unwrap_or_else(|| format_binary_bytes(bytes, bit_count))
}
BOXED_MAP => {
// arity = number of key-value pairs
Expand All @@ -1280,8 +1313,8 @@ unsafe fn format_boxed(term: ErlTerm, unicode: bool) -> String {
let val = ErlTerm(*ptr.add(1 + i * 2 + 1));
parts.push(format!(
"{} => {}",
format_term_as(key, unicode),
format_term_as(val, unicode)
format_term_inner(key, unicode, binary_strings),
format_term_inner(val, unicode, binary_strings)
));
}
format!("#{{{}}}", parts.join(","))
Expand Down Expand Up @@ -1310,9 +1343,8 @@ unsafe fn format_boxed(term: ErlTerm, unicode: bool) -> String {
/// Format a term with a depth limit, as `~W` (`pretty = false`) or `~P`
/// (`pretty = true`) do. A negative depth is unlimited. Terms deeper than
/// the limit become `...`, following OTP's `io_lib:write/2` for `~W` and
/// `io_lib_pretty` for `~P`; the two differ only for maps. Leaves use
/// `format_term_as`, so `~P` shares `~p`'s rendering (no strings or line
/// breaks) and `unicode` is the `t` modifier.
/// `io_lib_pretty` for `~P`; the two differ only for maps. Both retain
/// numeric binary rendering. `unicode` is the `t` modifier.
/// # Safety
/// Source graphs obey the enclosing BIF live, immutable, unmoved input contract.
pub(crate) unsafe fn format_term_limited(
Expand Down Expand Up @@ -1423,14 +1455,7 @@ unsafe fn write_limited(out: &mut String, term: ErlTerm, depth: i64, pretty: boo
}
BOXED_BINARY | BOXED_REFC_BINARY if arity > 0 => {
let bit_count = arity;
let byte_len = bit_count.div_ceil(8);
let bytes: &[u8] = if header.subtype() == BOXED_BINARY {
std::slice::from_raw_parts(ptr.add(1) as *const u8, byte_len)
} else {
let data = &*(*ptr.add(REFC_BINARY_PTR_WORD_INDEX) as *const BinaryData);
let offset = *ptr.add(REFC_BINARY_OFFSET_WORD_INDEX) as usize;
&data[offset..offset + byte_len]
};
let bytes = term.binary_bytes_any().unwrap();
// Whole bytes, then the trailing bits as Value:Size. Each element
// costs one level; `...` replaces the rest once one level is left.
let full = bit_count / 8;
Expand Down Expand Up @@ -2253,6 +2278,17 @@ mod tests {
assert_eq!(unsafe { format_term(empty_bin) }, "<<>>");
}

#[test]
fn format_term_printable_binary() {
let mut heap = ProcessHeap::new();
let bin = heap.alloc_binary(b"a\"\\\n\xe9");
assert_eq!(unsafe { format_term(bin) }, "<<97,34,92,10,233>>");
assert_eq!(
unsafe { format_term_with_binary_strings(bin) },
"<<\"a\\\"\\\\\\né\">>"
);
}

#[test]
fn format_term_sub_byte_bitstring() {
let mut heap = ProcessHeap::new();
Expand Down Expand Up @@ -3017,6 +3053,7 @@ mod tests {

#[test]
fn phash2_refc_binary_matches_heap_binary() {
use crate::binary::BinaryData;
use std::sync::Arc;
let mut heap = ProcessHeap::new();
// Content: bytes 0..10
Expand Down
20 changes: 12 additions & 8 deletions crates/nera-runtime/src/io_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,15 +315,15 @@ unsafe fn render(fmt: &str, args: &[ErlTerm]) -> Result<String, ()> {
' '
};
let mut unicode = false;
let mut strings = true;
while let Some(modifier @ ('t' | 'l' | 'k' | 'K')) = chars.peek().copied() {
chars.next();
match modifier {
't' => unicode = true,
'l' => strings = false,
'K' => {
argument(args, &mut index)?;
}
// Basic ~p rendering already leaves printable lists as lists,
// so it honours ~l.
// Map ordering is not modelled: accept ~k/~K without sorting.
_ => {}
}
Expand All @@ -337,17 +337,21 @@ unsafe fn render(fmt: &str, args: &[ErlTerm]) -> Result<String, ()> {
pad,
left,
)?,
// Keep Nera's existing term rendering. Width/precision on ~p are
// pretty-printer line length/indentation, not term-field padding.
// Width/precision on ~p are pretty-printer line length/indentation,
// not term-field padding.
'p' => {
if left {
return Err(());
}
bif::format_term_as(argument(args, &mut index)?, unicode)
let term = argument(args, &mut index)?;
// ~tp can interpret UTF-8 binaries, so do not quote them as Latin-1.
if strings && !unicode {
bif::format_term_with_binary_strings(term)
} else {
bif::format_term_as(term, unicode)
}
}
// Depth-limited ~w and ~p. EUnit's reporter prints failures with
// ~tP and passes the result to io:fwrite again, so a literal
// placeholder here made the second call fail with badarg.
// ~W and ~P limit term depth but keep binary bytes numeric.
'W' => {
let term = argument(args, &mut index)?;
let depth = argument(args, &mut index)?.as_small_int().ok_or(())?;
Expand Down
5 changes: 3 additions & 2 deletions docs/KNOWN_LIMITS.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,9 @@ These are real differences from the BEAM that we have reproduced.
earlier Nera-specific hash. Hashes previously stored by Nera may change.
Native funs lack BEAM's module/index metadata, so their hashes are not
BEAM-compatible. Process and reference identities are local to each runtime.
- Printing differs in some cases: a binary of printable bytes prints as
`<<98>>`, not `<<"b">>`.
- Plain `~p` quotes printable Latin-1 binaries as `<<"b">>`. Unlike BEAM,
`~tp` and `~P` still render those binaries numerically, and `~p` does not
quote printable character lists or wrap long terms.

## Reliability and performance

Expand Down
12 changes: 12 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -491,12 +491,24 @@ These are automatically skipped by the runner and show up as SKIP in output.
| Test File | Feature Category | Assertions |
|---------------------|-------------------------------------|------------|
| `io_format.erl` | io:format with ~w, ~p, ~s, ~n | ~5 |
| `io_format_printable_binary.erl` | Exact `~p` output for printable Latin-1 binaries alone and in lists and tuples, escapes, a sub-binary, numeric fallbacks and `~w`/`~lp` controls; same fixture on native and BEAM | 15 cases and stdout |
| `float_text.erl` | BEAM float text for ~w/~p and float_to_list/1,2: shortest notation boundaries, signed and padded exponents, option ordering, rounding, size limits, badarg, direct/apply/fun calls and stdout completion; runs unchanged on native and BEAM | Table-driven |
| `io_lib_format.erl` | io_lib:format/2 directives | ~8 |
| `io_format_atom_quoting.erl` | Atoms quoted as OTP writes them under ~w, ~p, ~W and ~P: uppercase, empty and punctuated names, reserved words, escapes, Latin-1 letters, characters above 255 with and without ~t, nesting, field widths; io:format output matches; also run on BEAM | 36 |
| `io_concurrent.erl` | Concurrent io:format from processes | ~4 |
| `file_io.erl` | file:read_file/1, file:write_file/2 | ~6 |

Run the printable binary regression after rebuilding the native runtime and compiler:

```sh
./target/release/nera test io_format_printable_binary -j 1 --timeout 30
work=$(mktemp -d)
erlc -o "$work" tests/io_format_printable_binary.erl
# The stdout line must end in io_format_printable_binary_ok.
erl +S 1 -noshell -pa "$work" -eval 'ok = io_format_printable_binary:test(), halt().'
rm -rf "$work"
```

### Sockets

| Test File | Feature Category | Assertions |
Expand Down
26 changes: 26 additions & 0 deletions tests/io_format_printable_binary.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
%% EXPECT: <<"abc">> | [<<"abc">>] | {ok,<<"abc">>} | io_format_printable_binary_ok
-module(io_format_printable_binary).
-export([test/0]).

test() ->
Text = <<"abc">>,
"<<\"abc\">>" = render("~p", Text),
"[<<\"abc\">>]" = render("~p", [Text]),
"{ok,<<\"abc\">>}" = render("~p", {ok, Text}),
"[{ok,[<<\"abc\">>]}]" = render("~p", [{ok, [Text]}]),
"[ok|<<\"abc\">>]" = render("~p", [ok | Text]),
"<<\"\\\"\\\\\\n\\r\\t\\v\\b\\f\\e\">>" = render("~p", <<$", $\\, 10, 13, 9, 11, 8, 12, 27>>),
[$<, $<, $", 160, 233, 255, $", $>, $>] = render("~p", <<160, 233, 255>>),
"<<>>" = render("~p", <<>>),
"<<97,98,99,0>>" = render("~p", <<"abc", 0>>),
"<<127>>" = render("~p", <<127>>),
"<<97,98,99,5:3>>" = render("~p", <<"abc", 5:3>>),
"{ok,<<97,98,99>>}" = render("~w", {ok, Text}),
"{ok,<<97,98,99>>}" = render("~lp", {ok, Text}),
Payload = binary:copy(Text, 24),
QuotedPayload = "<<\"" ++ binary_to_list(Payload) ++ "\">>",
QuotedPayload = render("~p", Payload),
QuotedPayload = render("~p", binary:part(<<0, Payload/binary, 0>>, 1, byte_size(Payload))),
io:format("~p | ~p | ~p | io_format_printable_binary_ok~n", [Text, [Text], {ok, Text}]).

render(Format, Term) -> lists:flatten(io_lib:format(Format, [Term])).
Loading