rune/compile/
assembly.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
//! Helpers for building assembly.

use core::fmt;

use crate as rune;
use crate::alloc::fmt::TryWrite;
use crate::alloc::prelude::*;
use crate::alloc::{hash_map, HashMap};
use crate::ast::{Span, Spanned};
use crate::compile::{self, Location};
use crate::runtime::{Inst, InstAddress, Label, Output};
use crate::{Hash, SourceId};

#[derive(Debug, TryClone)]
pub(crate) enum AssemblyInst {
    Jump {
        label: Label,
    },
    JumpIf {
        addr: InstAddress,
        label: Label,
    },
    JumpIfNot {
        addr: InstAddress,
        label: Label,
    },
    IterNext {
        addr: InstAddress,
        label: Label,
        out: Output,
    },
    Raw {
        raw: Inst,
    },
}

/// Helper structure to build instructions and maintain certain invariants.
#[derive(Debug, TryClone, Default)]
pub(crate) struct Assembly {
    /// The location that caused the assembly.
    location: Location,
    /// Registered label by offset.
    pub(crate) labels: HashMap<usize, (usize, Vec<Label>)>,
    /// Instructions with spans.
    pub(crate) instructions: Vec<(AssemblyInst, Span)>,
    /// Comments associated with instructions.
    pub(crate) comments: HashMap<usize, String>,
    /// The number of labels.
    pub(crate) label_count: usize,
    /// The collection of functions required by this assembly.
    pub(crate) required_functions: HashMap<Hash, Vec<(Span, SourceId)>>,
}

impl Assembly {
    /// Construct a new assembly.
    pub(crate) fn new(location: Location, label_count: usize) -> Self {
        Self {
            location,
            labels: Default::default(),
            instructions: Default::default(),
            comments: Default::default(),
            label_count,
            required_functions: Default::default(),
        }
    }

    /// Construct and return a new label.
    pub(crate) fn new_label(&mut self, name: &'static str) -> Label {
        let label = Label::new(name, self.label_count);
        self.label_count += 1;
        label
    }

    /// Apply the label at the current instruction offset.
    pub(crate) fn label(&mut self, label: &Label) -> compile::Result<()> {
        let len = self.labels.len();

        match self.labels.entry(self.instructions.len()) {
            hash_map::Entry::Occupied(e) => {
                let &mut (len, ref mut labels) = e.into_mut();
                label.set_jump(len);
                labels.try_push(label.try_clone()?)?;
            }
            hash_map::Entry::Vacant(e) => {
                label.set_jump(len);
                e.try_insert((len, try_vec![label.try_clone()?]))?;
            }
        }

        Ok(())
    }

    /// Add a jump to the given label.
    pub(crate) fn jump(&mut self, label: &Label, span: &dyn Spanned) -> compile::Result<()> {
        self.inner_push(
            AssemblyInst::Jump {
                label: label.try_clone()?,
            },
            span,
        )?;

        Ok(())
    }

    /// Add a conditional jump to the given label.
    pub(crate) fn jump_if(
        &mut self,
        addr: InstAddress,
        label: &Label,
        span: &dyn Spanned,
    ) -> compile::Result<()> {
        self.inner_push(
            AssemblyInst::JumpIf {
                addr,
                label: label.try_clone()?,
            },
            span,
        )?;

        Ok(())
    }

    /// Add jump-if-not instruction to a label.
    pub(crate) fn jump_if_not(
        &mut self,
        addr: InstAddress,
        label: &Label,
        span: &dyn Spanned,
    ) -> compile::Result<()> {
        self.inner_push(
            AssemblyInst::JumpIfNot {
                addr,
                label: label.try_clone()?,
            },
            span,
        )?;

        Ok(())
    }

    /// Add an instruction that advanced an iterator.
    pub(crate) fn iter_next(
        &mut self,
        addr: InstAddress,
        label: &Label,
        span: &dyn Spanned,
        out: Output,
    ) -> compile::Result<()> {
        self.inner_push(
            AssemblyInst::IterNext {
                addr,
                label: label.try_clone()?,
                out,
            },
            span,
        )?;

        Ok(())
    }

    /// Push a raw instruction.
    pub(crate) fn push(&mut self, raw: Inst, span: &dyn Spanned) -> compile::Result<()> {
        self.inner_push(AssemblyInst::Raw { raw }, span)?;
        Ok(())
    }

    /// Push a raw instruction.
    pub(crate) fn push_with_comment(
        &mut self,
        raw: Inst,
        span: &dyn Spanned,
        comment: &dyn fmt::Display,
    ) -> compile::Result<()> {
        let index = self.instructions.len();
        let c = self.comments.entry(index).or_try_default()?;

        if !c.is_empty() {
            c.try_push_str("; ")?;
        }

        write!(c, "{comment}")?;
        self.push(raw, span)?;
        Ok(())
    }

    fn inner_push(&mut self, inst: AssemblyInst, span: &dyn Spanned) -> compile::Result<()> {
        if let AssemblyInst::Raw {
            raw: Inst::Call { hash, .. },
        } = &inst
        {
            self.required_functions
                .entry(*hash)
                .or_try_default()?
                .try_push((span.span(), self.location.source_id))?;
        }

        self.instructions.try_push((inst, span.span()))?;
        Ok(())
    }
}