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