]> gitweb.ps.run Git - toc/blob - antlr4-cpp-runtime-4.9.2-source/runtime/src/dfa/DFAState.cpp
add antlr source code and ReadMe
[toc] / antlr4-cpp-runtime-4.9.2-source / runtime / src / dfa / DFAState.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 "atn/ATNConfigSet.h"
7 #include "atn/SemanticContext.h"
8 #include "atn/ATNConfig.h"
9 #include "misc/MurmurHash.h"
10
11 #include "dfa/DFAState.h"
12
13 using namespace antlr4::dfa;
14 using namespace antlr4::atn;
15
16 DFAState::PredPrediction::PredPrediction(const Ref<SemanticContext> &pred, int alt) : pred(pred) {
17   InitializeInstanceFields();
18   this->alt = alt;
19 }
20
21 DFAState::PredPrediction::~PredPrediction() {
22 }
23
24 std::string DFAState::PredPrediction::toString() {
25   return std::string("(") + pred->toString() + ", " + std::to_string(alt) + ")";
26 }
27
28 void DFAState::PredPrediction::InitializeInstanceFields() {
29   alt = 0;
30 }
31
32 DFAState::DFAState() {
33   InitializeInstanceFields();
34 }
35
36 DFAState::DFAState(int state) : DFAState() {
37   stateNumber = state;
38 }
39
40 DFAState::DFAState(std::unique_ptr<ATNConfigSet> configs_) : DFAState() {
41   configs = std::move(configs_);
42 }
43
44 DFAState::~DFAState() {
45   for (auto *predicate : predicates) {
46     delete predicate;
47   }
48 }
49
50 std::set<size_t> DFAState::getAltSet() {
51   std::set<size_t> alts;
52   if (configs != nullptr) {
53     for (size_t i = 0; i < configs->size(); i++) {
54       alts.insert(configs->get(i)->alt);
55     }
56   }
57   return alts;
58 }
59
60 size_t DFAState::hashCode() const {
61   size_t hash = misc::MurmurHash::initialize(7);
62   hash = misc::MurmurHash::update(hash, configs->hashCode());
63   hash = misc::MurmurHash::finish(hash, 1);
64   return hash;
65 }
66
67 bool DFAState::operator == (const DFAState &o) const {
68   // compare set of ATN configurations in this set with other
69   if (this == &o) {
70     return true;
71   }
72
73   return *configs == *o.configs;
74 }
75
76 std::string DFAState::toString() {
77   std::stringstream ss;
78   ss << stateNumber;
79   if (configs) {
80     ss << ":" << configs->toString();
81   }
82   if (isAcceptState) {
83     ss << " => ";
84     if (!predicates.empty()) {
85       for (size_t i = 0; i < predicates.size(); i++) {
86         ss << predicates[i]->toString();
87       }
88     } else {
89       ss << prediction;
90     }
91   }
92   return ss.str();
93 }
94
95 void DFAState::InitializeInstanceFields() {
96   stateNumber = -1;
97   isAcceptState = false;
98   prediction = 0;
99   requiresFullContext = false;
100 }