summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Bytecode/Generator.h
blob: 110ad25ac5b78637b3fb4d5a30bbf041bab88146 (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
/*
 * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/OwnPtr.h>
#include <LibJS/Bytecode/Block.h>
#include <LibJS/Bytecode/Label.h>
#include <LibJS/Forward.h>

namespace JS::Bytecode {

class Generator {
public:
    static OwnPtr<Block> generate(ASTNode const&);

    Register allocate_register();

    template<typename OpType, typename... Args>
    InstructionHandle<OpType> emit(Args&&... args)
    {
        return make_instruction<OpType>(0, forward<Args>(args)...);
    }

    template<typename OpType, typename... Args>
    InstructionHandle<OpType> emit_with_extra_register_slots(size_t extra_register_slots, Args&&... args)
    {
        return make_instruction<OpType>(extra_register_slots, forward<Args>(args)...);
    }

    Label make_label() const;

    void begin_continuable_scope();
    void end_continuable_scope();

    Label nearest_continuable_scope() const;

private:
    Generator();
    ~Generator();

    template<typename OpType, typename... Args>
    InstructionHandle<OpType> make_instruction(size_t extra_register_slots, Args&&... args)
    {
        auto& buffer = m_block->buffer();
        auto offset = buffer.size();
        buffer.resize(buffer.size() + sizeof(OpType) + extra_register_slots * sizeof(Register));
        new (buffer.data() + offset) OpType(forward<Args>(args)...);
        return InstructionHandle<OpType>(offset, m_block);
    }

    OwnPtr<Block> m_block;
    u32 m_next_register { 1 };
    Vector<Label> m_continuable_scopes;
};

}