aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/WebAssembly/Execution/Store.php
blob: 18f86269f4f9d6913c2e3145beffa9777b1c7edf (plain)
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
<?php

declare(strict_types=1);

namespace Nsfisis\Waddiwasi\WebAssembly\Execution;

use RuntimeException;
use function count;

final class Store
{
    /**
     * @param list<FuncInst> $funcs
     * @param list<TableInst> $tables
     * @param list<MemInst> $mems
     * @param list<GlobalInst> $globals
     * @param list<ElemInst> $elems
     * @param list<DataInst> $datas
     */
    public function __construct(
        public array $funcs,
        public array $tables,
        public array $mems,
        public array $globals,
        public array $elems,
        public array $datas,
    ) {
    }

    public static function empty(): self
    {
        return new self([], [], [], [], [], []);
    }

    public function register(Extern $extern): ExternVal
    {
        switch ($extern::class) {
            case Externs\Func::class:
                foreach ($this->funcs as $i => $f) {
                    if ($f === $extern->func) {
                        return ExternVal::Func($i);
                    }
                }
                $this->funcs[] = $extern->func;
                return ExternVal::Func(count($this->funcs) - 1);
            case Externs\Table::class:
                foreach ($this->tables as $i => $t) {
                    if ($t === $extern->table) {
                        return ExternVal::Table($i);
                    }
                }
                $this->tables[] = $extern->table;
                return ExternVal::Table(count($this->tables) - 1);
            case Externs\Mem::class:
                foreach ($this->mems as $i => $m) {
                    if ($m === $extern->mem) {
                        return ExternVal::Mem($i);
                    }
                }
                $this->mems[] = $extern->mem;
                return ExternVal::Mem(count($this->mems) - 1);
            case Externs\Global_::class:
                foreach ($this->globals as $i => $g) {
                    if ($g === $extern->global) {
                        return ExternVal::Global_($i);
                    }
                }
                $this->globals[] = $extern->global;
                return ExternVal::Global_(count($this->globals) - 1);
            default:
                throw new RuntimeException("unreachable");
        }
    }
}