blob: fbe66757c6edda12387a9216a59994940c8bded8 (
plain) (
blame)
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
|
#include <cassert>
#include "assembler.hpp"
#include "bytecode.hpp"
#include "symbol.hpp"
#include "tokenizer.hpp"
namespace SpasmImpl
{
namespace ASM
{
Assembler::Assembler(Lexer::Tokenizer& tokenizer, Bytecode_Stream& bytecode)
: _tokenizer(&tokenizer), _bytecode(&bytecode)
{
}
void Assembler::assemble()
{
Lexer::Token token = _tokenizer->next_token();
while (token.type() != Lexer::Token::EndInput)
{
const auto type = token.type();
if (type >= Lexer::Token::_NotOpCodeBegin)
{
switch (token.type())
{
case Lexer::Token::Ident:
assemble_identifier(token);
break;
case Lexer::Token::Label:
token = _tokenizer->next_token();
assert(token.type() == Lexer::Token::Ident);
_symbols.define(token.value_str(), _bytecode->size());
break;
default:
break;
}
}
else
{
_bytecode->push_opcode((Bytecode_Stream::Opcode_t)token.type());
if (type >= Lexer::Token::_OneArgBegin)
{
if (type == Lexer::Token::Call || type == Lexer::Token::Jump)
{
token = _tokenizer->next_token();
assert(token.type() == Lexer::Token::Ident);
assemble_identifier(token);
}
else
{
token = _tokenizer->next_token();
assert(token.type() == Lexer::Token::Integer);
_bytecode->push_integer(token.value_int());
}
}
if (type >= Lexer::Token::_TwoArgBegin)
{
if (type == Lexer::Token::JumpF || type == Lexer::Token::JumpT)
{
token = _tokenizer->next_token();
assert(token.type() == Lexer::Token::Ident);
assemble_identifier(token);
}
else
{
token = _tokenizer->next_token();
assert(token.type() == Lexer::Token::Integer);
_bytecode->push_integer(token.value_int());
}
}
if (type >= Lexer::Token::_ThreeArgBegin)
{
token = _tokenizer->next_token();
assert(token.type() == Lexer::Token::Integer);
_bytecode->push_integer(token.value_int());
}
}
token = _tokenizer->next_token();
}
Symbol_Table::const_iterator i = _symbols.begin();
while (i != _symbols.end())
{
backpatch(i->second);
++i;
}
}
void Assembler::backpatch(const Symbol* symbol)
{
Symbol::Positions_t::const_iterator i = symbol->positions_begin();
while (i != symbol->positions_end())
{
_bytecode->set_location(*i, symbol->definition());
++i;
}
}
void Assembler::assemble_identifier(const Lexer::Token& token)
{
Symbol* symbol = _symbols.insert(token.value_str(), _bytecode->size());
_bytecode->push_location(symbol->definition());
}
bool compile(std::istream& istr, Bytecode_Memory& bytecode)
{
Lexer::Tokenizer tokenizer(istr);
Assembler assembler(tokenizer, bytecode);
assembler.assemble();
return true;
}
} // namespace ASM
} // namespace SpasmImpl
|