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