summaryrefslogtreecommitdiffhomepage
path: root/grammer.cpp
blob: 31a4bbf55cde22a951fb343bbf725dee6401c29f (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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#include "grammer.h"

#include "debug.h"

#include <algorithm>
#include <limits>

using namespace Gram;

void Compiler::clear()
{
 symbol_variants.clear();
 nodes.clear();
}

std::string Compiler::GetTypeOfNode(index_t node_id) const
{
 if (node_id >= nodes.size())
  throw std::runtime_error("GetTypeOfNode(): node_id="s + std::to_string(node_id) + ", nodes.size()="s + std::to_string(nodes.size()));
 return nodes[node_id].type;
}

bool Gram::ChildIdIsEmpty(int32_t child_id)
{
 return child_id == 0;
}

bool Gram::ChildIdIsToken(int32_t child_id)
{
 return child_id < 0;
}

bool Gram::ChildIdIsNode(int32_t child_id)
{
 return child_id > 0;
}

index_t Gram::TokenIdFromChildId(int32_t child_id)
{
 return index_t(-child_id) - 1;
}

int32_t Gram::ChildIdFromTokenId(index_t token_id)
{
 return -1 - int32_t(token_id);
}

void Compiler::DumpTree()
{
 Debug("= Dump =======================================");
 Debug("nodes.size()="s + std::to_string(nodes.size()));
 if (nodes.size() > 0) {
  if (0) {
   Debug("--- Nodes ------------------------------------");
   for (const auto& node : nodes) {
    std::string line{"("s + std::to_string(node.node_id) + "):"s};
    for (const auto& child : node.child_ids) {
     line += " "s;
     if (ChildIdIsToken(child))
      line += "t"s + std::to_string(TokenIdFromChildId(child));
     else
      line += std::to_string(child);
    }
    Debug(line);
   }
  }

  Debug("--- Tree -------------------------------------");
  std::deque<std::pair<int32_t, size_t>> todo{std::pair<int32_t, size_t>{static_cast<int32_t>(0), 0}}; // id, indent
  while (!todo.empty()) {
   auto [current_index, indent] {todo.front()};
   todo.pop_front();

   std::string line(indent, ' ');
   if (ChildIdIsToken(current_index)) {
    index_t token_id {TokenIdFromChildId(current_index)};
    line += "Token("s + std::to_string(token_id) + "): "s + tokens[token_id].type;
    if (tokens[token_id].value != tokens[token_id].type)
     line += "("s + tokens[token_id].value + ")"s;
   } else {
    auto& node {nodes[current_index]};
    line += "Node("s + std::to_string(current_index) + "): "s + node.type + "/" + std::to_string(node.variant);
   
    auto child_ids{node.child_ids};
    for (int i = 0; i < child_ids.size(); i++) {
     todo.insert(todo.begin() + i, std::pair<int32_t, size_t>{child_ids[i], indent + 1});
    }
   }
   Debug(line);
  }
 }
 Debug("==============================================");
}

index_t Compiler::AddNode(const std::string& type, index_t variant, NodePosition pos)
{
 auto& list { m_bnf[type][variant]};
 index_t node_id{nodes.size()};
 if (nodes.size() > 0)
  nodes[pos.node_id].child_ids[pos.child_pos] = node_id;
 nodes.emplace_back(TreeNode{pos, node_id, type, variant, std::vector<int32_t>(size_t(list.size()), 0)});

 return node_id;
}

Compiler::AddNodeGuard::AddNodeGuard(Compiler& compiler, index_t variant): m_compiler(compiler)
{
 m_compiler.symbol_variants.push_back(variant);
}

Compiler::AddNodeGuard::~AddNodeGuard()
{
 m_compiler.symbol_variants.pop_back();
}

void Compiler::IncNodePosition(NodePosition& pos)
{
 if (nodes.size() == 0) // special case: empty tree 
  return;
 if (pos.node_id >= nodes.size())
  throw std::runtime_error("ICE: NodePosition with node_id "s + std::to_string(pos.node_id) + " doesn't exist."s);
 if (pos.child_pos >= nodes[pos.node_id].child_ids.size())
  throw std::runtime_error("ICE: NodePosition with child_pos "s + std::to_string(pos.child_pos) + " in node_id "s + std::to_string(pos.node_id) + " doesn't exist."s);

 int32_t child_id{nodes[pos.node_id].child_ids[pos.child_pos]};

 if (ChildIdIsEmpty(child_id))
  throw std::runtime_error("ICE: NodePosition is empty");

 // Actually, advance
 if (ChildIdIsToken(child_id)) {
  pos.child_pos++;
 } else {
  pos.node_id = child_id;
  pos.child_pos = 0;
 }
 
 // Go to parent if child ids completely traversed
 while (pos.node_id > 0 && pos.child_pos >= nodes[pos.node_id].child_ids.size()) {
  pos = nodes[pos.node_id].pos;
  pos.child_pos++;
 }

 // Advancing at root node for last child is allowed: Finished
 if (pos.child_pos >= nodes[pos.node_id].child_ids.size())
  return;

 if (ChildIdIsNode(nodes[pos.node_id].child_ids[pos.child_pos]))
  throw std::runtime_error("ICE: No node expected at "s + std::to_string(pos.node_id) + "/"s + std::to_string(pos.child_pos));
}

size_t Compiler::minimumSymbolsNeeded(const std::string& symbol)
{
 if (isTerminal(m_bnf, symbol)) {
  return 1;
 } else {
  auto it_min{m_min.find(symbol)};
  if (it_min != m_min.end())
   return it_min->second;
  m_min[symbol] = std::numeric_limits<size_t>::max();

  auto it{m_bnf.find(symbol)};
  if (it != m_bnf.end()) {
   size_t minimum{std::numeric_limits<size_t>::max()};
   
   for (const auto& list: it->second) {
    minimum = std::min(minimum, minimumSymbolsNeeded(list));
   }

   m_min[symbol] = minimum;

   return minimum;
  } else
   throw std::runtime_error("ICE: Symbol "s + symbol + " expected in BNF"s);
 }
}

size_t Compiler::minimumSymbolsNeeded(const std::vector<std::string>& symbol_list)
{
 size_t result{0};

 for (const auto& symbol: symbol_list) {
  size_t min { minimumSymbolsNeeded(symbol) };
  if (min == std::numeric_limits<size_t>::max())
   return min;
  result += min;
 }

 return result;
}

/// begin, end: indexes in tokens list
bool Compiler::match(std::vector<std::string> symbol_list, size_t begin, size_t end)
{
 // match terminal symbols at start
 while (begin < end && symbol_list.size() > 0 && symbol_list.front() == tokens[begin].type) {
  begin++;
  symbol_list.erase(symbol_list.begin());
 }

 // matching of empty list in non-terminals
 if (symbol_list.size() == 0) {
  if (begin == end) { // only match real empty list
   // this is the point of the final match
   constructTree();
   return true;
  }
  return false;
 }

 // matching of empty list in terminals
 if (begin == end) {
  const auto& symbol{symbol_list.front()};
  auto it{m_empty_lut.find(symbol)};
  if (it == m_empty_lut.end()) // can't match empty tokens list with this nt-symbol
   return false;

  AddNodeGuard guard(*this, it->second);
  std::vector<std::string> list {m_bnf[symbol][it->second]};
  list.insert(list.end(), symbol_list.begin() + 1, symbol_list.end());
  return match(list, begin, end);
 }

 // now, symbol_list has size > 0 and contains non-terminal symbols at start and end
 
 // resolve first symbol
 auto it = m_match_lut.find({symbol_list.front(), tokens[begin].type});
 if (it != m_match_lut.end()) {
  for (size_t i: it->second) {
   AddNodeGuard guard(*this, i);
   std::vector<std::string> list {m_bnf[symbol_list.front()][i]};
   list.insert(list.end(), symbol_list.begin() + 1, symbol_list.end());
   if (minimumSymbolsNeeded(list) > end - begin) // stop recursion
    continue;

   if (match(list, begin, end))
    return true;
  }
 } else
  return false; // terminal symbol not found in bnf, non-matching
 
 return false; // no match found
}

bool Compiler::match(std::string symbol, size_t begin, size_t end)
{
 std::vector<std::string> symbol_list{symbol};
 return match(symbol_list, begin, end);
}

void Compiler::fillStartCache()
{
 std::unordered_set<std::string> terminals {getTerminals(m_bnf)};

 { // follow terminal symbols
  for (const std::string& terminal: terminals) {
   std::unordered_set<std::string> current_set{terminal};
   std::unordered_set<std::string> done_set;
   std::unordered_set<std::string> next_set;

   do {
    for (const auto& current_symbol: current_set) {
     auto it {reversedPosFirst.find(current_symbol)};
     if (it != reversedPosFirst.end()) {
      std::unordered_set<std::pair<std::string, index_t>, PairHash>& positions{it->second};

      for (const auto& position: positions) {
       auto it_lut {m_match_lut.find({position.first, terminal})};
       if (it_lut == m_match_lut.end()) { // add new list
        m_match_lut[std::pair<std::string, std::string>{position.first, terminal}] = std::vector<size_t>{position.second};
       } else { // extend list
        it_lut->second.emplace_back(position.second);
       }

       if (done_set.find(position.first) == done_set.end()) {
        next_set.insert(position.first);
        done_set.insert(position.first);
       }
      }
     }
    }

    current_set = next_set;
    next_set.clear();
   } while (!current_set.empty());
  }
 }

 { // follow empty non-terminal symbols, and combine all found non-terminals with all terminals
  std::unordered_set<std::pair<std::string, size_t>, PairHash> current_set {getEmptyPositions(m_bnf)};
  std::unordered_set<std::pair<std::string, size_t>, PairHash> done_set;
  std::unordered_set<std::pair<std::string, size_t>, PairHash> next_set;

  do {
   for (const auto& current_pos: current_set) {
    m_empty_lut[current_pos.first] = current_pos.second;
    for (const std::string& terminal: terminals) {
     auto it_lut {m_match_lut.find({current_pos.first, terminal})};
     if (it_lut == m_match_lut.end()) { // add new list
      m_match_lut[std::pair<std::string, std::string>{current_pos.first, terminal}] = std::vector<size_t>{current_pos.second};
     } else { // extend list
      it_lut->second.emplace_back(current_pos.second);
     }
    }

    auto it {reversedPosFirst.find(current_pos.first)};
    if (it != reversedPosFirst.end()) {
     std::unordered_set<std::pair<std::string, index_t>, PairHash>& positions{it->second};

     for (const auto& position: positions) {
      if (done_set.find(position) == done_set.end()) {
       next_set.insert(position);
       done_set.insert(position);
      }
     }
    }

   }

   current_set = next_set;
   next_set.clear();
  } while (!current_set.empty());
 }

 for (auto& x: m_match_lut) {
  std::sort(x.second.begin(), x.second.end());
 }
}

void Compiler::constructTree()
{
 symbol_variants_it = symbol_variants.begin();
 
 std::vector<std::string> symbol_list{m_top};
 index_t symbol_list_pos{0};

 NodePosition tree_pos;

 while (symbol_list_pos < symbol_list.size()) {
  std::string symbol{symbol_list[symbol_list_pos]};

  if (isTerminal(m_bnf, symbol)) {
   // Advance terminal symbol
   nodes[tree_pos.node_id].child_ids[tree_pos.child_pos] = ChildIdFromTokenId(symbol_list_pos);
   IncNodePosition(tree_pos);
   symbol_list_pos++;
  } else {
   // Replace non-terminal symbol
   symbol_list.erase(symbol_list.begin() + symbol_list_pos);
   std::vector<std::string> list {m_bnf[symbol][*symbol_variants_it]};
   symbol_list.insert(symbol_list.begin() + symbol_list_pos, list.begin(), list.end());

   index_t node_id {AddNode(symbol, *symbol_variants_it, tree_pos)};
   
   if (node_id > 0) {
    nodes[tree_pos.node_id].child_ids[tree_pos.child_pos] = node_id;
    IncNodePosition(tree_pos);
   }
   
   symbol_variants_it++;
  }
 }

}

Compiler::Compiler(BNF& bnf, const std::string& top)
 : m_bnf {removeHeadRecursion(bnf)}
 , m_top(top)
 , reversedPosFirst{reversePosFirst(m_bnf)}
{
 //
 // prepare helper cache (TODO: remove this ugly workaround for remaining bad marker elements)
 //
 (void) minimumSymbolsNeeded("translation-unit");
 // remove bad marker elements
 auto it{m_min.begin()};
 while (it != m_min.end()) {
  if (it->second == std::numeric_limits<size_t>::max()) {
   it = m_min.erase(it);
  } else {
   ++it;
  }
 }
 (void) minimumSymbolsNeeded("translation-unit");

 // fill other cache
 fillStartCache();
}

std::vector<TreeNode> Compiler::compile(std::vector<Token> p_tokens)
{
 clear();
 tokens = p_tokens;

 if (tokens.size() == 0)
  throw std::runtime_error("No tokens");

 //
 // top-down algorithm:
 //
 // 1. Match linear tokens list to bnf, building up list of used variants (symbol_variants)
 // 2. Construct Node Tree from symbol_variants
 //
 if (!match(m_top, 0, tokens.size()))
  throw std::runtime_error("Compile error");

 DumpTree();

 return nodes;
}