aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/antlr4_cpp_runtime/src/dfa/DFASerializer.cpp
blob: 64d01769de596b35d9ae926afd76bf05bd0ce1b9 (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
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

#include "dfa/DFA.h"
#include "Vocabulary.h"

#include "dfa/DFASerializer.h"

using namespace antlr4::dfa;

DFASerializer::DFASerializer(const DFA *dfa, const Vocabulary &vocabulary) : _dfa(dfa), _vocabulary(vocabulary) {
}

std::string DFASerializer::toString() const {
  if (_dfa->s0 == nullptr) {
    return "";
  }

  std::stringstream ss;
  std::vector<DFAState *> states = _dfa->getStates();
  for (auto *s : states) {
    for (size_t i = 0; i < s->edges.size(); i++) {
      DFAState *t = s->edges[i];
      if (t != nullptr && t->stateNumber != INT32_MAX) {
        ss << getStateString(s);
        std::string label = getEdgeLabel(i);
        ss << "-" << label << "->" << getStateString(t) << "\n";
      }
    }
  }

  return ss.str();
}

std::string DFASerializer::getEdgeLabel(size_t i) const {
  return _vocabulary.getDisplayName(i); // ml: no longer needed -1 as we use a map for edges, without offset.
}

std::string DFASerializer::getStateString(DFAState *s) const {
  size_t n = s->stateNumber;

  const std::string baseStateStr = std::string(s->isAcceptState ? ":" : "") + "s" + std::to_string(n) +
    (s->requiresFullContext ? "^" : "");

  if (s->isAcceptState) {
    if (!s->predicates.empty()) {
      std::string buf;
      for (size_t i = 0; i < s->predicates.size(); i++) {
        buf.append(s->predicates[i].toString());
      }
      return baseStateStr + "=>" + buf;
    } else {
      return baseStateStr + "=>" + std::to_string(s->prediction);
    }
  } else {
    return baseStateStr;
  }
}