blob: 18719cdbfe984704defce8b840c72967b0447ae8 (
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
|
#pragma once
#include "bnf.h"
#include "minicc.h"
#include <cstdint>
namespace Gram {
// TreeNodes are only intermediate. Terminal symbols don't get of TreeNodes
// token_id: index into token list
// node_id: index into tree node list
struct TreeNode {
index_t parent_node_id{}; // root if parent_node_id == node_id
index_t node_id{};
std::string type;
index_t variant; // bnf[type][variant]
std::deque<std::string> alternative_types; // alternatives that we can consider if type fails. Discard after parsing!
std::vector<int32_t> child_ids; // < 0: terminal: token_id; >= 0: non-terminal: node_id; fill token by token
};
class Compiler
{
private:
// The result
index_t root_node_id{};
std::vector<TreeNode> nodes;
// Input
std::vector<std::string> tokens;
// Helper data
index_t tokens_used{0}; // number of tokens used, this is also the next token index to use
const BNF &bnf;
const std::string& Top;
std::map<std::string, std::set<std::string>> ReverseBNF; // possible parent types of a given type
public:
// Tree specific
void clear();
// Node specific
std::string GetTypeOfNode(index_t node_id) const;
index_t TrackBack();
void Validate(const std::string& Top, const BNF& bnf) const;
void Dump();
Compiler(const BNF& bnf, const std::string& Top);
std::pair<index_t, std::vector<TreeNode>> compile(std::vector<Token> Tokens);
};
} // namespace Gram
|