Skip to main content

rune/compile/
unit_builder.rs

1//! A single execution unit in the runestick virtual machine.
2//!
3//! A unit consists of a sequence of instructions, and lookaside tables for
4//! metadata like function locations.
5
6use core::fmt;
7
8use crate::alloc::fmt::TryWrite;
9use crate::alloc::prelude::*;
10use crate::alloc::{self, try_format, Box, HashMap, String, Vec};
11use crate::ast::{Span, Spanned};
12use crate::compile::meta;
13use crate::compile::{self, Assembly, AssemblyInst, ErrorKind, Location, Pool, WithSpan};
14use crate::hash;
15use crate::query::QueryInner;
16use crate::runtime::debug::{DebugArgs, DebugGlobal, DebugSignature};
17use crate::runtime::inst;
18use crate::runtime::unit::UnitEncoder;
19use crate::runtime::{
20    Address, Call, ConstValueBuf, DebugInfo, DebugInst, Inst, Label, Protocol, Rtti, RttiKind,
21    StaticString, Unit, UnitFn,
22};
23use crate::sync::Arc;
24use crate::{Context, Diagnostics, Hash, Item, ItemBuf, SourceId};
25
26/// Errors that can be raised when linking units.
27#[derive(Debug)]
28#[allow(missing_docs)]
29#[non_exhaustive]
30pub enum LinkerError {
31    MissingFunction {
32        hash: Hash,
33        spans: Vec<(Span, SourceId)>,
34    },
35}
36
37impl fmt::Display for LinkerError {
38    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39        match self {
40            LinkerError::MissingFunction { hash, .. } => {
41                write!(f, "Missing function with hash {hash}")
42            }
43        }
44    }
45}
46
47impl core::error::Error for LinkerError {}
48
49/// Instructions from a single source file.
50#[derive(Debug, Default)]
51pub(crate) struct UnitBuilder {
52    /// Registered re-exports.
53    reexports: HashMap<Hash, Hash>,
54    /// Where functions are located in the collection of instructions.
55    functions: hash::Map<UnitFn>,
56    /// Function by address.
57    functions_rev: HashMap<usize, Hash>,
58    /// Functions declared by a declaration source, which the host is expected
59    /// to provide at run time and which the linker therefore does not require.
60    declared: HashMap<Hash, ItemBuf>,
61    /// A static string.
62    static_strings: Vec<Arc<StaticString>>,
63    /// Reverse lookup for static strings.
64    static_string_rev: HashMap<Hash, usize>,
65    /// A static byte string.
66    static_bytes: Vec<Vec<u8>>,
67    /// Reverse lookup for static byte strings.
68    static_bytes_rev: HashMap<Hash, usize>,
69    /// Slots used for object keys.
70    ///
71    /// This is used when an object is used in a pattern match, to avoid having
72    /// to send the collection of keys to the virtual machine.
73    ///
74    /// All keys are sorted with the default string sort.
75    static_object_keys: Vec<Box<[String]>>,
76    /// Used to detect duplicates in the collection of static object keys.
77    static_object_keys_rev: HashMap<Hash, usize>,
78    /// A static string.
79    drop_sets: Vec<Arc<[Address]>>,
80    /// Reverse lookup for drop sets.
81    drop_sets_rev: HashMap<Vec<Address>, usize>,
82    /// Runtime type information for types.
83    rtti: hash::Map<Arc<Rtti>>,
84    /// The current label count.
85    label_count: usize,
86    /// A collection of required function hashes.
87    required_functions: HashMap<Hash, Vec<(Span, SourceId)>>,
88    /// Debug info if available for unit.
89    debug: Option<Box<DebugInfo>>,
90    /// Constant values
91    constants: hash::Map<ConstValueBuf>,
92    /// Hash to identifiers.
93    hash_to_ident: HashMap<Hash, Box<str>>,
94    /// Initializers for static items, indexed by the slot they've been
95    /// assigned.
96    globals: Vec<Option<ConstValueBuf>>,
97    /// Reverse lookup from the type hash of a static item to its slot.
98    globals_rev: hash::Map<usize>,
99}
100
101impl crate::runtime::LookupRtti for UnitBuilder {
102    #[inline]
103    fn lookup_rtti(&self, hash: &Hash) -> Option<&Arc<Rtti>> {
104        self.rtti.get(hash)
105    }
106}
107
108impl UnitBuilder {
109    /// Construct a new drop set.
110    pub(crate) fn drop_set(&mut self) -> DropSet<'_> {
111        DropSet {
112            builder: self,
113            addresses: Vec::new(),
114        }
115    }
116
117    /// Record a function which a declaration source declared, so that calling
118    /// it without the host providing it can name it at run time.
119    pub(crate) fn insert_declared(&mut self, hash: Hash, item: &Item) -> alloc::Result<()> {
120        self.declared.try_insert(hash, item.try_to_owned()?)?;
121        Ok(())
122    }
123
124    /// Insert an identifier for debug purposes.
125    pub(crate) fn insert_debug_ident(&mut self, ident: &str) -> alloc::Result<()> {
126        self.hash_to_ident
127            .try_insert(Hash::ident(ident), ident.try_into()?)?;
128        Ok(())
129    }
130
131    /// Convert into a runtime unit, shedding our build metadata in the process.
132    ///
133    /// Returns `None` if the builder is still in use.
134    pub(crate) fn build<S>(mut self, span: Span, storage: S) -> compile::Result<Unit<S>> {
135        if let Some(debug) = &mut self.debug {
136            debug.functions_rev = self.functions_rev;
137            debug.hash_to_ident = self.hash_to_ident;
138            debug.declared = self.declared;
139        }
140
141        for (from, to) in self.reexports {
142            if let Some(info) = self.functions.get(&to) {
143                let info = *info;
144                if self
145                    .functions
146                    .try_insert(from, info)
147                    .with_span(span)?
148                    .is_some()
149                {
150                    return Err(compile::Error::new(
151                        span,
152                        ErrorKind::FunctionConflictHash { hash: from },
153                    ));
154                }
155                continue;
156            }
157
158            if let Some(value) = self.constants.get(&to) {
159                let const_value = value.try_clone()?;
160
161                if self
162                    .constants
163                    .try_insert(from, const_value)
164                    .with_span(span)?
165                    .is_some()
166                {
167                    return Err(compile::Error::new(
168                        span,
169                        ErrorKind::ConstantConflict { hash: from },
170                    ));
171                }
172
173                continue;
174            }
175
176            return Err(compile::Error::new(
177                span,
178                ErrorKind::MissingFunctionHash { hash: to },
179            ));
180        }
181
182        Ok(Unit::new(
183            storage,
184            self.functions,
185            self.static_strings,
186            self.static_bytes,
187            self.static_object_keys,
188            self.drop_sets,
189            self.rtti,
190            self.debug,
191            self.constants,
192            self.globals,
193            self.globals_rev,
194        ))
195    }
196
197    /// Build a runtime unit out of the builder without consuming it.
198    ///
199    /// This is what makes it possible to execute a unit which is still being
200    /// built, which constant evaluation relies on - it compiles the constant
201    /// into an interior unit and has to run it while the outer compilation is
202    /// still in progress.
203    ///
204    /// Debug information is deliberately not included. The caller of a constant
205    /// evaluation already knows the span it is evaluating, and copying the debug
206    /// info of the interior unit for every evaluation is not worth what it adds
207    /// to the diagnostic.
208    pub(crate) fn snapshot<S>(&self, storage: S) -> alloc::Result<Unit<S>> {
209        Ok(Unit::new(
210            storage,
211            self.functions.try_clone()?,
212            self.static_strings.try_clone()?,
213            self.static_bytes.try_clone()?,
214            self.static_object_keys.try_clone()?,
215            self.drop_sets.try_clone()?,
216            self.rtti.try_clone()?,
217            None,
218            self.constants.try_clone()?,
219            self.globals.try_clone()?,
220            self.globals_rev.try_clone()?,
221        ))
222    }
223
224    /// Get the slot assigned to the static item with the given type hash,
225    /// allocating a new one if this is the first time we see it.
226    ///
227    /// Slots are handed out in the order they are requested, so a static which
228    /// is used before it is built still ends up with a single stable slot.
229    pub(crate) fn global_slot(&mut self, hash: Hash) -> alloc::Result<usize> {
230        if let Some(slot) = self.globals_rev.get(&hash).copied() {
231            return Ok(slot);
232        }
233
234        let slot = self.globals.len();
235        self.globals.try_push(None)?;
236        self.globals_rev.try_insert(hash, slot)?;
237        Ok(slot)
238    }
239
240    /// Record the initializer and the debug name for a static item.
241    pub(crate) fn insert_global(
242        &mut self,
243        hash: Hash,
244        path: &Item,
245        init: Option<ConstValueBuf>,
246        debug_info: bool,
247    ) -> alloc::Result<usize> {
248        let slot = self.global_slot(hash)?;
249
250        if let Some(init) = init {
251            self.globals[slot] = Some(init);
252        }
253
254        if debug_info {
255            let debug = self.debug_mut()?;
256
257            while debug.globals.len() <= slot {
258                debug.globals.try_push(DebugGlobal::new(ItemBuf::new()))?;
259            }
260
261            debug.globals[slot] = DebugGlobal::new(path.try_to_owned()?);
262        }
263
264        Ok(slot)
265    }
266
267    /// Insert a static string and return its associated slot that can later be
268    /// looked up through [lookup_string][Unit::lookup_string].
269    ///
270    /// Only uses up space if the static string is unique.
271    pub(crate) fn new_static_string(
272        &mut self,
273        span: &dyn Spanned,
274        current: &str,
275    ) -> compile::Result<usize> {
276        let current = StaticString::new(current)?;
277        let hash = current.hash();
278
279        if let Some(existing_slot) = self.static_string_rev.get(&hash).copied() {
280            let Some(existing) = self.static_strings.get(existing_slot) else {
281                return Err(compile::Error::new(
282                    span,
283                    ErrorKind::StaticStringMissing {
284                        hash,
285                        slot: existing_slot,
286                    },
287                ));
288            };
289
290            if ***existing != *current {
291                return Err(compile::Error::new(
292                    span,
293                    ErrorKind::StaticStringHashConflict {
294                        hash,
295                        current: (*current).try_clone()?,
296                        existing: (***existing).try_clone()?,
297                    },
298                ));
299            }
300
301            return Ok(existing_slot);
302        }
303
304        let new_slot = self.static_strings.len();
305        self.static_strings.try_push(Arc::try_new(current)?)?;
306        self.static_string_rev.try_insert(hash, new_slot)?;
307        Ok(new_slot)
308    }
309
310    /// Insert a static byte string and return its associated slot that can
311    /// later be looked up through [lookup_bytes][Unit::lookup_bytes].
312    ///
313    /// Only uses up space if the static byte string is unique.
314    pub(crate) fn new_static_bytes(
315        &mut self,
316        span: &dyn Spanned,
317        current: &[u8],
318    ) -> compile::Result<usize> {
319        let hash = Hash::static_bytes(current);
320
321        if let Some(existing_slot) = self.static_bytes_rev.get(&hash).copied() {
322            let existing = self.static_bytes.get(existing_slot).ok_or_else(|| {
323                compile::Error::new(
324                    span,
325                    ErrorKind::StaticBytesMissing {
326                        hash,
327                        slot: existing_slot,
328                    },
329                )
330            })?;
331
332            if &**existing != current {
333                return Err(compile::Error::new(
334                    span,
335                    ErrorKind::StaticBytesHashConflict {
336                        hash,
337                        current: current.try_to_owned()?,
338                        existing: existing.try_clone()?,
339                    },
340                ));
341            }
342
343            return Ok(existing_slot);
344        }
345
346        let new_slot = self.static_bytes.len();
347        self.static_bytes.try_push(current.try_to_owned()?)?;
348        self.static_bytes_rev.try_insert(hash, new_slot)?;
349        Ok(new_slot)
350    }
351
352    /// Insert a new collection of static object keys, or return one already
353    /// existing.
354    pub(crate) fn new_static_object_keys_iter(
355        &mut self,
356        span: &dyn Spanned,
357        current: impl IntoIterator<Item: AsRef<str>>,
358    ) -> compile::Result<usize> {
359        let current = current
360            .into_iter()
361            .map(|s| s.as_ref().try_to_owned())
362            .try_collect::<alloc::Result<Box<_>>>()??;
363
364        self.new_static_object_keys(span, current)
365    }
366
367    /// Insert a new collection of static object keys, or return one already
368    /// existing.
369    pub(crate) fn new_static_object_keys(
370        &mut self,
371        span: &dyn Spanned,
372        current: Box<[String]>,
373    ) -> compile::Result<usize> {
374        let hash = Hash::object_keys(&current[..]);
375
376        if let Some(existing_slot) = self.static_object_keys_rev.get(&hash).copied() {
377            let existing = self.static_object_keys.get(existing_slot).ok_or_else(|| {
378                compile::Error::new(
379                    span,
380                    ErrorKind::StaticObjectKeysMissing {
381                        hash,
382                        slot: existing_slot,
383                    },
384                )
385            })?;
386
387            if *existing != current {
388                return Err(compile::Error::new(
389                    span,
390                    ErrorKind::StaticObjectKeysHashConflict {
391                        hash,
392                        current,
393                        existing: existing.try_clone()?,
394                    },
395                ));
396            }
397
398            return Ok(existing_slot);
399        }
400
401        let new_slot = self.static_object_keys.len();
402        self.static_object_keys.try_push(current)?;
403        self.static_object_keys_rev.try_insert(hash, new_slot)?;
404        Ok(new_slot)
405    }
406
407    /// Declare a new struct.
408    pub(crate) fn insert_meta(
409        &mut self,
410        span: &dyn Spanned,
411        meta: &meta::Meta,
412        pool: &Pool,
413        query: &mut QueryInner,
414        debug_info: bool,
415    ) -> compile::Result<()> {
416        debug_assert_eq! {
417            pool.item_type_hash(meta.item_meta.item),
418            meta.hash,
419        };
420
421        match meta.kind {
422            meta::Kind::Type { .. } => {
423                let rtti = Arc::try_new(Rtti {
424                    kind: RttiKind::Empty,
425                    hash: meta.hash,
426                    variant_hash: Hash::EMPTY,
427                    item: pool.item(meta.item_meta.item).try_to_owned()?,
428                    fields: HashMap::default(),
429                })?;
430
431                self.constants
432                    .try_insert(
433                        Hash::associated_function(meta.hash, &Protocol::INTO_TYPE_NAME),
434                        ConstValueBuf::try_from(rtti.item.try_to_string()?)?,
435                    )
436                    .with_span(span)?;
437
438                if self
439                    .rtti
440                    .try_insert(meta.hash, rtti)
441                    .with_span(span)?
442                    .is_some()
443                {
444                    return Err(compile::Error::new(
445                        span,
446                        ErrorKind::TypeRttiConflict { hash: meta.hash },
447                    ));
448                }
449            }
450            meta::Kind::Struct {
451                fields: meta::Fields::Empty,
452                enum_hash: Hash::EMPTY,
453                ..
454            } => {
455                let info = UnitFn::EmptyStruct { hash: meta.hash };
456
457                let signature = DebugSignature::new(
458                    pool.item(meta.item_meta.item).try_to_owned()?,
459                    DebugArgs::EmptyArgs,
460                );
461
462                let rtti = Arc::try_new(Rtti {
463                    kind: RttiKind::Empty,
464                    hash: meta.hash,
465                    variant_hash: Hash::EMPTY,
466                    item: pool.item(meta.item_meta.item).try_to_owned()?,
467                    fields: HashMap::default(),
468                })?;
469
470                if self
471                    .rtti
472                    .try_insert(meta.hash, rtti)
473                    .with_span(span)?
474                    .is_some()
475                {
476                    return Err(compile::Error::new(
477                        span,
478                        ErrorKind::TypeRttiConflict { hash: meta.hash },
479                    ));
480                }
481
482                if self
483                    .functions
484                    .try_insert(meta.hash, info)
485                    .with_span(span)?
486                    .is_some()
487                {
488                    return Err(compile::Error::new(
489                        span,
490                        ErrorKind::FunctionConflict {
491                            existing: signature,
492                        },
493                    ));
494                }
495
496                self.constants
497                    .try_insert(
498                        Hash::associated_function(meta.hash, &Protocol::INTO_TYPE_NAME),
499                        ConstValueBuf::try_from(signature.path.try_to_string()?)?,
500                    )
501                    .with_span(span)?;
502
503                self.debug_mut()?
504                    .functions
505                    .try_insert(meta.hash, signature)?;
506            }
507            meta::Kind::Struct {
508                fields: meta::Fields::Empty,
509                enum_hash,
510                ..
511            } => {
512                let rtti = Arc::try_new(Rtti {
513                    kind: RttiKind::Empty,
514                    hash: enum_hash,
515                    variant_hash: meta.hash,
516                    item: pool.item(meta.item_meta.item).try_to_owned()?,
517                    fields: HashMap::default(),
518                })?;
519
520                if self
521                    .rtti
522                    .try_insert(meta.hash, rtti)
523                    .with_span(span)?
524                    .is_some()
525                {
526                    return Err(compile::Error::new(
527                        span,
528                        ErrorKind::RttiConflict { hash: meta.hash },
529                    ));
530                }
531
532                let info = UnitFn::EmptyStruct { hash: meta.hash };
533
534                let signature = DebugSignature::new(
535                    pool.item(meta.item_meta.item).try_to_owned()?,
536                    DebugArgs::EmptyArgs,
537                );
538
539                if self
540                    .functions
541                    .try_insert(meta.hash, info)
542                    .with_span(span)?
543                    .is_some()
544                {
545                    return Err(compile::Error::new(
546                        span,
547                        ErrorKind::FunctionConflict {
548                            existing: signature,
549                        },
550                    ));
551                }
552
553                self.debug_mut()?
554                    .functions
555                    .try_insert(meta.hash, signature)?;
556            }
557            meta::Kind::Struct {
558                fields: meta::Fields::Unnamed(args),
559                enum_hash: Hash::EMPTY,
560                ..
561            } => {
562                let info = UnitFn::TupleStruct {
563                    hash: meta.hash,
564                    args,
565                };
566
567                let signature = DebugSignature::new(
568                    pool.item(meta.item_meta.item).try_to_owned()?,
569                    DebugArgs::TupleArgs(args),
570                );
571
572                let rtti = Arc::try_new(Rtti {
573                    kind: RttiKind::Tuple,
574                    hash: meta.hash,
575                    variant_hash: Hash::EMPTY,
576                    item: pool.item(meta.item_meta.item).try_to_owned()?,
577                    fields: HashMap::default(),
578                })?;
579
580                if self
581                    .rtti
582                    .try_insert(meta.hash, rtti)
583                    .with_span(span)?
584                    .is_some()
585                {
586                    return Err(compile::Error::new(
587                        span,
588                        ErrorKind::TypeRttiConflict { hash: meta.hash },
589                    ));
590                }
591
592                if self
593                    .functions
594                    .try_insert(meta.hash, info)
595                    .with_span(span)?
596                    .is_some()
597                {
598                    return Err(compile::Error::new(
599                        span,
600                        ErrorKind::FunctionConflict {
601                            existing: signature,
602                        },
603                    ));
604                }
605
606                self.constants
607                    .try_insert(
608                        Hash::associated_function(meta.hash, &Protocol::INTO_TYPE_NAME),
609                        ConstValueBuf::try_from(signature.path.try_to_string()?)?,
610                    )
611                    .with_span(span)?;
612
613                self.debug_mut()?
614                    .functions
615                    .try_insert(meta.hash, signature)?;
616            }
617            meta::Kind::Struct {
618                fields: meta::Fields::Unnamed(args),
619                enum_hash,
620                ..
621            } => {
622                let rtti = Arc::try_new(Rtti {
623                    kind: RttiKind::Tuple,
624                    hash: enum_hash,
625                    variant_hash: meta.hash,
626                    item: pool.item(meta.item_meta.item).try_to_owned()?,
627                    fields: HashMap::default(),
628                })?;
629
630                if self
631                    .rtti
632                    .try_insert(meta.hash, rtti)
633                    .with_span(span)?
634                    .is_some()
635                {
636                    return Err(compile::Error::new(
637                        span,
638                        ErrorKind::RttiConflict { hash: meta.hash },
639                    ));
640                }
641
642                let info = UnitFn::TupleStruct {
643                    hash: meta.hash,
644                    args,
645                };
646
647                let signature = DebugSignature::new(
648                    pool.item(meta.item_meta.item).try_to_owned()?,
649                    DebugArgs::TupleArgs(args),
650                );
651
652                if self
653                    .functions
654                    .try_insert(meta.hash, info)
655                    .with_span(span)?
656                    .is_some()
657                {
658                    return Err(compile::Error::new(
659                        span,
660                        ErrorKind::FunctionConflict {
661                            existing: signature,
662                        },
663                    ));
664                }
665
666                self.debug_mut()?
667                    .functions
668                    .try_insert(meta.hash, signature)?;
669            }
670            meta::Kind::Struct {
671                fields: meta::Fields::Named(ref named),
672                enum_hash: Hash::EMPTY,
673                ..
674            } => {
675                let rtti = Arc::try_new(Rtti {
676                    kind: RttiKind::Struct,
677                    hash: meta.hash,
678                    variant_hash: Hash::EMPTY,
679                    item: pool.item(meta.item_meta.item).try_to_owned()?,
680                    fields: named.to_fields()?,
681                })?;
682
683                self.constants
684                    .try_insert(
685                        Hash::associated_function(meta.hash, &Protocol::INTO_TYPE_NAME),
686                        ConstValueBuf::try_from(rtti.item.try_to_string()?)?,
687                    )
688                    .with_span(span)?;
689
690                if self
691                    .rtti
692                    .try_insert(meta.hash, rtti)
693                    .with_span(span)?
694                    .is_some()
695                {
696                    return Err(compile::Error::new(
697                        span,
698                        ErrorKind::TypeRttiConflict { hash: meta.hash },
699                    ));
700                }
701            }
702            meta::Kind::Struct {
703                fields: meta::Fields::Named(ref named),
704                enum_hash,
705                ..
706            } => {
707                let rtti = Arc::try_new(Rtti {
708                    kind: RttiKind::Struct,
709                    hash: enum_hash,
710                    variant_hash: meta.hash,
711                    item: pool.item(meta.item_meta.item).try_to_owned()?,
712                    fields: named.to_fields()?,
713                })?;
714
715                if self
716                    .rtti
717                    .try_insert(meta.hash, rtti)
718                    .with_span(span)?
719                    .is_some()
720                {
721                    return Err(compile::Error::new(
722                        span,
723                        ErrorKind::RttiConflict { hash: meta.hash },
724                    ));
725                }
726            }
727            meta::Kind::Enum { .. } => {
728                let name = pool
729                    .item(meta.item_meta.item)
730                    .try_to_string()
731                    .with_span(span)?;
732
733                self.constants
734                    .try_insert(
735                        Hash::associated_function(meta.hash, &Protocol::INTO_TYPE_NAME),
736                        ConstValueBuf::try_from(name)?,
737                    )
738                    .with_span(span)?;
739            }
740            meta::Kind::Const => {
741                let Some(const_value) = query.get_const_value(meta.hash) else {
742                    return Err(compile::Error::msg(
743                        span,
744                        try_format!("Missing constant for hash {}", meta.hash),
745                    ));
746                };
747
748                let value = const_value.try_to_owned().with_span(span)?;
749
750                self.constants
751                    .try_insert(meta.hash, value)
752                    .with_span(span)?;
753            }
754            meta::Kind::Static => {
755                let init = match query.get_static_init(meta.hash) {
756                    Some(init) => Some(init.try_to_owned().with_span(span)?),
757                    None => None,
758                };
759
760                self.insert_global(meta.hash, pool.item(meta.item_meta.item), init, debug_info)
761                    .with_span(span)?;
762            }
763            meta::Kind::Macro => (),
764            meta::Kind::AttributeMacro => (),
765            meta::Kind::Function { .. } => (),
766            meta::Kind::Closure { .. } => (),
767            meta::Kind::AsyncBlock { .. } => (),
768            meta::Kind::ConstFn => (),
769            meta::Kind::Import { .. } => (),
770            meta::Kind::Alias { .. } => (),
771            meta::Kind::Module => (),
772            meta::Kind::Trait => (),
773        }
774
775        Ok(())
776    }
777
778    /// Construct a new empty assembly associated with the current unit.
779    pub(crate) fn new_assembly(&self, location: Location) -> Assembly {
780        Assembly::new(location, self.label_count)
781    }
782
783    /// Register a new function re-export.
784    pub(crate) fn new_function_reexport(
785        &mut self,
786        location: Location,
787        item: &Item,
788        target: &Item,
789    ) -> compile::Result<()> {
790        let hash = Hash::type_hash(item);
791        let target = Hash::type_hash(target);
792
793        if self.reexports.try_insert(hash, target)?.is_some() {
794            return Err(compile::Error::new(
795                location.span,
796                ErrorKind::FunctionReExportConflict { hash },
797            ));
798        }
799
800        Ok(())
801    }
802
803    /// Declare a new instance function at the current instruction pointer.
804    pub(crate) fn new_function(
805        &mut self,
806        location: Location,
807        item: &Item,
808        instance: Option<(Hash, &str)>,
809        args: usize,
810        captures: Option<usize>,
811        assembly: Assembly,
812        call: Call,
813        debug_args: Box<[Box<str>]>,
814        unit_storage: &mut dyn UnitEncoder,
815        size: usize,
816    ) -> compile::Result<()> {
817        tracing::trace!("instance fn: {}", item);
818
819        let offset = unit_storage.offset();
820
821        let info = UnitFn::Offset {
822            offset,
823            call,
824            args,
825            captures,
826        };
827        let signature = DebugSignature::new(item.try_to_owned()?, DebugArgs::Named(debug_args));
828
829        if let Some((type_hash, name)) = instance {
830            let instance_fn = Hash::associated_function(type_hash, name);
831
832            if self
833                .functions
834                .try_insert(instance_fn, info)
835                .with_span(location.span)?
836                .is_some()
837            {
838                return Err(compile::Error::new(
839                    location.span,
840                    ErrorKind::FunctionConflict {
841                        existing: signature,
842                    },
843                ));
844            }
845
846            self.debug_mut()?
847                .functions
848                .try_insert(instance_fn, signature.try_clone()?)?;
849        }
850
851        let hash = Hash::type_hash(item);
852
853        if self
854            .functions
855            .try_insert(hash, info)
856            .with_span(location.span)?
857            .is_some()
858        {
859            return Err(compile::Error::new(
860                location.span,
861                ErrorKind::FunctionConflict {
862                    existing: signature,
863                },
864            ));
865        }
866
867        self.constants
868            .try_insert(
869                Hash::associated_function(hash, &Protocol::INTO_TYPE_NAME),
870                ConstValueBuf::try_from(signature.path.try_to_string().with_span(location.span)?)?,
871            )
872            .with_span(location.span)?;
873
874        self.debug_mut()?.functions.try_insert(hash, signature)?;
875        self.functions_rev.try_insert(offset, hash)?;
876        self.add_assembly(location, assembly, unit_storage, size)?;
877        Ok(())
878    }
879
880    /// Declare a function which only exists inside of the unit it is being
881    /// assembled into, addressed by hash rather than by item.
882    ///
883    /// This is used by constant evaluation, which assembles the constants it
884    /// evaluates into an interior unit. Those functions are never looked up by
885    /// name and never outlive the evaluation, so they carry no debug signature
886    /// and no `INTO_TYPE_NAME` constant.
887    pub(crate) fn new_const_function(
888        &mut self,
889        location: Location,
890        hash: Hash,
891        args: usize,
892        assembly: Assembly,
893        unit_storage: &mut dyn UnitEncoder,
894        size: usize,
895    ) -> compile::Result<()> {
896        let offset = unit_storage.offset();
897
898        let info = UnitFn::Offset {
899            offset,
900            call: Call::Immediate,
901            args,
902            captures: None,
903        };
904
905        if self
906            .functions
907            .try_insert(hash, info)
908            .with_span(location.span)?
909            .is_some()
910        {
911            return Err(compile::Error::new(
912                location.span,
913                ErrorKind::FunctionConflictHash { hash },
914            ));
915        }
916
917        self.add_assembly(location, assembly, unit_storage, size)?;
918        Ok(())
919    }
920
921    /// Try to link the unit with the context, checking that all necessary
922    /// functions are provided.
923    ///
924    /// This can prevent a number of runtime errors, like missing functions.
925    pub(crate) fn link(
926        &mut self,
927        context: &Context,
928        diagnostics: &mut Diagnostics,
929    ) -> alloc::Result<()> {
930        for (hash, spans) in &self.required_functions {
931            // A declared function is provided by the host, which is not
932            // necessarily the context being compiled against: a language
933            // server or `rune check` has only the declarations to go by.
934            if self.functions.get(hash).is_none()
935                && context.lookup_function(*hash).is_none()
936                && !self.declared.contains_key(hash)
937            {
938                diagnostics.error(
939                    SourceId::empty(),
940                    LinkerError::MissingFunction {
941                        hash: *hash,
942                        spans: spans.try_clone()?,
943                    },
944                )?;
945            }
946        }
947
948        Ok(())
949    }
950
951    /// Insert and access debug information.
952    fn debug_mut(&mut self) -> alloc::Result<&mut DebugInfo> {
953        if self.debug.is_none() {
954            self.debug = Some(Box::try_new(DebugInfo::default())?);
955        }
956
957        Ok(self.debug.as_mut().unwrap())
958    }
959
960    /// Translate the given assembly into instructions.
961    fn add_assembly(
962        &mut self,
963        location: Location,
964        assembly: Assembly,
965        storage: &mut dyn UnitEncoder,
966        size: usize,
967    ) -> compile::Result<()> {
968        self.label_count = assembly.label_count;
969
970        storage
971            .encode(Inst::new(inst::Kind::Allocate { size }))
972            .with_span(location.span)?;
973
974        let base = storage.extend_offsets(assembly.labels.len())?;
975
976        self.required_functions
977            .try_extend(assembly.required_functions)?;
978
979        for (offset, (_, labels)) in &assembly.labels {
980            for label in labels {
981                if let Some(jump) = label.jump() {
982                    label.set_jump(storage.label_jump(base, *offset, jump));
983                }
984            }
985        }
986
987        for (pos, (inst, span)) in assembly.instructions.into_iter().enumerate() {
988            let mut comment = String::new();
989
990            let at = storage.offset();
991
992            let mut labels = Vec::new();
993
994            for label in assembly
995                .labels
996                .get(&pos)
997                .map(|e| e.1.as_slice())
998                .unwrap_or_default()
999            {
1000                if let Some(index) = label.jump() {
1001                    storage.mark_offset(index);
1002                }
1003
1004                labels.try_push(label.to_debug_label())?;
1005            }
1006
1007            let build_label = |label: Label| {
1008                label
1009                    .jump()
1010                    .ok_or(ErrorKind::MissingLabelLocation {
1011                        name: label.name,
1012                        index: label.index,
1013                    })
1014                    .with_span(span)
1015            };
1016
1017            match inst {
1018                AssemblyInst::Jump { label } => {
1019                    write!(comment, "label:{label}")?;
1020                    let jump = build_label(label)?;
1021                    storage
1022                        .encode(Inst::new(inst::Kind::Jump { jump }))
1023                        .with_span(span)?;
1024                }
1025                AssemblyInst::JumpIf { addr, label } => {
1026                    write!(comment, "label:{label}")?;
1027                    let jump = build_label(label)?;
1028                    storage
1029                        .encode(Inst::new(inst::Kind::JumpIf { cond: addr, jump }))
1030                        .with_span(span)?;
1031                }
1032                AssemblyInst::JumpIfNot { addr, label } => {
1033                    write!(comment, "label:{label}")?;
1034                    let jump = build_label(label)?;
1035                    storage
1036                        .encode(Inst::new(inst::Kind::JumpIfNot { cond: addr, jump }))
1037                        .with_span(span)?;
1038                }
1039                AssemblyInst::IterNext { addr, label, out } => {
1040                    write!(comment, "label:{label}")?;
1041                    let jump = build_label(label)?;
1042                    storage
1043                        .encode(Inst::new(inst::Kind::IterNext { addr, jump, out }))
1044                        .with_span(span)?;
1045                }
1046                AssemblyInst::Raw { raw } => {
1047                    // Optimization to avoid performing lookups for recursive
1048                    // function calls.
1049                    let kind = match raw {
1050                        inst @ inst::Kind::Call {
1051                            hash,
1052                            addr,
1053                            args,
1054                            out,
1055                        } => {
1056                            if let Some(UnitFn::Offset { offset, call, .. }) =
1057                                self.functions.get(&hash)
1058                            {
1059                                inst::Kind::CallOffset {
1060                                    offset: *offset,
1061                                    call: *call,
1062                                    addr,
1063                                    args,
1064                                    out,
1065                                }
1066                            } else {
1067                                inst
1068                            }
1069                        }
1070                        kind => kind,
1071                    };
1072
1073                    storage.encode(Inst::new(kind)).with_span(span)?;
1074                }
1075            }
1076
1077            if let Some(c) = assembly.comments.get(&pos) {
1078                if !comment.is_empty() {
1079                    comment.try_push_str("; ")?;
1080                }
1081
1082                comment.try_push_str(c)?;
1083            }
1084
1085            let comment = if comment.is_empty() {
1086                None
1087            } else {
1088                Some(comment.try_into()?)
1089            };
1090
1091            self.debug_mut()?.instructions.try_insert(
1092                at,
1093                DebugInst::new(location.source_id, span, comment, labels),
1094            )?;
1095        }
1096
1097        Ok(())
1098    }
1099}
1100
1101/// A set of addresses that should be dropped.
1102pub(crate) struct DropSet<'a> {
1103    builder: &'a mut UnitBuilder,
1104    addresses: Vec<Address>,
1105}
1106
1107impl DropSet<'_> {
1108    /// Construct a new drop set.
1109    pub(crate) fn push(&mut self, addr: Address) -> alloc::Result<()> {
1110        self.addresses.try_push(addr)
1111    }
1112
1113    pub(crate) fn finish(self) -> alloc::Result<Option<usize>> {
1114        if self.addresses.is_empty() {
1115            return Ok(None);
1116        }
1117
1118        if let Some(set) = self.builder.drop_sets_rev.get(&self.addresses) {
1119            return Ok(Some(*set));
1120        }
1121
1122        let set = self.builder.drop_sets.len();
1123
1124        self.builder
1125            .drop_sets_rev
1126            .try_insert(self.addresses.try_clone()?, set)?;
1127        self.builder
1128            .drop_sets
1129            .try_push(Arc::copy_from_slice(&self.addresses[..])?)?;
1130        Ok(Some(set))
1131    }
1132}