]> gitweb.ps.run Git - toc/blob - antlr4-cpp-runtime-4.9.2-source/runtime/src/dfa/DFASerializer.cpp
add antlr source code and ReadMe
[toc] / antlr4-cpp-runtime-4.9.2-source / runtime / src / dfa / DFASerializer.cpp
1 /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2  * Use of this file is governed by the BSD 3-clause license that
3  * can be found in the LICENSE.txt file in the project root.
4  */
5
6 #include "dfa/DFA.h"
7 #include "Vocabulary.h"
8
9 #include "dfa/DFASerializer.h"
10
11 using namespace antlr4::dfa;
12
13 DFASerializer::DFASerializer(const DFA *dfa, const std::vector<std::string>& tokenNames)
14   : DFASerializer(dfa, Vocabulary::fromTokenNames(tokenNames)) {
15 }
16
17 DFASerializer::DFASerializer(const DFA *dfa, const Vocabulary &vocabulary) : _dfa(dfa), _vocabulary(vocabulary) {
18 }
19
20 DFASerializer::~DFASerializer() {
21 }
22
23 std::string DFASerializer::toString() const {
24   if (_dfa->s0 == nullptr) {
25     return "";
26   }
27
28   std::stringstream ss;
29   std::vector<DFAState *> states = _dfa->getStates();
30   for (auto *s : states) {
31     for (size_t i = 0; i < s->edges.size(); i++) {
32       DFAState *t = s->edges[i];
33       if (t != nullptr && t->stateNumber != INT32_MAX) {
34         ss << getStateString(s);
35         std::string label = getEdgeLabel(i);
36         ss << "-" << label << "->" << getStateString(t) << "\n";
37       }
38     }
39   }
40
41   return ss.str();
42 }
43
44 std::string DFASerializer::getEdgeLabel(size_t i) const {
45   return _vocabulary.getDisplayName(i); // ml: no longer needed -1 as we use a map for edges, without offset.
46 }
47
48 std::string DFASerializer::getStateString(DFAState *s) const {
49   size_t n = s->stateNumber;
50
51   const std::string baseStateStr = std::string(s->isAcceptState ? ":" : "") + "s" + std::to_string(n) +
52     (s->requiresFullContext ? "^" : "");
53
54   if (s->isAcceptState) {
55     if (!s->predicates.empty()) {
56       std::string buf;
57       for (size_t i = 0; i < s->predicates.size(); i++) {
58         buf.append(s->predicates[i]->toString());
59       }
60       return baseStateStr + "=>" + buf;
61     } else {
62       return baseStateStr + "=>" + std::to_string(s->prediction);
63     }
64   } else {
65     return baseStateStr;
66   }
67 }