Skip to main content

byteflow/bytecode/
asm.rs

1//! Text listing that round-trips through [`super::disassemble`].
2//!
3//! This is not a language. Each line is a directive or one [`Instruction`]
4//! in the same shape [`Instruction`]'s `Display` already prints.
5
6use super::chunk::{Chunk, FunctionDef};
7use super::format::module_abi;
8use super::instruction::Instruction;
9use super::opcode::Opcode;
10use super::value::{MapKey, Value};
11use super::verify::{verify, VerifyError};
12
13/// Why a text listing could not become a verified [`Chunk`].
14#[derive(Debug)]
15pub enum AssembleError {
16    Syntax {
17        line: usize,
18        message: String,
19    },
20    /// The `.abi` line does not match the ABI [`super::encode`] would write.
21    Abi {
22        declared: u32,
23        encoded: u32,
24    },
25    Verify(VerifyError),
26}
27
28impl std::fmt::Display for AssembleError {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        match self {
31            AssembleError::Syntax { line, message } => {
32                write!(f, "assemble line {line}: {message}")
33            }
34            AssembleError::Abi { declared, encoded } => {
35                write!(
36                    f,
37                    "listing abi {declared} does not match encoded abi {encoded}"
38                )
39            }
40            AssembleError::Verify(err) => write!(f, "assemble verify: {err}"),
41        }
42    }
43}
44
45impl std::error::Error for AssembleError {}
46
47impl From<VerifyError> for AssembleError {
48    fn from(err: VerifyError) -> Self {
49        AssembleError::Verify(err)
50    }
51}
52
53/// Parse a listing produced by [`super::disassemble`] and verify it.
54pub fn assemble(text: &str) -> Result<Chunk, AssembleError> {
55    let mut name = None;
56    let mut declared_abi = None;
57    let mut constants = Vec::new();
58    let mut functions = Vec::new();
59    let mut code = Vec::new();
60    for (idx, raw) in text.lines().enumerate() {
61        let line_no = idx + 1;
62        let line = strip_comment(raw).trim();
63        if line.is_empty() {
64            continue;
65        }
66        if let Some(rest) = line.strip_prefix(".chunk ") {
67            name = Some(parse_quoted(rest, line_no)?);
68        } else if let Some(rest) = line.strip_prefix(".abi ") {
69            declared_abi = Some(parse_u32(rest.trim(), line_no, "abi")?);
70        } else if let Some(rest) = line.strip_prefix(".const ") {
71            constants.push(parse_value(rest.trim(), line_no)?);
72        } else if let Some(rest) = line.strip_prefix(".fn ") {
73            functions.push(parse_fn(rest.trim(), line_no)?);
74        } else {
75            let body = match split_index(line) {
76                Some((index, body)) => {
77                    if index != code.len() {
78                        return Err(syn(line_no, format!("instruction index {index}")));
79                    }
80                    body
81                }
82                None => line,
83            };
84            code.push(parse_instruction(body, line_no)?);
85        }
86    }
87    let name = name.ok_or_else(|| syn(1, "missing .chunk"))?;
88    let declared = declared_abi.ok_or_else(|| syn(1, "missing .abi"))?;
89    let encoded = module_abi(&constants);
90    if declared != encoded {
91        return Err(AssembleError::Abi { declared, encoded });
92    }
93    let chunk = Chunk {
94        name,
95        constants,
96        code,
97        functions,
98    };
99    verify(&chunk)?;
100    Ok(chunk)
101}
102
103#[inline]
104fn syn(line: usize, message: impl Into<String>) -> AssembleError {
105    AssembleError::Syntax {
106        line,
107        message: message.into(),
108    }
109}
110
111fn strip_comment(line: &str) -> &str {
112    let mut quote = false;
113    let mut escape = false;
114    let bytes = line.as_bytes();
115    let mut i = 0;
116    while i < bytes.len() {
117        let c = bytes[i] as char;
118        if escape {
119            escape = false;
120            i += 1;
121            continue;
122        }
123        if c == '\\' && quote {
124            escape = true;
125            i += 1;
126            continue;
127        }
128        if c == '"' {
129            quote = !quote;
130        }
131        if !quote && c == ';' {
132            return &line[..i];
133        }
134        i += 1;
135    }
136    line
137}
138
139#[inline]
140fn split_index(line: &str) -> Option<(usize, &str)> {
141    let bytes = line.as_bytes();
142    let mut i = 0;
143    while i < bytes.len() && bytes[i].is_ascii_digit() {
144        i += 1;
145    }
146    // At least one digit, then whitespace. A fixed width of 4 drops every
147    // instruction from index 10000 onward (`10000  Op` has a digit where the
148    // old parser required a space).
149    if i == 0 || i == bytes.len() || bytes[i] != b' ' {
150        return None;
151    }
152    let index = line[..i].parse().ok()?;
153    Some((index, line[i..].trim()))
154}
155
156#[inline]
157fn parse_u32(text: &str, line: usize, what: &str) -> Result<u32, AssembleError> {
158    text.parse().map_err(|_| syn(line, format!("bad {what}")))
159}
160
161fn parse_quoted(text: &str, line: usize) -> Result<String, AssembleError> {
162    let (out, rest) = take_quoted(text, line)?;
163    if !rest.trim().is_empty() {
164        return Err(syn(line, "trailing junk after string"));
165    }
166    Ok(out)
167}
168
169/// Quoted string and the unparsed tail after the closing quote.
170///
171/// Byte offsets follow the source, including multi-byte characters. Escape
172/// bodies are ASCII (`\\`, `\"`, `\n`, `\r`).
173fn take_quoted(text: &str, line: usize) -> Result<(String, &str), AssembleError> {
174    let text = text.trim_start();
175    if !text.starts_with('"') {
176        return Err(syn(line, "expected quoted string"));
177    }
178    let mut out = String::new();
179    let mut chars = text[1..].chars();
180    let mut consumed = 1usize;
181    loop {
182        match chars.next() {
183            Some('\\') => {
184                consumed += 1;
185                match chars.next() {
186                    Some('\\') => out.push('\\'),
187                    Some('"') => out.push('"'),
188                    Some('n') => out.push('\n'),
189                    Some('r') => out.push('\r'),
190                    _ => return Err(syn(line, "bad escape")),
191                }
192                consumed += 1;
193            }
194            Some('"') => {
195                consumed += 1;
196                let after = match text.get(consumed..) {
197                    Some(rest) => rest,
198                    None => "",
199                };
200                return Ok((out, after));
201            }
202            Some(c) => {
203                out.push(c);
204                consumed += c.len_utf8();
205            }
206            None => return Err(syn(line, "unterminated string")),
207        }
208    }
209}
210
211fn parse_fn(text: &str, line: usize) -> Result<FunctionDef, AssembleError> {
212    let text = text.trim_start();
213    let (name, rest) = if text.starts_with('"') {
214        take_quoted(text, line)?
215    } else {
216        let (name, rest) = token_span(text);
217        if name.is_empty() {
218            return Err(syn(line, "function name"));
219        }
220        (name.to_string(), rest)
221    };
222    let mut parts = rest.split_whitespace();
223    let entry = field(parts.next(), "entry=", line)?;
224    let arity = field(parts.next(), "arity=", line)?;
225    let regs = field(parts.next(), "regs=", line)?;
226    if parts.next().is_some() {
227        return Err(syn(line, "extra function field"));
228    }
229    let arity = u8::try_from(arity).map_err(|_| syn(line, "arity"))?;
230    let num_registers = u8::try_from(regs).map_err(|_| syn(line, "regs"))?;
231    Ok(FunctionDef {
232        name,
233        entry,
234        arity,
235        num_registers,
236    })
237}
238
239fn field(token: Option<&str>, prefix: &str, line: usize) -> Result<u32, AssembleError> {
240    let token = token.ok_or_else(|| syn(line, format!("missing {prefix}")))?;
241    let rest = token
242        .strip_prefix(prefix)
243        .ok_or_else(|| syn(line, format!("expected {prefix}")))?;
244    parse_u32(rest, line, prefix)
245}
246
247pub(crate) fn write_constant(out: &mut String, value: &Value) {
248    use std::fmt::Write as _;
249    let _ = write!(out, ".const ");
250    write_value(out, value);
251    let _ = writeln!(out);
252}
253
254fn write_value(out: &mut String, value: &Value) {
255    use std::fmt::Write as _;
256    match value {
257        Value::Unit => out.push_str("unit"),
258        Value::Bool(true) => out.push_str("bool true"),
259        Value::Bool(false) => out.push_str("bool false"),
260        Value::Int(n) => {
261            let _ = write!(out, "int {n}");
262        }
263        Value::Float(n) => write_float(out, *n),
264        Value::Pid(n) => {
265            let _ = write!(out, "pid {n}");
266        }
267        Value::Cap(cap) => {
268            let _ = write!(out, "cap {}", cap.as_u128());
269        }
270        Value::Str(text) => {
271            out.push_str("str ");
272            push_quoted(out, text);
273        }
274        Value::Bytes(bytes) => {
275            out.push_str("bytes ");
276            for byte in bytes.iter() {
277                let _ = write!(out, "{byte:02x}");
278            }
279        }
280        Value::List(items) => {
281            out.push_str("list [");
282            for (index, item) in items.iter().enumerate() {
283                if index > 0 {
284                    out.push_str(", ");
285                }
286                write_value(out, item);
287            }
288            out.push(']');
289        }
290        Value::Record(fields) => {
291            out.push_str("record [");
292            for (index, field) in fields.iter().enumerate() {
293                if index > 0 {
294                    out.push_str(", ");
295                }
296                write_value(out, field);
297            }
298            out.push(']');
299        }
300        Value::Map(entries) => {
301            out.push_str("map [");
302            for (index, (key, value)) in entries.iter().enumerate() {
303                if index > 0 {
304                    out.push_str(", ");
305                }
306                match key {
307                    MapKey::Int(n) => {
308                        let _ = write!(out, "int {n}");
309                    }
310                    MapKey::Str(text) => {
311                        out.push_str("str ");
312                        push_quoted(out, text);
313                    }
314                }
315                out.push_str(" -> ");
316                write_value(out, value);
317            }
318            out.push(']');
319        }
320        Value::Message(message) => {
321            let _ = write!(
322                out,
323                "msg {} {} {} {} ",
324                message.sender,
325                message.reply_cap.as_u128(),
326                message.request_id,
327                message.tag
328            );
329            write_value(out, message.payload.as_ref());
330        }
331    }
332}
333
334/// Decimal when that text parses back to the same bits. `NaN` payloads and
335/// `-0.0` do not: `Display` collapses every NaN, and `-0.0 == 0.0`.
336fn write_float(out: &mut String, n: f64) {
337    use std::fmt::Write as _;
338    let decimal = n.to_string();
339    let round_trips = decimal
340        .parse::<f64>()
341        .ok()
342        .is_some_and(|parsed| parsed.to_bits() == n.to_bits());
343    if round_trips {
344        let _ = write!(out, "float {decimal}");
345    } else {
346        let _ = write!(out, "float bits {:#x}", n.to_bits());
347    }
348}
349
350fn push_quoted(out: &mut String, text: &str) {
351    out.push('"');
352    for c in text.chars() {
353        match c {
354            '\\' => out.push_str("\\\\"),
355            '"' => out.push_str("\\\""),
356            '\n' => out.push_str("\\n"),
357            '\r' => out.push_str("\\r"),
358            c => out.push(c),
359        }
360    }
361    out.push('"');
362}
363
364fn parse_value(text: &str, line: usize) -> Result<Value, AssembleError> {
365    let (value, rest) = take_value(text, line)?;
366    if !rest.trim().is_empty() {
367        return Err(syn(line, "trailing junk after constant"));
368    }
369    Ok(value)
370}
371
372fn take_value(text: &str, line: usize) -> Result<(Value, &str), AssembleError> {
373    let text = text.trim_start();
374    if let Some(rest) = text.strip_prefix("unit") {
375        return Ok((Value::Unit, rest));
376    }
377    if let Some(rest) = text.strip_prefix("bool ") {
378        let rest = rest.trim_start();
379        if let Some(rest) = rest.strip_prefix("true") {
380            return Ok((Value::Bool(true), rest));
381        }
382        if let Some(rest) = rest.strip_prefix("false") {
383            return Ok((Value::Bool(false), rest));
384        }
385        return Err(syn(line, "bad bool"));
386    }
387    if let Some(rest) = text.strip_prefix("int ") {
388        let (token, rest) = token_span(rest.trim_start());
389        let n = token.parse::<i64>().map_err(|_| syn(line, "bad int"))?;
390        return Ok((Value::Int(n), rest));
391    }
392    if let Some(rest) = text.strip_prefix("float ") {
393        let rest = rest.trim_start();
394        if let Some(rest) = rest.strip_prefix("bits ") {
395            let (token, rest) = token_span(rest.trim_start());
396            let bits = parse_u64_token(token).map_err(|_| syn(line, "bad float bits"))?;
397            return Ok((Value::Float(f64::from_bits(bits)), rest));
398        }
399        let (token, rest) = token_span(rest);
400        let n = token.parse::<f64>().map_err(|_| syn(line, "bad float"))?;
401        return Ok((Value::Float(n), rest));
402    }
403    if let Some(rest) = text.strip_prefix("pid ") {
404        let (token, rest) = token_span(rest.trim_start());
405        let n = token.parse::<u64>().map_err(|_| syn(line, "bad pid"))?;
406        return Ok((Value::Pid(n), rest));
407    }
408    if let Some(rest) = text.strip_prefix("cap ") {
409        let (token, rest) = token_span(rest.trim_start());
410        let n = token.parse::<u128>().map_err(|_| syn(line, "bad cap"))?;
411        return Ok((Value::Cap(super::cap::CapId::from_raw(n)), rest));
412    }
413    if let Some(rest) = text.strip_prefix("str ") {
414        let rest = rest.trim_start();
415        if !rest.starts_with('"') {
416            return Err(syn(line, "bad str"));
417        }
418        let mut owned = String::new();
419        let mut chars = rest[1..].chars();
420        let mut consumed = 1usize;
421        loop {
422            match chars.next() {
423                Some('\\') => {
424                    consumed += 1;
425                    match chars.next() {
426                        Some('\\') => owned.push('\\'),
427                        Some('"') => owned.push('"'),
428                        Some('n') => owned.push('\n'),
429                        Some('r') => owned.push('\r'),
430                        _ => return Err(syn(line, "bad escape")),
431                    }
432                    consumed += 1;
433                }
434                Some('"') => {
435                    consumed += 1;
436                    let after = rest.get(consumed..).unwrap_or("");
437                    return Ok((Value::str(owned), after));
438                }
439                Some(c) => {
440                    owned.push(c);
441                    consumed += c.len_utf8();
442                }
443                None => return Err(syn(line, "unterminated str")),
444            }
445        }
446    }
447    if let Some(rest) = text.strip_prefix("bytes ") {
448        let (token, rest) = token_span(rest.trim_start());
449        if token.len() % 2 != 0 {
450            return Err(syn(line, "bad bytes"));
451        }
452        let mut bytes = Vec::with_capacity(token.len() / 2);
453        let digits = token.as_bytes();
454        let mut i = 0;
455        while i < digits.len() {
456            let hi = hex_val(digits[i]).ok_or_else(|| syn(line, "bad bytes"))?;
457            let lo = hex_val(digits[i + 1]).ok_or_else(|| syn(line, "bad bytes"))?;
458            bytes.push((hi << 4) | lo);
459            i += 2;
460        }
461        return Ok((Value::bytes(bytes), rest));
462    }
463    if let Some(rest) = text.strip_prefix("list [") {
464        return take_list(rest, line);
465    }
466    if let Some(rest) = text.strip_prefix("map [") {
467        return take_map(rest, line);
468    }
469    if let Some(rest) = text.strip_prefix("record [") {
470        let (value, rest) = take_list(rest, line)?;
471        let Value::List(items) = value else {
472            return Err(syn(line, "record"));
473        };
474        let record =
475            Value::try_record(items.to_vec()).ok_or_else(|| syn(line, "record rejected"))?;
476        return Ok((record, rest));
477    }
478    if let Some(rest) = text.strip_prefix("msg ") {
479        return take_msg(rest, line);
480    }
481    Err(syn(line, "unknown constant"))
482}
483
484fn parse_u64_token(token: &str) -> Result<u64, ()> {
485    if let Some(hex) = token
486        .strip_prefix("0x")
487        .or_else(|| token.strip_prefix("0X"))
488    {
489        return u64::from_str_radix(hex, 16).map_err(|_| ());
490    }
491    token.parse().map_err(|_| ())
492}
493
494fn token_span(text: &str) -> (&str, &str) {
495    let end = text
496        .find(|c: char| c.is_whitespace() || c == ',' || c == ']')
497        .unwrap_or(text.len());
498    // A negative number's '-' is part of the token. Only split on " -> ".
499    if text[..end].is_empty() {
500        return ("", text);
501    }
502    (&text[..end], &text[end..])
503}
504
505fn hex_val(byte: u8) -> Option<u8> {
506    match byte {
507        b'0'..=b'9' => Some(byte - b'0'),
508        b'a'..=b'f' => Some(byte - b'a' + 10),
509        b'A'..=b'F' => Some(byte - b'A' + 10),
510        _ => None,
511    }
512}
513
514fn take_list(mut text: &str, line: usize) -> Result<(Value, &str), AssembleError> {
515    let mut items = Vec::new();
516    text = text.trim_start();
517    if let Some(rest) = text.strip_prefix(']') {
518        let list = Value::try_list(items).ok_or_else(|| syn(line, "list rejected"))?;
519        return Ok((list, rest));
520    }
521    loop {
522        let (item, rest) = take_value(text, line)?;
523        items.push(item);
524        text = rest.trim_start();
525        if let Some(rest) = text.strip_prefix(']') {
526            let list = Value::try_list(items).ok_or_else(|| syn(line, "list rejected"))?;
527            return Ok((list, rest));
528        }
529        text = text
530            .strip_prefix(',')
531            .ok_or_else(|| syn(line, "list separator"))?
532            .trim_start();
533    }
534}
535
536fn take_map(mut text: &str, line: usize) -> Result<(Value, &str), AssembleError> {
537    let mut entries = Vec::new();
538    text = text.trim_start();
539    if let Some(rest) = text.strip_prefix(']') {
540        let map = Value::try_map(entries).ok_or_else(|| syn(line, "map rejected"))?;
541        return Ok((map, rest));
542    }
543    loop {
544        let (key_value, rest) = take_value(text, line)?;
545        let key = match key_value {
546            Value::Int(n) => MapKey::Int(n),
547            Value::Str(text) => MapKey::Str(text),
548            _ => return Err(syn(line, "map key")),
549        };
550        let rest = rest.trim_start();
551        let rest = rest
552            .strip_prefix("->")
553            .ok_or_else(|| syn(line, "map arrow"))?
554            .trim_start();
555        let (value, rest) = take_value(rest, line)?;
556        entries.push((key, value));
557        text = rest.trim_start();
558        if let Some(rest) = text.strip_prefix(']') {
559            let map = Value::try_map(entries).ok_or_else(|| syn(line, "map rejected"))?;
560            return Ok((map, rest));
561        }
562        text = text
563            .strip_prefix(',')
564            .ok_or_else(|| syn(line, "map separator"))?
565            .trim_start();
566    }
567}
568
569fn take_msg(text: &str, line: usize) -> Result<(Value, &str), AssembleError> {
570    let mut parts = text.splitn(5, char::is_whitespace);
571    let sender = parts
572        .next()
573        .ok_or_else(|| syn(line, "msg sender"))?
574        .parse::<u64>()
575        .map_err(|_| syn(line, "msg sender"))?;
576    let reply = parts
577        .next()
578        .ok_or_else(|| syn(line, "msg reply"))?
579        .parse::<u128>()
580        .map_err(|_| syn(line, "msg reply"))?;
581    let request = parts
582        .next()
583        .ok_or_else(|| syn(line, "msg request"))?
584        .parse::<u64>()
585        .map_err(|_| syn(line, "msg request"))?;
586    let tag = parts
587        .next()
588        .ok_or_else(|| syn(line, "msg tag"))?
589        .parse::<u16>()
590        .map_err(|_| syn(line, "msg tag"))?;
591    let payload_text = parts.next().unwrap_or("");
592    let (payload, rest) = take_value(payload_text, line)?;
593    let message = super::value::Message::new(sender, request, tag, payload)
594        .authenticate(sender, super::cap::CapId::from_raw(reply));
595    Ok((Value::Message(message), rest))
596}
597
598struct Scan<'a> {
599    line: usize,
600    rest: &'a str,
601}
602
603impl<'a> Scan<'a> {
604    fn new(line: usize, rest: &'a str) -> Self {
605        Self { line, rest }
606    }
607
608    fn skip(&mut self) {
609        self.rest = self.rest.trim_start();
610    }
611
612    fn eat(&mut self, lit: &str) -> Result<(), AssembleError> {
613        self.skip();
614        if let Some(rest) = self.rest.strip_prefix(lit) {
615            self.rest = rest;
616            Ok(())
617        } else {
618            Err(syn(self.line, format!("expected {lit}")))
619        }
620    }
621
622    fn end(&mut self) -> Result<(), AssembleError> {
623        self.skip();
624        if self.rest.is_empty() {
625            Ok(())
626        } else {
627            Err(syn(self.line, "trailing junk"))
628        }
629    }
630
631    fn reg(&mut self) -> Result<u8, AssembleError> {
632        self.eat("r")?;
633        let (token, rest) = take_num(self.rest);
634        self.rest = rest;
635        let n = token
636            .parse::<u16>()
637            .map_err(|_| syn(self.line, "register"))?;
638        u8::try_from(n).map_err(|_| syn(self.line, "register"))
639    }
640
641    fn i32(&mut self) -> Result<i32, AssembleError> {
642        self.skip();
643        if let Some(rest) = self.rest.strip_prefix('+') {
644            self.rest = rest;
645        }
646        let (token, rest) = take_num(self.rest);
647        if token.is_empty() {
648            return Err(syn(self.line, "number"));
649        }
650        self.rest = rest;
651        token.parse().map_err(|_| syn(self.line, "number"))
652    }
653
654    fn hex(&mut self) -> Result<u32, AssembleError> {
655        self.eat("0x")?;
656        let (token, rest) = take_hex(self.rest);
657        self.rest = rest;
658        if token.is_empty() {
659            return Err(syn(self.line, "hex"));
660        }
661        u32::from_str_radix(token, 16).map_err(|_| syn(self.line, "hex"))
662    }
663
664    fn slot(&mut self, kind: &str) -> Result<i32, AssembleError> {
665        self.eat(kind)?;
666        self.eat("[")?;
667        let n = self.i32()?;
668        self.eat("]")?;
669        Ok(n)
670    }
671
672    fn comma(&mut self) -> Result<(), AssembleError> {
673        self.eat(",")?;
674        Ok(())
675    }
676}
677
678fn take_num(text: &str) -> (&str, &str) {
679    let mut end = 0;
680    let bytes = text.as_bytes();
681    if bytes.first() == Some(&b'-') {
682        end = 1;
683    }
684    while end < bytes.len() && bytes[end].is_ascii_digit() {
685        end += 1;
686    }
687    (&text[..end], &text[end..])
688}
689
690fn take_hex(text: &str) -> (&str, &str) {
691    let end = text
692        .find(|c: char| !c.is_ascii_hexdigit())
693        .unwrap_or(text.len());
694    (&text[..end], &text[end..])
695}
696
697fn parse_instruction(text: &str, line: usize) -> Result<Instruction, AssembleError> {
698    let text = text.trim();
699    let (name, rest) = text.split_once(char::is_whitespace).unwrap_or((text, ""));
700    let op = opcode_from_name(name).ok_or_else(|| syn(line, format!("unknown opcode {name}")))?;
701    let mut s = Scan::new(line, rest);
702    let instr = match op {
703        Opcode::Halt | Opcode::Yield | Opcode::Nop => Instruction::nullary(op),
704        Opcode::LoadConst => {
705            let a = s.reg()?;
706            s.comma()?;
707            let imm = s.slot("const")?;
708            Instruction::a_imm(op, a, imm)
709        }
710        Opcode::Move
711        | Opcode::Neg
712        | Opcode::BitNot
713        | Opcode::Send
714        | Opcode::ReceiveTimeout
715        | Opcode::ReceiveMatch
716        | Opcode::IsAlive
717        | Opcode::ExitSignal
718        | Opcode::TableOpen
719        | Opcode::Whereis
720        | Opcode::Monitor
721        | Opcode::Link => {
722            let a = s.reg()?;
723            s.comma()?;
724            let b = s.reg()?;
725            Instruction::abc(op, a, b, 0)
726        }
727        Opcode::LoadImm | Opcode::Trap | Opcode::SetRestartPolicy => {
728            if op == Opcode::LoadImm {
729                let a = s.reg()?;
730                s.comma()?;
731                let imm = s.i32()?;
732                Instruction::a_imm(op, a, imm)
733            } else if op == Opcode::Trap || op == Opcode::SetRestartPolicy {
734                let imm = s.i32()?;
735                Instruction::only_imm(op, imm)
736            } else {
737                Instruction::nullary(op)
738            }
739        }
740        Opcode::Add
741        | Opcode::Sub
742        | Opcode::Mul
743        | Opcode::Div
744        | Opcode::Mod
745        | Opcode::Eq
746        | Opcode::Ne
747        | Opcode::Lt
748        | Opcode::Le
749        | Opcode::Gt
750        | Opcode::Ge
751        | Opcode::BitAnd
752        | Opcode::BitOr
753        | Opcode::BitXor
754        | Opcode::Shl
755        | Opcode::Shr
756        | Opcode::Ushr
757        | Opcode::MapGet
758        | Opcode::TableGet
759        | Opcode::TablePut
760        | Opcode::Ask => {
761            let a = s.reg()?;
762            s.comma()?;
763            let b = s.reg()?;
764            s.comma()?;
765            let c = s.reg()?;
766            Instruction::abc(op, a, b, c)
767        }
768        Opcode::AddImm
769        | Opcode::SubImm
770        | Opcode::MulImm
771        | Opcode::EqImm
772        | Opcode::NeImm
773        | Opcode::LtImm
774        | Opcode::LeImm
775        | Opcode::GtImm
776        | Opcode::GeImm
777        | Opcode::ListGet
778        | Opcode::RecordGet => {
779            let a = s.reg()?;
780            s.comma()?;
781            let b = s.reg()?;
782            s.comma()?;
783            let imm = s.i32()?;
784            Instruction::new(op, a, b, 0, imm)
785        }
786        Opcode::ListPack | Opcode::RecordPack => {
787            let a = s.reg()?;
788            s.comma()?;
789            let b = s.reg()?;
790            s.comma()?;
791            s.eat("count=")?;
792            let imm = s.i32()?;
793            Instruction::new(op, a, b, 0, imm)
794        }
795        Opcode::MapPack => {
796            let a = s.reg()?;
797            s.comma()?;
798            let b = s.reg()?;
799            s.comma()?;
800            s.eat("pairs=")?;
801            let imm = s.i32()?;
802            Instruction::new(op, a, b, 0, imm)
803        }
804        Opcode::ListLen
805        | Opcode::MapLen
806        | Opcode::RecordLen
807        | Opcode::StrLen
808        | Opcode::BytesLen
809        | Opcode::DictGet
810        | Opcode::DictErase => {
811            if op == Opcode::DictGet || op == Opcode::DictErase {
812                let a = s.reg()?;
813                s.comma()?;
814                s.eat("key=")?;
815                let b = s.reg()?;
816                Instruction::abc(op, a, b, 0)
817            } else {
818                let a = s.reg()?;
819                s.comma()?;
820                let b = s.reg()?;
821                Instruction::abc(op, a, b, 0)
822            }
823        }
824        Opcode::Jump => Instruction::only_imm(op, s.i32()?),
825        Opcode::Branch | Opcode::BranchTrue | Opcode::StartSupervisor => {
826            if op == Opcode::Branch || op == Opcode::BranchTrue {
827                let a = s.reg()?;
828                s.comma()?;
829                Instruction::a_imm(op, a, s.i32()?)
830            } else {
831                s.eat("strategy=")?;
832                Instruction::only_imm(op, s.i32()?)
833            }
834        }
835        Opcode::Call | Opcode::TailCall => {
836            let a = s.reg()?;
837            s.comma()?;
838            let imm = s.slot("fn")?;
839            s.comma()?;
840            s.eat("argc=")?;
841            let b = s.i32()?;
842            let b = u8::try_from(b).map_err(|_| syn(line, "argc"))?;
843            Instruction::new(op, a, b, 0, imm)
844        }
845        Opcode::CallNative => {
846            let a = s.reg()?;
847            s.comma()?;
848            let imm = s.slot("native")?;
849            s.comma()?;
850            s.eat("argc=")?;
851            let b = u8::try_from(s.i32()?).map_err(|_| syn(line, "argc"))?;
852            Instruction::new(op, a, b, 0, imm)
853        }
854        Opcode::CallNativeFrom => {
855            let a = s.reg()?;
856            s.comma()?;
857            let b = s.reg()?;
858            s.comma()?;
859            let imm = s.slot("native")?;
860            Instruction::new(op, a, b, 0, imm)
861        }
862        Opcode::Return
863        | Opcode::Exit
864        | Opcode::Sleep
865        | Opcode::Receive
866        | Opcode::SelfPid
867        | Opcode::FreshRequestId
868        | Opcode::Demonitor
869        | Opcode::Unlink
870        | Opcode::RegisterName
871        | Opcode::SetTrapExit => {
872            let a = s.reg()?;
873            Instruction::a_imm(op, a, 0)
874        }
875        Opcode::Spawn => {
876            let a = s.reg()?;
877            s.comma()?;
878            let imm = s.slot("fn")?;
879            s.comma()?;
880            s.eat("argc=")?;
881            let b = u8::try_from(s.i32()?).map_err(|_| syn(line, "argc"))?;
882            s.comma()?;
883            s.eat("rights=")?;
884            let c = s.hex()?;
885            let c = u8::try_from(c).map_err(|_| syn(line, "rights"))?;
886            Instruction::new(op, a, b, c, imm)
887        }
888        Opcode::ReceiveMatchImm | Opcode::ReceiveMatchKind => {
889            let a = s.reg()?;
890            s.comma()?;
891            if op == Opcode::ReceiveMatchImm {
892                s.eat("tag=")?;
893            } else {
894                s.eat("kind=")?;
895            }
896            Instruction::a_imm(op, a, s.i32()?)
897        }
898        Opcode::ReceiveMatchTimeout
899        | Opcode::ReceiveMatchEq
900        | Opcode::ReceiveMatchValue
901        | Opcode::ReceiveMatchCorr
902        | Opcode::DictPut => {
903            let a = s.reg()?;
904            s.comma()?;
905            let (b_lit, c_lit) = match op {
906                Opcode::ReceiveMatchTimeout => ("tag=", "timeout="),
907                Opcode::ReceiveMatchEq | Opcode::ReceiveMatchValue => ("tag=", "payload="),
908                Opcode::ReceiveMatchCorr => ("tag=", "id="),
909                Opcode::DictPut => ("key=", "val="),
910                _ => ("", ""),
911            };
912            s.eat(b_lit)?;
913            let b = s.reg()?;
914            s.comma()?;
915            s.eat(c_lit)?;
916            let c = s.reg()?;
917            Instruction::abc(op, a, b, c)
918        }
919        Opcode::ReceiveMatchImmTimeout | Opcode::ReceiveMatchCorrImm => {
920            let a = s.reg()?;
921            s.comma()?;
922            s.eat("tag=")?;
923            let imm = s.i32()?;
924            s.comma()?;
925            if op == Opcode::ReceiveMatchImmTimeout {
926                s.eat("timeout=")?;
927            } else {
928                s.eat("id=")?;
929            }
930            let b = s.reg()?;
931            Instruction::new(op, a, b, 0, imm)
932        }
933        Opcode::StartChild => {
934            let a = s.reg()?;
935            s.comma()?;
936            let imm = s.slot("fn")?;
937            s.comma()?;
938            s.eat("policy=")?;
939            let b = u8::try_from(s.i32()?).map_err(|_| syn(line, "policy"))?;
940            Instruction::new(op, a, b, 0, imm)
941        }
942        Opcode::SendRemote => {
943            s.eat("node=")?;
944            let a = s.reg()?;
945            s.comma()?;
946            s.eat("name=")?;
947            let b = s.reg()?;
948            s.comma()?;
949            s.eat("msg=")?;
950            let c = s.reg()?;
951            Instruction::abc(op, a, b, c)
952        }
953        Opcode::AskTimeout => {
954            let a = s.reg()?;
955            s.comma()?;
956            let b = s.reg()?;
957            s.comma()?;
958            let c = s.reg()?;
959            s.comma()?;
960            s.eat("timeout=")?;
961            let imm = s.reg()?;
962            Instruction::new(op, a, b, c, i32::from(imm))
963        }
964        Opcode::Delegate => {
965            let a = s.reg()?;
966            s.comma()?;
967            let b = s.reg()?;
968            s.comma()?;
969            s.eat("rights=")?;
970            let rights = s.hex()?;
971            s.skip();
972            if s.rest.is_empty() {
973                Instruction::new(op, a, b, 255, rights as i32)
974            } else {
975                s.eat(",")?;
976                s.eat("native=")?;
977                let c = s.reg()?;
978                Instruction::new(op, a, b, c, rights as i32)
979            }
980        }
981        Opcode::HostAwait => {
982            let a = s.reg()?;
983            s.comma()?;
984            let b = s.reg()?;
985            s.comma()?;
986            s.eat("op=")?;
987            let imm = s.i32()?;
988            Instruction::new(op, a, b, 0, imm)
989        }
990        Opcode::ReceiveMatchCmp => {
991            let a = s.reg()?;
992            s.comma()?;
993            s.eat("tag=")?;
994            let b = s.reg()?;
995            s.comma()?;
996            s.eat("bound=")?;
997            let c = s.reg()?;
998            s.comma()?;
999            s.eat("cmp=")?;
1000            let imm = s.i32()?;
1001            Instruction::new(op, a, b, c, imm)
1002        }
1003    };
1004    s.end()?;
1005    Ok(instr)
1006}
1007
1008fn opcode_from_name(name: &str) -> Option<Opcode> {
1009    Some(match name {
1010        "Halt" => Opcode::Halt,
1011        "LoadConst" => Opcode::LoadConst,
1012        "Move" => Opcode::Move,
1013        "LoadImm" => Opcode::LoadImm,
1014        "Add" => Opcode::Add,
1015        "Sub" => Opcode::Sub,
1016        "Mul" => Opcode::Mul,
1017        "Div" => Opcode::Div,
1018        "Mod" => Opcode::Mod,
1019        "Neg" => Opcode::Neg,
1020        "Eq" => Opcode::Eq,
1021        "Lt" => Opcode::Lt,
1022        "Le" => Opcode::Le,
1023        "Jump" => Opcode::Jump,
1024        "Branch" => Opcode::Branch,
1025        "Call" => Opcode::Call,
1026        "Return" => Opcode::Return,
1027        "CallNative" => Opcode::CallNative,
1028        "Spawn" => Opcode::Spawn,
1029        "Yield" => Opcode::Yield,
1030        "Sleep" => Opcode::Sleep,
1031        "Exit" => Opcode::Exit,
1032        "SelfPid" => Opcode::SelfPid,
1033        "Send" => Opcode::Send,
1034        "Receive" => Opcode::Receive,
1035        "ReceiveTimeout" => Opcode::ReceiveTimeout,
1036        "ReceiveMatch" => Opcode::ReceiveMatch,
1037        "ReceiveMatchImm" => Opcode::ReceiveMatchImm,
1038        "Ask" => Opcode::Ask,
1039        "Monitor" => Opcode::Monitor,
1040        "Demonitor" => Opcode::Demonitor,
1041        "Link" => Opcode::Link,
1042        "Unlink" => Opcode::Unlink,
1043        "Trap" => Opcode::Trap,
1044        "Nop" => Opcode::Nop,
1045        "CallNativeFrom" => Opcode::CallNativeFrom,
1046        "AddImm" => Opcode::AddImm,
1047        "SubImm" => Opcode::SubImm,
1048        "MulImm" => Opcode::MulImm,
1049        "EqImm" => Opcode::EqImm,
1050        "LtImm" => Opcode::LtImm,
1051        "LeImm" => Opcode::LeImm,
1052        "ListPack" => Opcode::ListPack,
1053        "ListGet" => Opcode::ListGet,
1054        "ListLen" => Opcode::ListLen,
1055        "BitAnd" => Opcode::BitAnd,
1056        "BitOr" => Opcode::BitOr,
1057        "BitXor" => Opcode::BitXor,
1058        "BitNot" => Opcode::BitNot,
1059        "Shl" => Opcode::Shl,
1060        "Shr" => Opcode::Shr,
1061        "ReceiveMatchCmp" => Opcode::ReceiveMatchCmp,
1062        "MapPack" => Opcode::MapPack,
1063        "MapGet" => Opcode::MapGet,
1064        "MapLen" => Opcode::MapLen,
1065        "TableOpen" => Opcode::TableOpen,
1066        "TableGet" => Opcode::TableGet,
1067        "TablePut" => Opcode::TablePut,
1068        "RecordPack" => Opcode::RecordPack,
1069        "RecordGet" => Opcode::RecordGet,
1070        "RecordLen" => Opcode::RecordLen,
1071        "Ne" => Opcode::Ne,
1072        "Gt" => Opcode::Gt,
1073        "Ge" => Opcode::Ge,
1074        "NeImm" => Opcode::NeImm,
1075        "GtImm" => Opcode::GtImm,
1076        "GeImm" => Opcode::GeImm,
1077        "Ushr" => Opcode::Ushr,
1078        "BranchTrue" => Opcode::BranchTrue,
1079        "StrLen" => Opcode::StrLen,
1080        "BytesLen" => Opcode::BytesLen,
1081        "TailCall" => Opcode::TailCall,
1082        "AskTimeout" => Opcode::AskTimeout,
1083        "Delegate" => Opcode::Delegate,
1084        "FreshRequestId" => Opcode::FreshRequestId,
1085        "ReceiveMatchCorr" => Opcode::ReceiveMatchCorr,
1086        "ReceiveMatchCorrImm" => Opcode::ReceiveMatchCorrImm,
1087        "SetTrapExit" => Opcode::SetTrapExit,
1088        "RegisterName" => Opcode::RegisterName,
1089        "Whereis" => Opcode::Whereis,
1090        "ReceiveMatchKind" => Opcode::ReceiveMatchKind,
1091        "SetRestartPolicy" => Opcode::SetRestartPolicy,
1092        "HostAwait" => Opcode::HostAwait,
1093        "ReceiveMatchTimeout" => Opcode::ReceiveMatchTimeout,
1094        "ReceiveMatchImmTimeout" => Opcode::ReceiveMatchImmTimeout,
1095        "IsAlive" => Opcode::IsAlive,
1096        "ExitSignal" => Opcode::ExitSignal,
1097        "DictPut" => Opcode::DictPut,
1098        "DictGet" => Opcode::DictGet,
1099        "DictErase" => Opcode::DictErase,
1100        "ReceiveMatchEq" => Opcode::ReceiveMatchEq,
1101        "StartChild" => Opcode::StartChild,
1102        "ReceiveMatchValue" => Opcode::ReceiveMatchValue,
1103        "SendRemote" => Opcode::SendRemote,
1104        "StartSupervisor" => Opcode::StartSupervisor,
1105        _ => return None,
1106    })
1107}
1108
1109#[cfg(test)]
1110mod tests {
1111    use super::*;
1112    use crate::bytecode::builder::ChunkBuilder;
1113    use crate::bytecode::{decode, disassemble, encode};
1114
1115    fn round_trip(chunk: Chunk) -> Result<(), AssembleError> {
1116        let text = disassemble(&chunk);
1117        let parsed = assemble(&text)?;
1118        let again = decode(&encode(&parsed)).map_err(|err| AssembleError::Syntax {
1119            line: 0,
1120            message: err.to_string(),
1121        })?;
1122        if again != chunk {
1123            return Err(AssembleError::Syntax {
1124                line: 0,
1125                message: format!("round trip mismatch\n{text}"),
1126            });
1127        }
1128        Ok(())
1129    }
1130
1131    #[test]
1132    fn integers_round_trip_as_abi_v5() -> Result<(), AssembleError> {
1133        let mut b = ChunkBuilder::new("ints");
1134        b.begin_function("main", 0, 2);
1135        b.emit_load_imm(0, 41);
1136        b.emit_load_imm(1, 1);
1137        b.emit_binop(Opcode::Add, 0, 0, 1);
1138        b.emit_return(0);
1139        let chunk = b.finish();
1140        let text = disassemble(&chunk);
1141        assert!(text.contains(".abi 5"));
1142        assert!(!text.contains(".abi 6"));
1143        round_trip(chunk)
1144    }
1145
1146    #[test]
1147    fn list_round_trip_as_abi_v6() -> Result<(), AssembleError> {
1148        let list = Value::try_list(vec![Value::Int(1), Value::Int(2)]).ok_or_else(|| {
1149            AssembleError::Syntax {
1150                line: 0,
1151                message: "list".into(),
1152            }
1153        })?;
1154        let mut b = ChunkBuilder::new("lists");
1155        let index = b.const_(list);
1156        b.begin_function("main", 0, 1);
1157        b.emit_load_const(0, index);
1158        b.emit_return(0);
1159        let chunk = b.finish();
1160        let text = disassemble(&chunk);
1161        assert!(text.contains(".abi 6"), "{text}");
1162        assert!(
1163            !text.contains(".abi 5\n") && !text.contains(".abi 5\r"),
1164            "{text}"
1165        );
1166        round_trip(chunk)
1167    }
1168
1169    #[test]
1170    fn map_round_trip_as_abi_v7() -> Result<(), AssembleError> {
1171        let map = Value::try_map(vec![
1172            (MapKey::int(1), Value::Int(7)),
1173            (MapKey::str("a"), Value::Int(2)),
1174        ])
1175        .ok_or_else(|| AssembleError::Syntax {
1176            line: 0,
1177            message: "map".into(),
1178        })?;
1179        let mut b = ChunkBuilder::new("maps");
1180        let index = b.const_(map);
1181        b.begin_function("main", 0, 1);
1182        b.emit_load_const(0, index);
1183        b.emit_return(0);
1184        let chunk = b.finish();
1185        let text = disassemble(&chunk);
1186        assert!(text.contains(".abi 7"), "{text}");
1187        round_trip(chunk)
1188    }
1189
1190    #[test]
1191    fn record_round_trip_as_abi_v8() -> Result<(), AssembleError> {
1192        let record = Value::try_record(vec![Value::Int(4), Value::Int(5)]).ok_or_else(|| {
1193            AssembleError::Syntax {
1194                line: 0,
1195                message: "record".into(),
1196            }
1197        })?;
1198        let mut b = ChunkBuilder::new("recs");
1199        let index = b.const_(record);
1200        b.begin_function("main", 0, 1);
1201        b.emit_load_const(0, index);
1202        b.emit_return(0);
1203        let chunk = b.finish();
1204        let text = disassemble(&chunk);
1205        assert!(text.contains(".abi 8"), "{text}");
1206        assert!(text.contains("record ["), "{text}");
1207        round_trip(chunk)
1208    }
1209
1210    #[test]
1211    fn bad_syntax_is_an_error() {
1212        let err = assemble(".chunk \"x\"\n.abi 5\n.fn main entry=0 arity=0 regs=1\n0000 Nope\n");
1213        assert!(matches!(err, Err(AssembleError::Syntax { .. })));
1214    }
1215
1216    #[test]
1217    fn bad_operand_is_an_error() {
1218        let err = assemble(
1219            ".chunk \"x\"\n.abi 5\n.fn main entry=0 arity=0 regs=1\n0000 LoadImm r0, no\n",
1220        );
1221        assert!(matches!(err, Err(AssembleError::Syntax { .. })));
1222    }
1223
1224    #[test]
1225    fn bad_constant_reference_fails_verify() {
1226        let err = assemble(
1227            ".chunk \"x\"\n.abi 5\n.fn main entry=0 arity=0 regs=1\n0000 LoadConst r0, const[3]\n",
1228        );
1229        assert!(matches!(
1230            err,
1231            Err(AssembleError::Verify(VerifyError::ConstOutOfRange { .. }))
1232        ));
1233    }
1234
1235    #[test]
1236    fn bad_function_reference_fails_verify() {
1237        let text = "\
1238.chunk \"x\"
1239.abi 5
1240.fn main entry=0 arity=0 regs=1
12410000 Call r0, fn[4], argc=0
1242";
1243        let err = assemble(text);
1244        assert!(matches!(
1245            err,
1246            Err(AssembleError::Verify(
1247                VerifyError::FunctionOutOfRange { .. }
1248            ))
1249        ));
1250    }
1251
1252    #[test]
1253    fn declared_abi_must_match_the_constants() {
1254        let text = "\
1255.chunk \"x\"
1256.abi 5
1257.const list [int 1]
1258.fn main entry=0 arity=0 regs=1
12590000 Return r0
1260";
1261        let err = assemble(text);
1262        assert!(matches!(
1263            err,
1264            Err(AssembleError::Abi {
1265                declared: 5,
1266                encoded: 6
1267            })
1268        ));
1269    }
1270
1271    #[test]
1272    fn empty_input_does_not_panic() {
1273        assert!(assemble("").is_err());
1274        assert!(assemble("not a module").is_err());
1275    }
1276
1277    #[test]
1278    fn every_opcode_listing_parses_back() -> Result<(), AssembleError> {
1279        let samples = [
1280            Instruction::nullary(Opcode::Halt),
1281            Instruction::a_imm(Opcode::LoadConst, 1, 2),
1282            Instruction::abc(Opcode::Move, 1, 2, 0),
1283            Instruction::a_imm(Opcode::LoadImm, 1, -3),
1284            Instruction::abc(Opcode::Add, 1, 2, 3),
1285            Instruction::abc(Opcode::Sub, 1, 2, 3),
1286            Instruction::abc(Opcode::Mul, 1, 2, 3),
1287            Instruction::abc(Opcode::Div, 1, 2, 3),
1288            Instruction::abc(Opcode::Mod, 1, 2, 3),
1289            Instruction::abc(Opcode::Neg, 1, 2, 0),
1290            Instruction::abc(Opcode::Eq, 1, 2, 3),
1291            Instruction::abc(Opcode::Lt, 1, 2, 3),
1292            Instruction::abc(Opcode::Le, 1, 2, 3),
1293            Instruction::only_imm(Opcode::Jump, -1),
1294            Instruction::a_imm(Opcode::Branch, 1, 4),
1295            Instruction::new(Opcode::Call, 1, 2, 0, 3),
1296            Instruction::a_imm(Opcode::Return, 1, 0),
1297            Instruction::new(Opcode::CallNative, 1, 2, 0, 3),
1298            Instruction::new(Opcode::Spawn, 1, 0, 0, 2),
1299            Instruction::nullary(Opcode::Yield),
1300            Instruction::a_imm(Opcode::Sleep, 1, 0),
1301            Instruction::a_imm(Opcode::Exit, 1, 0),
1302            Instruction::a_imm(Opcode::SelfPid, 1, 0),
1303            Instruction::abc(Opcode::Send, 1, 2, 0),
1304            Instruction::a_imm(Opcode::Receive, 1, 0),
1305            Instruction::abc(Opcode::ReceiveTimeout, 1, 2, 0),
1306            Instruction::abc(Opcode::ReceiveMatch, 1, 2, 0),
1307            Instruction::a_imm(Opcode::ReceiveMatchImm, 1, 7),
1308            Instruction::abc(Opcode::Ask, 1, 2, 3),
1309            Instruction::abc(Opcode::Monitor, 1, 2, 0),
1310            Instruction::a_imm(Opcode::Demonitor, 1, 0),
1311            Instruction::abc(Opcode::Link, 1, 2, 0),
1312            Instruction::a_imm(Opcode::Unlink, 1, 0),
1313            Instruction::only_imm(Opcode::Trap, 9),
1314            Instruction::nullary(Opcode::Nop),
1315            Instruction::new(Opcode::CallNativeFrom, 1, 2, 0, 3),
1316            Instruction::new(Opcode::AddImm, 1, 2, 0, -4),
1317            Instruction::new(Opcode::SubImm, 1, 2, 0, 4),
1318            Instruction::new(Opcode::MulImm, 1, 2, 0, 4),
1319            Instruction::new(Opcode::EqImm, 1, 2, 0, 4),
1320            Instruction::new(Opcode::LtImm, 1, 2, 0, 4),
1321            Instruction::new(Opcode::LeImm, 1, 2, 0, 4),
1322            Instruction::new(Opcode::ListPack, 1, 2, 0, 3),
1323            Instruction::new(Opcode::ListGet, 1, 2, 0, 3),
1324            Instruction::abc(Opcode::ListLen, 1, 2, 0),
1325            Instruction::abc(Opcode::BitAnd, 1, 2, 3),
1326            Instruction::abc(Opcode::BitOr, 1, 2, 3),
1327            Instruction::abc(Opcode::BitXor, 1, 2, 3),
1328            Instruction::abc(Opcode::BitNot, 1, 2, 0),
1329            Instruction::abc(Opcode::Shl, 1, 2, 3),
1330            Instruction::abc(Opcode::Shr, 1, 2, 3),
1331            Instruction::new(Opcode::ReceiveMatchCmp, 1, 2, 3, 0),
1332            Instruction::new(Opcode::MapPack, 1, 2, 0, 3),
1333            Instruction::abc(Opcode::MapGet, 1, 2, 3),
1334            Instruction::abc(Opcode::MapLen, 1, 2, 0),
1335            Instruction::abc(Opcode::TableOpen, 1, 2, 0),
1336            Instruction::abc(Opcode::TableGet, 1, 2, 3),
1337            Instruction::abc(Opcode::TablePut, 1, 2, 3),
1338            Instruction::new(Opcode::RecordPack, 1, 2, 0, 3),
1339            Instruction::new(Opcode::RecordGet, 1, 2, 0, 3),
1340            Instruction::abc(Opcode::RecordLen, 1, 2, 0),
1341            Instruction::abc(Opcode::Ne, 1, 2, 3),
1342            Instruction::abc(Opcode::Gt, 1, 2, 3),
1343            Instruction::abc(Opcode::Ge, 1, 2, 3),
1344            Instruction::new(Opcode::NeImm, 1, 2, 0, 4),
1345            Instruction::new(Opcode::GtImm, 1, 2, 0, 4),
1346            Instruction::new(Opcode::GeImm, 1, 2, 0, 4),
1347            Instruction::abc(Opcode::Ushr, 1, 2, 3),
1348            Instruction::a_imm(Opcode::BranchTrue, 1, 4),
1349            Instruction::abc(Opcode::StrLen, 1, 2, 0),
1350            Instruction::abc(Opcode::BytesLen, 1, 2, 0),
1351            Instruction::new(Opcode::TailCall, 1, 2, 0, 3),
1352            Instruction::new(Opcode::AskTimeout, 1, 2, 3, 4),
1353            Instruction::new(Opcode::Delegate, 1, 2, 255, 0),
1354            Instruction::new(Opcode::Delegate, 1, 2, 3, 1),
1355            Instruction::a_imm(Opcode::FreshRequestId, 1, 0),
1356            Instruction::abc(Opcode::ReceiveMatchCorr, 1, 2, 3),
1357            Instruction::new(Opcode::ReceiveMatchCorrImm, 1, 2, 0, 7),
1358            Instruction::a_imm(Opcode::SetTrapExit, 1, 0),
1359            Instruction::a_imm(Opcode::RegisterName, 1, 0),
1360            Instruction::abc(Opcode::Whereis, 1, 2, 0),
1361            Instruction::a_imm(Opcode::ReceiveMatchKind, 1, 2),
1362            Instruction::only_imm(Opcode::SetRestartPolicy, 1),
1363            Instruction::new(Opcode::HostAwait, 1, 2, 0, 3),
1364            Instruction::abc(Opcode::ReceiveMatchTimeout, 1, 2, 3),
1365            Instruction::new(Opcode::ReceiveMatchImmTimeout, 1, 2, 0, 7),
1366            Instruction::abc(Opcode::IsAlive, 1, 2, 0),
1367            Instruction::abc(Opcode::ExitSignal, 1, 2, 0),
1368            Instruction::abc(Opcode::DictPut, 1, 2, 3),
1369            Instruction::abc(Opcode::DictGet, 1, 2, 0),
1370            Instruction::abc(Opcode::DictErase, 1, 2, 0),
1371            Instruction::abc(Opcode::ReceiveMatchEq, 1, 2, 3),
1372            Instruction::new(Opcode::StartChild, 1, 2, 0, 3),
1373            Instruction::abc(Opcode::ReceiveMatchValue, 1, 2, 3),
1374            Instruction::abc(Opcode::SendRemote, 1, 2, 3),
1375            Instruction::only_imm(Opcode::StartSupervisor, 1),
1376        ];
1377        for instr in samples {
1378            let text = instr.to_string();
1379            let parsed = parse_instruction(&text, 1)?;
1380            if parsed != instr {
1381                return Err(AssembleError::Syntax {
1382                    line: 1,
1383                    message: format!("{text} parsed as {parsed:?}, want {instr:?}"),
1384                });
1385            }
1386        }
1387        Ok(())
1388    }
1389
1390    #[test]
1391    fn instruction_index_past_four_digits_round_trips() -> Result<(), AssembleError> {
1392        let mut b = ChunkBuilder::new("wide");
1393        b.begin_function("main", 0, 1);
1394        for _ in 0..10_000 {
1395            b.emit_load_imm(0, 0);
1396        }
1397        b.emit_return(0);
1398        let chunk = b.finish();
1399        let text = disassemble(&chunk);
1400        if !text.contains("\n10000  Return r0") {
1401            return Err(AssembleError::Syntax {
1402                line: 0,
1403                message: "listing did not print a five-digit index".into(),
1404            });
1405        }
1406        round_trip(chunk)
1407    }
1408
1409    #[test]
1410    fn function_names_with_spaces_and_semicolons_round_trip() -> Result<(), AssembleError> {
1411        let mut b = ChunkBuilder::new("names");
1412        b.begin_function("my fn; still one", 0, 1);
1413        b.emit_return(0);
1414        b.begin_function("say \"hi\"\nnext", 0, 1);
1415        b.emit_halt();
1416        let chunk = b.finish();
1417        let text = disassemble(&chunk);
1418        if !text.contains(".fn \"my fn; still one\"") {
1419            return Err(AssembleError::Syntax {
1420                line: 0,
1421                message: format!("function name was not quoted:\n{text}"),
1422            });
1423        }
1424        if text.lines().any(|line| {
1425            let line = line.trim();
1426            line == "next" || line.starts_with("next ")
1427        }) {
1428            return Err(AssembleError::Syntax {
1429                line: 0,
1430                message: format!("newline in a name split the listing:\n{text}"),
1431            });
1432        }
1433        let bare = "\
1434.chunk \"names\"
1435.abi 5
1436.fn main entry=0 arity=0 regs=1
14370000  Return r0
1438";
1439        let parsed = assemble(bare)?;
1440        if parsed.functions.first().map(|f| f.name.as_str()) != Some("main") {
1441            return Err(AssembleError::Syntax {
1442                line: 0,
1443                message: "unquoted function name".into(),
1444            });
1445        }
1446        round_trip(chunk)
1447    }
1448
1449    #[test]
1450    fn carriage_return_in_names_and_strings_round_trips() -> Result<(), AssembleError> {
1451        let mut b = ChunkBuilder::new("chunk\rname");
1452        b.const_(Value::Str("hi\rthere".into()));
1453        b.begin_function("fn\rname", 0, 1);
1454        b.emit_load_const(0, 0);
1455        b.emit_return(0);
1456        let chunk = b.finish();
1457        let text = disassemble(&chunk);
1458        if text.contains('\r') {
1459            return Err(AssembleError::Syntax {
1460                line: 0,
1461                message: format!("raw carriage return split the listing:\n{text}"),
1462            });
1463        }
1464        round_trip(chunk)
1465    }
1466
1467    #[test]
1468    fn float_nan_and_negative_zero_keep_their_bits() -> Result<(), AssembleError> {
1469        let nan = f64::from_bits(0x7ff8_0000_0000_0001);
1470        let neg_zero = -0.0f64;
1471        let mut b = ChunkBuilder::new("floats");
1472        b.const_(Value::Float(nan));
1473        b.const_(Value::Float(neg_zero));
1474        b.const_(Value::Float(1.5));
1475        b.begin_function("main", 0, 1);
1476        b.emit_return(0);
1477        let chunk = b.finish();
1478        let text = disassemble(&chunk);
1479        if !text.contains("float bits 0x") {
1480            return Err(AssembleError::Syntax {
1481                line: 0,
1482                message: format!("non-finite float was printed in decimal:\n{text}"),
1483            });
1484        }
1485        let parsed = assemble(&text)?;
1486        let bits: Vec<u64> = parsed
1487            .constants
1488            .iter()
1489            .filter_map(|value| match value {
1490                Value::Float(n) => Some(n.to_bits()),
1491                _ => None,
1492            })
1493            .collect();
1494        if bits != [nan.to_bits(), neg_zero.to_bits(), 1.5f64.to_bits()] {
1495            return Err(AssembleError::Syntax {
1496                line: 0,
1497                message: format!("float bits {bits:x?} from\n{text}"),
1498            });
1499        }
1500        Ok(())
1501    }
1502}